babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322
  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 result = new Vector3(0, 0, 0);
  923. Vector3.LerpToRef(start, end, amount, result);
  924. return result;
  925. };
  926. Vector3.LerpToRef = function (start, end, amount, result) {
  927. result.x = start.x + ((end.x - start.x) * amount);
  928. result.y = start.y + ((end.y - start.y) * amount);
  929. result.z = start.z + ((end.z - start.z) * amount);
  930. };
  931. Vector3.Dot = function (left, right) {
  932. return (left.x * right.x + left.y * right.y + left.z * right.z);
  933. };
  934. Vector3.Cross = function (left, right) {
  935. var result = Vector3.Zero();
  936. Vector3.CrossToRef(left, right, result);
  937. return result;
  938. };
  939. Vector3.CrossToRef = function (left, right, result) {
  940. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  941. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  942. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  943. result.copyFrom(Tmp.Vector3[0]);
  944. };
  945. Vector3.Normalize = function (vector) {
  946. var result = Vector3.Zero();
  947. Vector3.NormalizeToRef(vector, result);
  948. return result;
  949. };
  950. Vector3.NormalizeToRef = function (vector, result) {
  951. result.copyFrom(vector);
  952. result.normalize();
  953. };
  954. Vector3.Project = function (vector, world, transform, viewport) {
  955. var cw = viewport.width;
  956. var ch = viewport.height;
  957. var cx = viewport.x;
  958. var cy = viewport.y;
  959. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  960. 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);
  961. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  962. world.multiplyToRef(transform, matrix);
  963. matrix.multiplyToRef(viewportMatrix, matrix);
  964. return Vector3.TransformCoordinates(vector, matrix);
  965. };
  966. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  967. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  968. world.multiplyToRef(transform, matrix);
  969. matrix.invert();
  970. source.x = source.x / viewportWidth * 2 - 1;
  971. source.y = -(source.y / viewportHeight * 2 - 1);
  972. var vector = Vector3.TransformCoordinates(source, matrix);
  973. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  974. if (MathTools.WithinEpsilon(num, 1.0)) {
  975. vector = vector.scale(1.0 / num);
  976. }
  977. return vector;
  978. };
  979. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  980. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  981. world.multiplyToRef(view, matrix);
  982. matrix.multiplyToRef(projection, matrix);
  983. matrix.invert();
  984. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  985. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  986. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  987. if (MathTools.WithinEpsilon(num, 1.0)) {
  988. vector = vector.scale(1.0 / num);
  989. }
  990. return vector;
  991. };
  992. Vector3.Minimize = function (left, right) {
  993. var min = left.clone();
  994. min.MinimizeInPlace(right);
  995. return min;
  996. };
  997. Vector3.Maximize = function (left, right) {
  998. var max = left.clone();
  999. max.MaximizeInPlace(right);
  1000. return max;
  1001. };
  1002. Vector3.Distance = function (value1, value2) {
  1003. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1004. };
  1005. Vector3.DistanceSquared = function (value1, value2) {
  1006. var x = value1.x - value2.x;
  1007. var y = value1.y - value2.y;
  1008. var z = value1.z - value2.z;
  1009. return (x * x) + (y * y) + (z * z);
  1010. };
  1011. Vector3.Center = function (value1, value2) {
  1012. var center = value1.add(value2);
  1013. center.scaleInPlace(0.5);
  1014. return center;
  1015. };
  1016. /**
  1017. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1018. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1019. * to something in order to rotate it from its local system to the given target system.
  1020. */
  1021. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1022. var rotation = Vector3.Zero();
  1023. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1024. return rotation;
  1025. };
  1026. /**
  1027. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1028. */
  1029. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1030. var u = axis1.normalize();
  1031. var w = axis3.normalize();
  1032. // world axis
  1033. var X = Axis.X;
  1034. var Y = Axis.Y;
  1035. // equation unknowns and vars
  1036. var yaw = 0.0;
  1037. var pitch = 0.0;
  1038. var roll = 0.0;
  1039. var x = 0.0;
  1040. var y = 0.0;
  1041. var z = 0.0;
  1042. var t = 0.0;
  1043. var sign = -1.0;
  1044. var nbRevert = 0;
  1045. var cross = Tmp.Vector3[0];
  1046. var dot = 0.0;
  1047. // step 1 : rotation around w
  1048. // Rv3(u) = u1, and u1 belongs to plane xOz
  1049. // Rv3(w) = w1 = w invariant
  1050. var u1 = Tmp.Vector3[1];
  1051. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1052. z = 1.0;
  1053. }
  1054. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1055. x = 1.0;
  1056. }
  1057. else {
  1058. t = w.z / w.x;
  1059. x = -t * Math.sqrt(1 / (1 + t * t));
  1060. z = Math.sqrt(1 / (1 + t * t));
  1061. }
  1062. u1.x = x;
  1063. u1.y = y;
  1064. u1.z = z;
  1065. u1.normalize();
  1066. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1067. cross.normalize();
  1068. if (Vector3.Dot(w, cross) < 0) {
  1069. sign = 1.0;
  1070. }
  1071. dot = Vector3.Dot(u, u1);
  1072. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1073. roll = Math.acos(dot) * sign;
  1074. if (Vector3.Dot(u1, X) < 0) {
  1075. roll = Math.PI + roll;
  1076. u1 = u1.scaleInPlace(-1);
  1077. nbRevert++;
  1078. }
  1079. // step 2 : rotate around u1
  1080. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1081. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1082. var w2 = Tmp.Vector3[2];
  1083. var v2 = Tmp.Vector3[3];
  1084. x = 0.0;
  1085. y = 0.0;
  1086. z = 0.0;
  1087. sign = -1.0;
  1088. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1089. x = 1.0;
  1090. }
  1091. else {
  1092. t = u1.z / u1.x;
  1093. x = -t * Math.sqrt(1 / (1 + t * t));
  1094. z = Math.sqrt(1 / (1 + t * t));
  1095. }
  1096. w2.x = x;
  1097. w2.y = y;
  1098. w2.z = z;
  1099. w2.normalize();
  1100. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1101. v2.normalize();
  1102. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1103. cross.normalize();
  1104. if (Vector3.Dot(u1, cross) < 0) {
  1105. sign = 1.0;
  1106. }
  1107. dot = Vector3.Dot(w, w2);
  1108. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1109. pitch = Math.acos(dot) * sign;
  1110. if (Vector3.Dot(v2, Y) < 0) {
  1111. pitch = Math.PI + pitch;
  1112. nbRevert++;
  1113. }
  1114. // step 3 : rotate around v2
  1115. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1116. sign = -1.0;
  1117. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1118. cross.normalize();
  1119. if (Vector3.Dot(cross, Y) < 0) {
  1120. sign = 1.0;
  1121. }
  1122. dot = Vector3.Dot(u1, X);
  1123. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1124. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1125. if (dot < 0 && nbRevert < 2) {
  1126. yaw = Math.PI + yaw;
  1127. }
  1128. ref.x = pitch;
  1129. ref.y = yaw;
  1130. ref.z = roll;
  1131. };
  1132. return Vector3;
  1133. }());
  1134. BABYLON.Vector3 = Vector3;
  1135. //Vector4 class created for EulerAngle class conversion to Quaternion
  1136. var Vector4 = (function () {
  1137. function Vector4(x, y, z, w) {
  1138. this.x = x;
  1139. this.y = y;
  1140. this.z = z;
  1141. this.w = w;
  1142. }
  1143. Vector4.prototype.toString = function () {
  1144. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1145. };
  1146. Vector4.prototype.getClassName = function () {
  1147. return "Vector4";
  1148. };
  1149. Vector4.prototype.getHashCode = function () {
  1150. var hash = this.x || 0;
  1151. hash = (hash * 397) ^ (this.y || 0);
  1152. hash = (hash * 397) ^ (this.z || 0);
  1153. hash = (hash * 397) ^ (this.w || 0);
  1154. return hash;
  1155. };
  1156. // Operators
  1157. Vector4.prototype.asArray = function () {
  1158. var result = [];
  1159. this.toArray(result, 0);
  1160. return result;
  1161. };
  1162. Vector4.prototype.toArray = function (array, index) {
  1163. if (index === undefined) {
  1164. index = 0;
  1165. }
  1166. array[index] = this.x;
  1167. array[index + 1] = this.y;
  1168. array[index + 2] = this.z;
  1169. array[index + 3] = this.w;
  1170. return this;
  1171. };
  1172. Vector4.prototype.addInPlace = function (otherVector) {
  1173. this.x += otherVector.x;
  1174. this.y += otherVector.y;
  1175. this.z += otherVector.z;
  1176. this.w += otherVector.w;
  1177. return this;
  1178. };
  1179. Vector4.prototype.add = function (otherVector) {
  1180. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1181. };
  1182. Vector4.prototype.addToRef = function (otherVector, result) {
  1183. result.x = this.x + otherVector.x;
  1184. result.y = this.y + otherVector.y;
  1185. result.z = this.z + otherVector.z;
  1186. result.w = this.w + otherVector.w;
  1187. return this;
  1188. };
  1189. Vector4.prototype.subtractInPlace = function (otherVector) {
  1190. this.x -= otherVector.x;
  1191. this.y -= otherVector.y;
  1192. this.z -= otherVector.z;
  1193. this.w -= otherVector.w;
  1194. return this;
  1195. };
  1196. Vector4.prototype.subtract = function (otherVector) {
  1197. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1198. };
  1199. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1200. result.x = this.x - otherVector.x;
  1201. result.y = this.y - otherVector.y;
  1202. result.z = this.z - otherVector.z;
  1203. result.w = this.w - otherVector.w;
  1204. return this;
  1205. };
  1206. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1207. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1208. };
  1209. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1210. result.x = this.x - x;
  1211. result.y = this.y - y;
  1212. result.z = this.z - z;
  1213. result.w = this.w - w;
  1214. return this;
  1215. };
  1216. Vector4.prototype.negate = function () {
  1217. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1218. };
  1219. Vector4.prototype.scaleInPlace = function (scale) {
  1220. this.x *= scale;
  1221. this.y *= scale;
  1222. this.z *= scale;
  1223. this.w *= scale;
  1224. return this;
  1225. };
  1226. Vector4.prototype.scale = function (scale) {
  1227. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1228. };
  1229. Vector4.prototype.scaleToRef = function (scale, result) {
  1230. result.x = this.x * scale;
  1231. result.y = this.y * scale;
  1232. result.z = this.z * scale;
  1233. result.w = this.w * scale;
  1234. };
  1235. Vector4.prototype.equals = function (otherVector) {
  1236. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1237. };
  1238. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1239. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1240. return otherVector
  1241. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1242. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1243. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1244. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1245. };
  1246. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1247. return this.x === x && this.y === y && this.z === z && this.w === w;
  1248. };
  1249. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1250. this.x *= otherVector.x;
  1251. this.y *= otherVector.y;
  1252. this.z *= otherVector.z;
  1253. this.w *= otherVector.w;
  1254. return this;
  1255. };
  1256. Vector4.prototype.multiply = function (otherVector) {
  1257. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1258. };
  1259. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1260. result.x = this.x * otherVector.x;
  1261. result.y = this.y * otherVector.y;
  1262. result.z = this.z * otherVector.z;
  1263. result.w = this.w * otherVector.w;
  1264. return this;
  1265. };
  1266. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1267. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1268. };
  1269. Vector4.prototype.divide = function (otherVector) {
  1270. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1271. };
  1272. Vector4.prototype.divideToRef = function (otherVector, result) {
  1273. result.x = this.x / otherVector.x;
  1274. result.y = this.y / otherVector.y;
  1275. result.z = this.z / otherVector.z;
  1276. result.w = this.w / otherVector.w;
  1277. return this;
  1278. };
  1279. Vector4.prototype.MinimizeInPlace = function (other) {
  1280. if (other.x < this.x)
  1281. this.x = other.x;
  1282. if (other.y < this.y)
  1283. this.y = other.y;
  1284. if (other.z < this.z)
  1285. this.z = other.z;
  1286. if (other.w < this.w)
  1287. this.w = other.w;
  1288. return this;
  1289. };
  1290. Vector4.prototype.MaximizeInPlace = function (other) {
  1291. if (other.x > this.x)
  1292. this.x = other.x;
  1293. if (other.y > this.y)
  1294. this.y = other.y;
  1295. if (other.z > this.z)
  1296. this.z = other.z;
  1297. if (other.w > this.w)
  1298. this.w = other.w;
  1299. return this;
  1300. };
  1301. // Properties
  1302. Vector4.prototype.length = function () {
  1303. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1304. };
  1305. Vector4.prototype.lengthSquared = function () {
  1306. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1307. };
  1308. // Methods
  1309. Vector4.prototype.normalize = function () {
  1310. var len = this.length();
  1311. if (len === 0)
  1312. return this;
  1313. var num = 1.0 / len;
  1314. this.x *= num;
  1315. this.y *= num;
  1316. this.z *= num;
  1317. this.w *= num;
  1318. return this;
  1319. };
  1320. Vector4.prototype.toVector3 = function () {
  1321. return new Vector3(this.x, this.y, this.z);
  1322. };
  1323. Vector4.prototype.clone = function () {
  1324. return new Vector4(this.x, this.y, this.z, this.w);
  1325. };
  1326. Vector4.prototype.copyFrom = function (source) {
  1327. this.x = source.x;
  1328. this.y = source.y;
  1329. this.z = source.z;
  1330. this.w = source.w;
  1331. return this;
  1332. };
  1333. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1334. this.x = x;
  1335. this.y = y;
  1336. this.z = z;
  1337. this.w = w;
  1338. return this;
  1339. };
  1340. // Statics
  1341. Vector4.FromArray = function (array, offset) {
  1342. if (!offset) {
  1343. offset = 0;
  1344. }
  1345. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1346. };
  1347. Vector4.FromArrayToRef = function (array, offset, result) {
  1348. result.x = array[offset];
  1349. result.y = array[offset + 1];
  1350. result.z = array[offset + 2];
  1351. result.w = array[offset + 3];
  1352. };
  1353. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1354. result.x = array[offset];
  1355. result.y = array[offset + 1];
  1356. result.z = array[offset + 2];
  1357. result.w = array[offset + 3];
  1358. };
  1359. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1360. result.x = x;
  1361. result.y = y;
  1362. result.z = z;
  1363. result.w = w;
  1364. };
  1365. Vector4.Zero = function () {
  1366. return new Vector4(0, 0, 0, 0);
  1367. };
  1368. Vector4.Normalize = function (vector) {
  1369. var result = Vector4.Zero();
  1370. Vector4.NormalizeToRef(vector, result);
  1371. return result;
  1372. };
  1373. Vector4.NormalizeToRef = function (vector, result) {
  1374. result.copyFrom(vector);
  1375. result.normalize();
  1376. };
  1377. Vector4.Minimize = function (left, right) {
  1378. var min = left.clone();
  1379. min.MinimizeInPlace(right);
  1380. return min;
  1381. };
  1382. Vector4.Maximize = function (left, right) {
  1383. var max = left.clone();
  1384. max.MaximizeInPlace(right);
  1385. return max;
  1386. };
  1387. Vector4.Distance = function (value1, value2) {
  1388. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1389. };
  1390. Vector4.DistanceSquared = function (value1, value2) {
  1391. var x = value1.x - value2.x;
  1392. var y = value1.y - value2.y;
  1393. var z = value1.z - value2.z;
  1394. var w = value1.w - value2.w;
  1395. return (x * x) + (y * y) + (z * z) + (w * w);
  1396. };
  1397. Vector4.Center = function (value1, value2) {
  1398. var center = value1.add(value2);
  1399. center.scaleInPlace(0.5);
  1400. return center;
  1401. };
  1402. return Vector4;
  1403. }());
  1404. BABYLON.Vector4 = Vector4;
  1405. var Size = (function () {
  1406. function Size(width, height) {
  1407. this.width = width;
  1408. this.height = height;
  1409. }
  1410. Size.prototype.toString = function () {
  1411. return "{W: " + this.width + ", H: " + this.height + "}";
  1412. };
  1413. Size.prototype.getClassName = function () {
  1414. return "Size";
  1415. };
  1416. Size.prototype.getHashCode = function () {
  1417. var hash = this.width || 0;
  1418. hash = (hash * 397) ^ (this.height || 0);
  1419. return hash;
  1420. };
  1421. Size.prototype.copyFrom = function (src) {
  1422. this.width = src.width;
  1423. this.height = src.height;
  1424. };
  1425. Size.prototype.copyFromFloats = function (width, height) {
  1426. this.width = width;
  1427. this.height = height;
  1428. };
  1429. Size.prototype.multiplyByFloats = function (w, h) {
  1430. return new Size(this.width * w, this.height * h);
  1431. };
  1432. Size.prototype.clone = function () {
  1433. return new Size(this.width, this.height);
  1434. };
  1435. Size.prototype.equals = function (other) {
  1436. if (!other) {
  1437. return false;
  1438. }
  1439. return (this.width === other.width) && (this.height === other.height);
  1440. };
  1441. Object.defineProperty(Size.prototype, "surface", {
  1442. get: function () {
  1443. return this.width * this.height;
  1444. },
  1445. enumerable: true,
  1446. configurable: true
  1447. });
  1448. Size.Zero = function () {
  1449. return new Size(0, 0);
  1450. };
  1451. Size.prototype.add = function (otherSize) {
  1452. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1453. return r;
  1454. };
  1455. Size.prototype.substract = function (otherSize) {
  1456. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1457. return r;
  1458. };
  1459. Size.Lerp = function (start, end, amount) {
  1460. var w = start.width + ((end.width - start.width) * amount);
  1461. var h = start.height + ((end.height - start.height) * amount);
  1462. return new Size(w, h);
  1463. };
  1464. return Size;
  1465. }());
  1466. BABYLON.Size = Size;
  1467. var Quaternion = (function () {
  1468. function Quaternion(x, y, z, w) {
  1469. if (x === void 0) { x = 0; }
  1470. if (y === void 0) { y = 0; }
  1471. if (z === void 0) { z = 0; }
  1472. if (w === void 0) { w = 1; }
  1473. this.x = x;
  1474. this.y = y;
  1475. this.z = z;
  1476. this.w = w;
  1477. }
  1478. Quaternion.prototype.toString = function () {
  1479. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1480. };
  1481. Quaternion.prototype.getClassName = function () {
  1482. return "Quaternion";
  1483. };
  1484. Quaternion.prototype.getHashCode = function () {
  1485. var hash = this.x || 0;
  1486. hash = (hash * 397) ^ (this.y || 0);
  1487. hash = (hash * 397) ^ (this.z || 0);
  1488. hash = (hash * 397) ^ (this.w || 0);
  1489. return hash;
  1490. };
  1491. Quaternion.prototype.asArray = function () {
  1492. return [this.x, this.y, this.z, this.w];
  1493. };
  1494. Quaternion.prototype.equals = function (otherQuaternion) {
  1495. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1496. };
  1497. Quaternion.prototype.clone = function () {
  1498. return new Quaternion(this.x, this.y, this.z, this.w);
  1499. };
  1500. Quaternion.prototype.copyFrom = function (other) {
  1501. this.x = other.x;
  1502. this.y = other.y;
  1503. this.z = other.z;
  1504. this.w = other.w;
  1505. return this;
  1506. };
  1507. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1508. this.x = x;
  1509. this.y = y;
  1510. this.z = z;
  1511. this.w = w;
  1512. return this;
  1513. };
  1514. Quaternion.prototype.add = function (other) {
  1515. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1516. };
  1517. Quaternion.prototype.subtract = function (other) {
  1518. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1519. };
  1520. Quaternion.prototype.scale = function (value) {
  1521. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1522. };
  1523. Quaternion.prototype.multiply = function (q1) {
  1524. var result = new Quaternion(0, 0, 0, 1.0);
  1525. this.multiplyToRef(q1, result);
  1526. return result;
  1527. };
  1528. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1529. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1530. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1531. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1532. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1533. result.copyFromFloats(x, y, z, w);
  1534. return this;
  1535. };
  1536. Quaternion.prototype.multiplyInPlace = function (q1) {
  1537. this.multiplyToRef(q1, this);
  1538. return this;
  1539. };
  1540. Quaternion.prototype.conjugateToRef = function (ref) {
  1541. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1542. return this;
  1543. };
  1544. Quaternion.prototype.conjugateInPlace = function () {
  1545. this.x *= -1;
  1546. this.y *= -1;
  1547. this.z *= -1;
  1548. return this;
  1549. };
  1550. Quaternion.prototype.conjugate = function () {
  1551. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1552. return result;
  1553. };
  1554. Quaternion.prototype.length = function () {
  1555. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1556. };
  1557. Quaternion.prototype.normalize = function () {
  1558. var length = 1.0 / this.length();
  1559. this.x *= length;
  1560. this.y *= length;
  1561. this.z *= length;
  1562. this.w *= length;
  1563. return this;
  1564. };
  1565. Quaternion.prototype.toEulerAngles = function (order) {
  1566. if (order === void 0) { order = "YZX"; }
  1567. var result = Vector3.Zero();
  1568. this.toEulerAnglesToRef(result, order);
  1569. return result;
  1570. };
  1571. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1572. if (order === void 0) { order = "YZX"; }
  1573. var qz = this.z;
  1574. var qx = this.x;
  1575. var qy = this.y;
  1576. var qw = this.w;
  1577. var sqw = qw * qw;
  1578. var sqz = qz * qz;
  1579. var sqx = qx * qx;
  1580. var sqy = qy * qy;
  1581. var zAxisY = qy * qz - qx * qw;
  1582. var limit = .4999999;
  1583. if (zAxisY < -limit) {
  1584. result.y = 2 * Math.atan2(qy, qw);
  1585. result.x = Math.PI / 2;
  1586. result.z = 0;
  1587. }
  1588. else if (zAxisY > limit) {
  1589. result.y = 2 * Math.atan2(qy, qw);
  1590. result.x = -Math.PI / 2;
  1591. result.z = 0;
  1592. }
  1593. else {
  1594. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  1595. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  1596. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  1597. }
  1598. return this;
  1599. };
  1600. Quaternion.prototype.toRotationMatrix = function (result) {
  1601. var xx = this.x * this.x;
  1602. var yy = this.y * this.y;
  1603. var zz = this.z * this.z;
  1604. var xy = this.x * this.y;
  1605. var zw = this.z * this.w;
  1606. var zx = this.z * this.x;
  1607. var yw = this.y * this.w;
  1608. var yz = this.y * this.z;
  1609. var xw = this.x * this.w;
  1610. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1611. result.m[1] = 2.0 * (xy + zw);
  1612. result.m[2] = 2.0 * (zx - yw);
  1613. result.m[3] = 0;
  1614. result.m[4] = 2.0 * (xy - zw);
  1615. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1616. result.m[6] = 2.0 * (yz + xw);
  1617. result.m[7] = 0;
  1618. result.m[8] = 2.0 * (zx + yw);
  1619. result.m[9] = 2.0 * (yz - xw);
  1620. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1621. result.m[11] = 0;
  1622. result.m[12] = 0;
  1623. result.m[13] = 0;
  1624. result.m[14] = 0;
  1625. result.m[15] = 1.0;
  1626. return this;
  1627. };
  1628. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1629. Quaternion.FromRotationMatrixToRef(matrix, this);
  1630. return this;
  1631. };
  1632. // Statics
  1633. Quaternion.FromRotationMatrix = function (matrix) {
  1634. var result = new Quaternion();
  1635. Quaternion.FromRotationMatrixToRef(matrix, result);
  1636. return result;
  1637. };
  1638. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1639. var data = matrix.m;
  1640. var m11 = data[0], m12 = data[4], m13 = data[8];
  1641. var m21 = data[1], m22 = data[5], m23 = data[9];
  1642. var m31 = data[2], m32 = data[6], m33 = data[10];
  1643. var trace = m11 + m22 + m33;
  1644. var s;
  1645. if (trace > 0) {
  1646. s = 0.5 / Math.sqrt(trace + 1.0);
  1647. result.w = 0.25 / s;
  1648. result.x = (m32 - m23) * s;
  1649. result.y = (m13 - m31) * s;
  1650. result.z = (m21 - m12) * s;
  1651. }
  1652. else if (m11 > m22 && m11 > m33) {
  1653. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1654. result.w = (m32 - m23) / s;
  1655. result.x = 0.25 * s;
  1656. result.y = (m12 + m21) / s;
  1657. result.z = (m13 + m31) / s;
  1658. }
  1659. else if (m22 > m33) {
  1660. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1661. result.w = (m13 - m31) / s;
  1662. result.x = (m12 + m21) / s;
  1663. result.y = 0.25 * s;
  1664. result.z = (m23 + m32) / s;
  1665. }
  1666. else {
  1667. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1668. result.w = (m21 - m12) / s;
  1669. result.x = (m13 + m31) / s;
  1670. result.y = (m23 + m32) / s;
  1671. result.z = 0.25 * s;
  1672. }
  1673. };
  1674. Quaternion.Inverse = function (q) {
  1675. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1676. };
  1677. Quaternion.Identity = function () {
  1678. return new Quaternion(0, 0, 0, 1);
  1679. };
  1680. Quaternion.RotationAxis = function (axis, angle) {
  1681. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1682. };
  1683. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1684. var sin = Math.sin(angle / 2);
  1685. axis.normalize();
  1686. result.w = Math.cos(angle / 2);
  1687. result.x = axis.x * sin;
  1688. result.y = axis.y * sin;
  1689. result.z = axis.z * sin;
  1690. return result;
  1691. };
  1692. Quaternion.FromArray = function (array, offset) {
  1693. if (!offset) {
  1694. offset = 0;
  1695. }
  1696. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1697. };
  1698. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1699. var q = new Quaternion();
  1700. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1701. return q;
  1702. };
  1703. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1704. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1705. var halfRoll = roll * 0.5;
  1706. var halfPitch = pitch * 0.5;
  1707. var halfYaw = yaw * 0.5;
  1708. var sinRoll = Math.sin(halfRoll);
  1709. var cosRoll = Math.cos(halfRoll);
  1710. var sinPitch = Math.sin(halfPitch);
  1711. var cosPitch = Math.cos(halfPitch);
  1712. var sinYaw = Math.sin(halfYaw);
  1713. var cosYaw = Math.cos(halfYaw);
  1714. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1715. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1716. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1717. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1718. };
  1719. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1720. var result = new Quaternion();
  1721. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1722. return result;
  1723. };
  1724. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1725. // Produces a quaternion from Euler angles in the z-x-z orientation
  1726. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1727. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1728. var halfBeta = beta * 0.5;
  1729. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1730. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1731. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1732. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1733. };
  1734. Quaternion.Slerp = function (left, right, amount) {
  1735. var result = Quaternion.Identity();
  1736. Quaternion.SlerpToRef(left, right, amount, result);
  1737. return result;
  1738. };
  1739. Quaternion.SlerpToRef = function (left, right, amount, result) {
  1740. var num2;
  1741. var num3;
  1742. var num = amount;
  1743. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1744. var flag = false;
  1745. if (num4 < 0) {
  1746. flag = true;
  1747. num4 = -num4;
  1748. }
  1749. if (num4 > 0.999999) {
  1750. num3 = 1 - num;
  1751. num2 = flag ? -num : num;
  1752. }
  1753. else {
  1754. var num5 = Math.acos(num4);
  1755. var num6 = (1.0 / Math.sin(num5));
  1756. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1757. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1758. }
  1759. result.x = (num3 * left.x) + (num2 * right.x);
  1760. result.y = (num3 * left.y) + (num2 * right.y);
  1761. result.z = (num3 * left.z) + (num2 * right.z);
  1762. result.w = (num3 * left.w) + (num2 * right.w);
  1763. };
  1764. return Quaternion;
  1765. }());
  1766. BABYLON.Quaternion = Quaternion;
  1767. var Matrix = (function () {
  1768. function Matrix() {
  1769. this.m = new Float32Array(16);
  1770. }
  1771. // Properties
  1772. Matrix.prototype.isIdentity = function () {
  1773. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1774. return false;
  1775. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1776. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1777. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1778. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1779. return false;
  1780. return true;
  1781. };
  1782. Matrix.prototype.determinant = function () {
  1783. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1784. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1785. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1786. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1787. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1788. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1789. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1790. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1791. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1792. };
  1793. // Methods
  1794. Matrix.prototype.toArray = function () {
  1795. return this.m;
  1796. };
  1797. Matrix.prototype.asArray = function () {
  1798. return this.toArray();
  1799. };
  1800. Matrix.prototype.invert = function () {
  1801. this.invertToRef(this);
  1802. return this;
  1803. };
  1804. Matrix.prototype.reset = function () {
  1805. for (var index = 0; index < 16; index++) {
  1806. this.m[index] = 0;
  1807. }
  1808. return this;
  1809. };
  1810. Matrix.prototype.add = function (other) {
  1811. var result = new Matrix();
  1812. this.addToRef(other, result);
  1813. return result;
  1814. };
  1815. Matrix.prototype.addToRef = function (other, result) {
  1816. for (var index = 0; index < 16; index++) {
  1817. result.m[index] = this.m[index] + other.m[index];
  1818. }
  1819. return this;
  1820. };
  1821. Matrix.prototype.addToSelf = function (other) {
  1822. for (var index = 0; index < 16; index++) {
  1823. this.m[index] += other.m[index];
  1824. }
  1825. return this;
  1826. };
  1827. Matrix.prototype.invertToRef = function (other) {
  1828. var l1 = this.m[0];
  1829. var l2 = this.m[1];
  1830. var l3 = this.m[2];
  1831. var l4 = this.m[3];
  1832. var l5 = this.m[4];
  1833. var l6 = this.m[5];
  1834. var l7 = this.m[6];
  1835. var l8 = this.m[7];
  1836. var l9 = this.m[8];
  1837. var l10 = this.m[9];
  1838. var l11 = this.m[10];
  1839. var l12 = this.m[11];
  1840. var l13 = this.m[12];
  1841. var l14 = this.m[13];
  1842. var l15 = this.m[14];
  1843. var l16 = this.m[15];
  1844. var l17 = (l11 * l16) - (l12 * l15);
  1845. var l18 = (l10 * l16) - (l12 * l14);
  1846. var l19 = (l10 * l15) - (l11 * l14);
  1847. var l20 = (l9 * l16) - (l12 * l13);
  1848. var l21 = (l9 * l15) - (l11 * l13);
  1849. var l22 = (l9 * l14) - (l10 * l13);
  1850. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1851. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1852. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1853. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1854. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1855. var l28 = (l7 * l16) - (l8 * l15);
  1856. var l29 = (l6 * l16) - (l8 * l14);
  1857. var l30 = (l6 * l15) - (l7 * l14);
  1858. var l31 = (l5 * l16) - (l8 * l13);
  1859. var l32 = (l5 * l15) - (l7 * l13);
  1860. var l33 = (l5 * l14) - (l6 * l13);
  1861. var l34 = (l7 * l12) - (l8 * l11);
  1862. var l35 = (l6 * l12) - (l8 * l10);
  1863. var l36 = (l6 * l11) - (l7 * l10);
  1864. var l37 = (l5 * l12) - (l8 * l9);
  1865. var l38 = (l5 * l11) - (l7 * l9);
  1866. var l39 = (l5 * l10) - (l6 * l9);
  1867. other.m[0] = l23 * l27;
  1868. other.m[4] = l24 * l27;
  1869. other.m[8] = l25 * l27;
  1870. other.m[12] = l26 * l27;
  1871. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1872. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1873. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1874. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1875. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1876. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1877. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1878. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1879. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1880. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1881. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1882. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1883. return this;
  1884. };
  1885. Matrix.prototype.setTranslation = function (vector3) {
  1886. this.m[12] = vector3.x;
  1887. this.m[13] = vector3.y;
  1888. this.m[14] = vector3.z;
  1889. return this;
  1890. };
  1891. Matrix.prototype.getTranslation = function () {
  1892. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1893. };
  1894. Matrix.prototype.multiply = function (other) {
  1895. var result = new Matrix();
  1896. this.multiplyToRef(other, result);
  1897. return result;
  1898. };
  1899. Matrix.prototype.copyFrom = function (other) {
  1900. for (var index = 0; index < 16; index++) {
  1901. this.m[index] = other.m[index];
  1902. }
  1903. return this;
  1904. };
  1905. Matrix.prototype.copyToArray = function (array, offset) {
  1906. if (offset === void 0) { offset = 0; }
  1907. for (var index = 0; index < 16; index++) {
  1908. array[offset + index] = this.m[index];
  1909. }
  1910. return this;
  1911. };
  1912. Matrix.prototype.multiplyToRef = function (other, result) {
  1913. this.multiplyToArray(other, result.m, 0);
  1914. return this;
  1915. };
  1916. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1917. var tm0 = this.m[0];
  1918. var tm1 = this.m[1];
  1919. var tm2 = this.m[2];
  1920. var tm3 = this.m[3];
  1921. var tm4 = this.m[4];
  1922. var tm5 = this.m[5];
  1923. var tm6 = this.m[6];
  1924. var tm7 = this.m[7];
  1925. var tm8 = this.m[8];
  1926. var tm9 = this.m[9];
  1927. var tm10 = this.m[10];
  1928. var tm11 = this.m[11];
  1929. var tm12 = this.m[12];
  1930. var tm13 = this.m[13];
  1931. var tm14 = this.m[14];
  1932. var tm15 = this.m[15];
  1933. var om0 = other.m[0];
  1934. var om1 = other.m[1];
  1935. var om2 = other.m[2];
  1936. var om3 = other.m[3];
  1937. var om4 = other.m[4];
  1938. var om5 = other.m[5];
  1939. var om6 = other.m[6];
  1940. var om7 = other.m[7];
  1941. var om8 = other.m[8];
  1942. var om9 = other.m[9];
  1943. var om10 = other.m[10];
  1944. var om11 = other.m[11];
  1945. var om12 = other.m[12];
  1946. var om13 = other.m[13];
  1947. var om14 = other.m[14];
  1948. var om15 = other.m[15];
  1949. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1950. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1951. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1952. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1953. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1954. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1955. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1956. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1957. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1958. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1959. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1960. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1961. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1962. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1963. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1964. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1965. return this;
  1966. };
  1967. Matrix.prototype.equals = function (value) {
  1968. return value &&
  1969. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1970. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1971. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1972. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1973. };
  1974. Matrix.prototype.clone = function () {
  1975. 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]);
  1976. };
  1977. Matrix.prototype.getClassName = function () {
  1978. return "Matrix";
  1979. };
  1980. Matrix.prototype.getHashCode = function () {
  1981. var hash = this.m[0] || 0;
  1982. for (var i = 1; i < 16; i++) {
  1983. hash = (hash * 397) ^ (this.m[i] || 0);
  1984. }
  1985. return hash;
  1986. };
  1987. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1988. translation.x = this.m[12];
  1989. translation.y = this.m[13];
  1990. translation.z = this.m[14];
  1991. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1992. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1993. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1994. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1995. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1996. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1997. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1998. rotation.x = 0;
  1999. rotation.y = 0;
  2000. rotation.z = 0;
  2001. rotation.w = 1;
  2002. return false;
  2003. }
  2004. 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]);
  2005. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  2006. return true;
  2007. };
  2008. Matrix.prototype.getRotationMatrix = function () {
  2009. var result = Matrix.Identity();
  2010. this.getRotationMatrixToRef(result);
  2011. return result;
  2012. };
  2013. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2014. var m = this.m;
  2015. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2016. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2017. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2018. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2019. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2020. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2021. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  2022. };
  2023. // Statics
  2024. Matrix.FromArray = function (array, offset) {
  2025. var result = new Matrix();
  2026. if (!offset) {
  2027. offset = 0;
  2028. }
  2029. Matrix.FromArrayToRef(array, offset, result);
  2030. return result;
  2031. };
  2032. Matrix.FromArrayToRef = function (array, offset, result) {
  2033. for (var index = 0; index < 16; index++) {
  2034. result.m[index] = array[index + offset];
  2035. }
  2036. };
  2037. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2038. for (var index = 0; index < 16; index++) {
  2039. result.m[index] = array[index + offset] * scale;
  2040. }
  2041. };
  2042. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2043. result.m[0] = initialM11;
  2044. result.m[1] = initialM12;
  2045. result.m[2] = initialM13;
  2046. result.m[3] = initialM14;
  2047. result.m[4] = initialM21;
  2048. result.m[5] = initialM22;
  2049. result.m[6] = initialM23;
  2050. result.m[7] = initialM24;
  2051. result.m[8] = initialM31;
  2052. result.m[9] = initialM32;
  2053. result.m[10] = initialM33;
  2054. result.m[11] = initialM34;
  2055. result.m[12] = initialM41;
  2056. result.m[13] = initialM42;
  2057. result.m[14] = initialM43;
  2058. result.m[15] = initialM44;
  2059. };
  2060. Matrix.prototype.getRow = function (index) {
  2061. if (index < 0 || index > 3) {
  2062. return null;
  2063. }
  2064. var i = index * 4;
  2065. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2066. };
  2067. Matrix.prototype.setRow = function (index, row) {
  2068. if (index < 0 || index > 3) {
  2069. return this;
  2070. }
  2071. var i = index * 4;
  2072. this.m[i + 0] = row.x;
  2073. this.m[i + 1] = row.y;
  2074. this.m[i + 2] = row.z;
  2075. this.m[i + 3] = row.w;
  2076. return this;
  2077. };
  2078. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2079. var result = new Matrix();
  2080. result.m[0] = initialM11;
  2081. result.m[1] = initialM12;
  2082. result.m[2] = initialM13;
  2083. result.m[3] = initialM14;
  2084. result.m[4] = initialM21;
  2085. result.m[5] = initialM22;
  2086. result.m[6] = initialM23;
  2087. result.m[7] = initialM24;
  2088. result.m[8] = initialM31;
  2089. result.m[9] = initialM32;
  2090. result.m[10] = initialM33;
  2091. result.m[11] = initialM34;
  2092. result.m[12] = initialM41;
  2093. result.m[13] = initialM42;
  2094. result.m[14] = initialM43;
  2095. result.m[15] = initialM44;
  2096. return result;
  2097. };
  2098. Matrix.Compose = function (scale, rotation, translation) {
  2099. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2100. var rotationMatrix = Matrix.Identity();
  2101. rotation.toRotationMatrix(rotationMatrix);
  2102. result = result.multiply(rotationMatrix);
  2103. result.setTranslation(translation);
  2104. return result;
  2105. };
  2106. Matrix.Identity = function () {
  2107. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2108. };
  2109. Matrix.IdentityToRef = function (result) {
  2110. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2111. };
  2112. Matrix.Zero = function () {
  2113. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2114. };
  2115. Matrix.RotationX = function (angle) {
  2116. var result = new Matrix();
  2117. Matrix.RotationXToRef(angle, result);
  2118. return result;
  2119. };
  2120. Matrix.Invert = function (source) {
  2121. var result = new Matrix();
  2122. source.invertToRef(result);
  2123. return result;
  2124. };
  2125. Matrix.RotationXToRef = function (angle, result) {
  2126. var s = Math.sin(angle);
  2127. var c = Math.cos(angle);
  2128. result.m[0] = 1.0;
  2129. result.m[15] = 1.0;
  2130. result.m[5] = c;
  2131. result.m[10] = c;
  2132. result.m[9] = -s;
  2133. result.m[6] = s;
  2134. result.m[1] = 0;
  2135. result.m[2] = 0;
  2136. result.m[3] = 0;
  2137. result.m[4] = 0;
  2138. result.m[7] = 0;
  2139. result.m[8] = 0;
  2140. result.m[11] = 0;
  2141. result.m[12] = 0;
  2142. result.m[13] = 0;
  2143. result.m[14] = 0;
  2144. };
  2145. Matrix.RotationY = function (angle) {
  2146. var result = new Matrix();
  2147. Matrix.RotationYToRef(angle, result);
  2148. return result;
  2149. };
  2150. Matrix.RotationYToRef = function (angle, result) {
  2151. var s = Math.sin(angle);
  2152. var c = Math.cos(angle);
  2153. result.m[5] = 1.0;
  2154. result.m[15] = 1.0;
  2155. result.m[0] = c;
  2156. result.m[2] = -s;
  2157. result.m[8] = s;
  2158. result.m[10] = c;
  2159. result.m[1] = 0;
  2160. result.m[3] = 0;
  2161. result.m[4] = 0;
  2162. result.m[6] = 0;
  2163. result.m[7] = 0;
  2164. result.m[9] = 0;
  2165. result.m[11] = 0;
  2166. result.m[12] = 0;
  2167. result.m[13] = 0;
  2168. result.m[14] = 0;
  2169. };
  2170. Matrix.RotationZ = function (angle) {
  2171. var result = new Matrix();
  2172. Matrix.RotationZToRef(angle, result);
  2173. return result;
  2174. };
  2175. Matrix.RotationZToRef = function (angle, result) {
  2176. var s = Math.sin(angle);
  2177. var c = Math.cos(angle);
  2178. result.m[10] = 1.0;
  2179. result.m[15] = 1.0;
  2180. result.m[0] = c;
  2181. result.m[1] = s;
  2182. result.m[4] = -s;
  2183. result.m[5] = c;
  2184. result.m[2] = 0;
  2185. result.m[3] = 0;
  2186. result.m[6] = 0;
  2187. result.m[7] = 0;
  2188. result.m[8] = 0;
  2189. result.m[9] = 0;
  2190. result.m[11] = 0;
  2191. result.m[12] = 0;
  2192. result.m[13] = 0;
  2193. result.m[14] = 0;
  2194. };
  2195. Matrix.RotationAxis = function (axis, angle) {
  2196. var result = Matrix.Zero();
  2197. Matrix.RotationAxisToRef(axis, angle, result);
  2198. return result;
  2199. };
  2200. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2201. var s = Math.sin(-angle);
  2202. var c = Math.cos(-angle);
  2203. var c1 = 1 - c;
  2204. axis.normalize();
  2205. result.m[0] = (axis.x * axis.x) * c1 + c;
  2206. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2207. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2208. result.m[3] = 0.0;
  2209. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2210. result.m[5] = (axis.y * axis.y) * c1 + c;
  2211. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2212. result.m[7] = 0.0;
  2213. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2214. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2215. result.m[10] = (axis.z * axis.z) * c1 + c;
  2216. result.m[11] = 0.0;
  2217. result.m[15] = 1.0;
  2218. };
  2219. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2220. var result = new Matrix();
  2221. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2222. return result;
  2223. };
  2224. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2225. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2226. this._tempQuaternion.toRotationMatrix(result);
  2227. };
  2228. Matrix.Scaling = function (x, y, z) {
  2229. var result = Matrix.Zero();
  2230. Matrix.ScalingToRef(x, y, z, result);
  2231. return result;
  2232. };
  2233. Matrix.ScalingToRef = function (x, y, z, result) {
  2234. result.m[0] = x;
  2235. result.m[1] = 0;
  2236. result.m[2] = 0;
  2237. result.m[3] = 0;
  2238. result.m[4] = 0;
  2239. result.m[5] = y;
  2240. result.m[6] = 0;
  2241. result.m[7] = 0;
  2242. result.m[8] = 0;
  2243. result.m[9] = 0;
  2244. result.m[10] = z;
  2245. result.m[11] = 0;
  2246. result.m[12] = 0;
  2247. result.m[13] = 0;
  2248. result.m[14] = 0;
  2249. result.m[15] = 1.0;
  2250. };
  2251. Matrix.Translation = function (x, y, z) {
  2252. var result = Matrix.Identity();
  2253. Matrix.TranslationToRef(x, y, z, result);
  2254. return result;
  2255. };
  2256. Matrix.TranslationToRef = function (x, y, z, result) {
  2257. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2258. };
  2259. Matrix.Lerp = function (startValue, endValue, gradient) {
  2260. var result = Matrix.Zero();
  2261. for (var index = 0; index < 16; index++) {
  2262. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2263. }
  2264. return result;
  2265. };
  2266. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2267. var startScale = new Vector3(0, 0, 0);
  2268. var startRotation = new Quaternion();
  2269. var startTranslation = new Vector3(0, 0, 0);
  2270. startValue.decompose(startScale, startRotation, startTranslation);
  2271. var endScale = new Vector3(0, 0, 0);
  2272. var endRotation = new Quaternion();
  2273. var endTranslation = new Vector3(0, 0, 0);
  2274. endValue.decompose(endScale, endRotation, endTranslation);
  2275. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2276. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2277. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2278. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2279. };
  2280. Matrix.LookAtLH = function (eye, target, up) {
  2281. var result = Matrix.Zero();
  2282. Matrix.LookAtLHToRef(eye, target, up, result);
  2283. return result;
  2284. };
  2285. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2286. // Z axis
  2287. target.subtractToRef(eye, this._zAxis);
  2288. this._zAxis.normalize();
  2289. // X axis
  2290. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2291. if (this._xAxis.lengthSquared() === 0) {
  2292. this._xAxis.x = 1.0;
  2293. }
  2294. else {
  2295. this._xAxis.normalize();
  2296. }
  2297. // Y axis
  2298. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2299. this._yAxis.normalize();
  2300. // Eye angles
  2301. var ex = -Vector3.Dot(this._xAxis, eye);
  2302. var ey = -Vector3.Dot(this._yAxis, eye);
  2303. var ez = -Vector3.Dot(this._zAxis, eye);
  2304. 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);
  2305. };
  2306. Matrix.LookAtRH = function (eye, target, up) {
  2307. var result = Matrix.Zero();
  2308. Matrix.LookAtRHToRef(eye, target, up, result);
  2309. return result;
  2310. };
  2311. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2312. // Z axis
  2313. eye.subtractToRef(target, this._zAxis);
  2314. this._zAxis.normalize();
  2315. // X axis
  2316. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2317. if (this._xAxis.lengthSquared() === 0) {
  2318. this._xAxis.x = 1.0;
  2319. }
  2320. else {
  2321. this._xAxis.normalize();
  2322. }
  2323. // Y axis
  2324. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2325. this._yAxis.normalize();
  2326. // Eye angles
  2327. var ex = -Vector3.Dot(this._xAxis, eye);
  2328. var ey = -Vector3.Dot(this._yAxis, eye);
  2329. var ez = -Vector3.Dot(this._zAxis, eye);
  2330. 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);
  2331. };
  2332. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2333. var matrix = Matrix.Zero();
  2334. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2335. return matrix;
  2336. };
  2337. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2338. var hw = 2.0 / width;
  2339. var hh = 2.0 / height;
  2340. var id = 1.0 / (zfar - znear);
  2341. var nid = znear / (znear - zfar);
  2342. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2343. };
  2344. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2345. var matrix = Matrix.Zero();
  2346. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2347. return matrix;
  2348. };
  2349. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2350. result.m[0] = 2.0 / (right - left);
  2351. result.m[1] = result.m[2] = result.m[3] = 0;
  2352. result.m[5] = 2.0 / (top - bottom);
  2353. result.m[4] = result.m[6] = result.m[7] = 0;
  2354. result.m[10] = 1.0 / (zfar - znear);
  2355. result.m[8] = result.m[9] = result.m[11] = 0;
  2356. result.m[12] = (left + right) / (left - right);
  2357. result.m[13] = (top + bottom) / (bottom - top);
  2358. result.m[14] = -znear / (zfar - znear);
  2359. result.m[15] = 1.0;
  2360. };
  2361. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2362. var matrix = Matrix.Zero();
  2363. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2364. return matrix;
  2365. };
  2366. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2367. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2368. result.m[10] *= -1.0;
  2369. };
  2370. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2371. var matrix = Matrix.Zero();
  2372. matrix.m[0] = (2.0 * znear) / width;
  2373. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2374. matrix.m[5] = (2.0 * znear) / height;
  2375. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2376. matrix.m[10] = -zfar / (znear - zfar);
  2377. matrix.m[8] = matrix.m[9] = 0.0;
  2378. matrix.m[11] = 1.0;
  2379. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2380. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2384. var matrix = Matrix.Zero();
  2385. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2386. return matrix;
  2387. };
  2388. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2389. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2390. var tan = 1.0 / (Math.tan(fov * 0.5));
  2391. if (isVerticalFovFixed) {
  2392. result.m[0] = tan / aspect;
  2393. }
  2394. else {
  2395. result.m[0] = tan;
  2396. }
  2397. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2398. if (isVerticalFovFixed) {
  2399. result.m[5] = tan;
  2400. }
  2401. else {
  2402. result.m[5] = tan * aspect;
  2403. }
  2404. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2405. result.m[8] = result.m[9] = 0.0;
  2406. result.m[10] = zfar / (zfar - znear);
  2407. result.m[11] = 1.0;
  2408. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2409. result.m[14] = -(znear * zfar) / (zfar - znear);
  2410. };
  2411. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2412. var matrix = Matrix.Zero();
  2413. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2414. return matrix;
  2415. };
  2416. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2417. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2418. var tan = 1.0 / (Math.tan(fov * 0.5));
  2419. if (isVerticalFovFixed) {
  2420. result.m[0] = tan / aspect;
  2421. }
  2422. else {
  2423. result.m[0] = tan;
  2424. }
  2425. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2426. if (isVerticalFovFixed) {
  2427. result.m[5] = tan;
  2428. }
  2429. else {
  2430. result.m[5] = tan * aspect;
  2431. }
  2432. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2433. result.m[8] = result.m[9] = 0.0;
  2434. result.m[10] = zfar / (znear - zfar);
  2435. result.m[11] = -1.0;
  2436. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2437. result.m[14] = (znear * zfar) / (znear - zfar);
  2438. };
  2439. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2440. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2441. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2442. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2443. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2444. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2445. var xScale = 2.0 / (leftTan + rightTan);
  2446. var yScale = 2.0 / (upTan + downTan);
  2447. result.m[0] = xScale;
  2448. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2449. result.m[5] = yScale;
  2450. result.m[6] = result.m[7] = 0.0;
  2451. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2452. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2453. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2454. result.m[10] = -zfar / (znear - zfar);
  2455. result.m[11] = 1.0;
  2456. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2457. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2458. result.m[14] = (znear * zfar) / (znear - zfar);
  2459. };
  2460. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2461. var cw = viewport.width;
  2462. var ch = viewport.height;
  2463. var cx = viewport.x;
  2464. var cy = viewport.y;
  2465. 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);
  2466. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2467. };
  2468. Matrix.GetAsMatrix2x2 = function (matrix) {
  2469. return new Float32Array([
  2470. matrix.m[0], matrix.m[1],
  2471. matrix.m[4], matrix.m[5]
  2472. ]);
  2473. };
  2474. Matrix.GetAsMatrix3x3 = function (matrix) {
  2475. return new Float32Array([
  2476. matrix.m[0], matrix.m[1], matrix.m[2],
  2477. matrix.m[4], matrix.m[5], matrix.m[6],
  2478. matrix.m[8], matrix.m[9], matrix.m[10]
  2479. ]);
  2480. };
  2481. Matrix.Transpose = function (matrix) {
  2482. var result = new Matrix();
  2483. result.m[0] = matrix.m[0];
  2484. result.m[1] = matrix.m[4];
  2485. result.m[2] = matrix.m[8];
  2486. result.m[3] = matrix.m[12];
  2487. result.m[4] = matrix.m[1];
  2488. result.m[5] = matrix.m[5];
  2489. result.m[6] = matrix.m[9];
  2490. result.m[7] = matrix.m[13];
  2491. result.m[8] = matrix.m[2];
  2492. result.m[9] = matrix.m[6];
  2493. result.m[10] = matrix.m[10];
  2494. result.m[11] = matrix.m[14];
  2495. result.m[12] = matrix.m[3];
  2496. result.m[13] = matrix.m[7];
  2497. result.m[14] = matrix.m[11];
  2498. result.m[15] = matrix.m[15];
  2499. return result;
  2500. };
  2501. Matrix.Reflection = function (plane) {
  2502. var matrix = new Matrix();
  2503. Matrix.ReflectionToRef(plane, matrix);
  2504. return matrix;
  2505. };
  2506. Matrix.ReflectionToRef = function (plane, result) {
  2507. plane.normalize();
  2508. var x = plane.normal.x;
  2509. var y = plane.normal.y;
  2510. var z = plane.normal.z;
  2511. var temp = -2 * x;
  2512. var temp2 = -2 * y;
  2513. var temp3 = -2 * z;
  2514. result.m[0] = (temp * x) + 1;
  2515. result.m[1] = temp2 * x;
  2516. result.m[2] = temp3 * x;
  2517. result.m[3] = 0.0;
  2518. result.m[4] = temp * y;
  2519. result.m[5] = (temp2 * y) + 1;
  2520. result.m[6] = temp3 * y;
  2521. result.m[7] = 0.0;
  2522. result.m[8] = temp * z;
  2523. result.m[9] = temp2 * z;
  2524. result.m[10] = (temp3 * z) + 1;
  2525. result.m[11] = 0.0;
  2526. result.m[12] = temp * plane.d;
  2527. result.m[13] = temp2 * plane.d;
  2528. result.m[14] = temp3 * plane.d;
  2529. result.m[15] = 1.0;
  2530. };
  2531. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2532. mat.m[0] = xaxis.x;
  2533. mat.m[1] = xaxis.y;
  2534. mat.m[2] = xaxis.z;
  2535. mat.m[3] = 0;
  2536. mat.m[4] = yaxis.x;
  2537. mat.m[5] = yaxis.y;
  2538. mat.m[6] = yaxis.z;
  2539. mat.m[7] = 0;
  2540. mat.m[8] = zaxis.x;
  2541. mat.m[9] = zaxis.y;
  2542. mat.m[10] = zaxis.z;
  2543. mat.m[11] = 0;
  2544. mat.m[12] = 0;
  2545. mat.m[13] = 0;
  2546. mat.m[14] = 0;
  2547. mat.m[15] = 1;
  2548. };
  2549. Matrix.FromQuaternionToRef = function (quat, result) {
  2550. var xx = quat.x * quat.x;
  2551. var yy = quat.y * quat.y;
  2552. var zz = quat.z * quat.z;
  2553. var xy = quat.x * quat.y;
  2554. var zw = quat.z * quat.w;
  2555. var zx = quat.z * quat.x;
  2556. var yw = quat.y * quat.w;
  2557. var yz = quat.y * quat.z;
  2558. var xw = quat.x * quat.w;
  2559. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2560. result.m[1] = 2.0 * (xy + zw);
  2561. result.m[2] = 2.0 * (zx - yw);
  2562. result.m[3] = 0;
  2563. result.m[4] = 2.0 * (xy - zw);
  2564. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2565. result.m[6] = 2.0 * (yz + xw);
  2566. result.m[7] = 0;
  2567. result.m[8] = 2.0 * (zx + yw);
  2568. result.m[9] = 2.0 * (yz - xw);
  2569. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2570. result.m[11] = 0;
  2571. result.m[12] = 0;
  2572. result.m[13] = 0;
  2573. result.m[14] = 0;
  2574. result.m[15] = 1.0;
  2575. };
  2576. Matrix._tempQuaternion = new Quaternion();
  2577. Matrix._xAxis = Vector3.Zero();
  2578. Matrix._yAxis = Vector3.Zero();
  2579. Matrix._zAxis = Vector3.Zero();
  2580. return Matrix;
  2581. }());
  2582. BABYLON.Matrix = Matrix;
  2583. var Plane = (function () {
  2584. function Plane(a, b, c, d) {
  2585. this.normal = new Vector3(a, b, c);
  2586. this.d = d;
  2587. }
  2588. Plane.prototype.asArray = function () {
  2589. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2590. };
  2591. // Methods
  2592. Plane.prototype.clone = function () {
  2593. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2594. };
  2595. Plane.prototype.getClassName = function () {
  2596. return "Plane";
  2597. };
  2598. Plane.prototype.getHashCode = function () {
  2599. var hash = this.normal.getHashCode();
  2600. hash = (hash * 397) ^ (this.d || 0);
  2601. return hash;
  2602. };
  2603. Plane.prototype.normalize = function () {
  2604. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2605. var magnitude = 0;
  2606. if (norm !== 0) {
  2607. magnitude = 1.0 / norm;
  2608. }
  2609. this.normal.x *= magnitude;
  2610. this.normal.y *= magnitude;
  2611. this.normal.z *= magnitude;
  2612. this.d *= magnitude;
  2613. return this;
  2614. };
  2615. Plane.prototype.transform = function (transformation) {
  2616. var transposedMatrix = Matrix.Transpose(transformation);
  2617. var x = this.normal.x;
  2618. var y = this.normal.y;
  2619. var z = this.normal.z;
  2620. var d = this.d;
  2621. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2622. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2623. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2624. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2625. return new Plane(normalX, normalY, normalZ, finalD);
  2626. };
  2627. Plane.prototype.dotCoordinate = function (point) {
  2628. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2629. };
  2630. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2631. var x1 = point2.x - point1.x;
  2632. var y1 = point2.y - point1.y;
  2633. var z1 = point2.z - point1.z;
  2634. var x2 = point3.x - point1.x;
  2635. var y2 = point3.y - point1.y;
  2636. var z2 = point3.z - point1.z;
  2637. var yz = (y1 * z2) - (z1 * y2);
  2638. var xz = (z1 * x2) - (x1 * z2);
  2639. var xy = (x1 * y2) - (y1 * x2);
  2640. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2641. var invPyth;
  2642. if (pyth !== 0) {
  2643. invPyth = 1.0 / pyth;
  2644. }
  2645. else {
  2646. invPyth = 0;
  2647. }
  2648. this.normal.x = yz * invPyth;
  2649. this.normal.y = xz * invPyth;
  2650. this.normal.z = xy * invPyth;
  2651. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2652. return this;
  2653. };
  2654. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2655. var dot = Vector3.Dot(this.normal, direction);
  2656. return (dot <= epsilon);
  2657. };
  2658. Plane.prototype.signedDistanceTo = function (point) {
  2659. return Vector3.Dot(point, this.normal) + this.d;
  2660. };
  2661. // Statics
  2662. Plane.FromArray = function (array) {
  2663. return new Plane(array[0], array[1], array[2], array[3]);
  2664. };
  2665. Plane.FromPoints = function (point1, point2, point3) {
  2666. var result = new Plane(0, 0, 0, 0);
  2667. result.copyFromPoints(point1, point2, point3);
  2668. return result;
  2669. };
  2670. Plane.FromPositionAndNormal = function (origin, normal) {
  2671. var result = new Plane(0, 0, 0, 0);
  2672. normal.normalize();
  2673. result.normal = normal;
  2674. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2675. return result;
  2676. };
  2677. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2678. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2679. return Vector3.Dot(point, normal) + d;
  2680. };
  2681. return Plane;
  2682. }());
  2683. BABYLON.Plane = Plane;
  2684. var Viewport = (function () {
  2685. function Viewport(x, y, width, height) {
  2686. this.x = x;
  2687. this.y = y;
  2688. this.width = width;
  2689. this.height = height;
  2690. }
  2691. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2692. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2693. };
  2694. return Viewport;
  2695. }());
  2696. BABYLON.Viewport = Viewport;
  2697. var Frustum = (function () {
  2698. function Frustum() {
  2699. }
  2700. Frustum.GetPlanes = function (transform) {
  2701. var frustumPlanes = [];
  2702. for (var index = 0; index < 6; index++) {
  2703. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2704. }
  2705. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2706. return frustumPlanes;
  2707. };
  2708. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2709. // Near
  2710. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2711. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2712. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2713. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2714. frustumPlanes[0].normalize();
  2715. // Far
  2716. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2717. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2718. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2719. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2720. frustumPlanes[1].normalize();
  2721. // Left
  2722. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2723. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2724. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2725. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2726. frustumPlanes[2].normalize();
  2727. // Right
  2728. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2729. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2730. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2731. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2732. frustumPlanes[3].normalize();
  2733. // Top
  2734. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2735. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2736. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2737. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2738. frustumPlanes[4].normalize();
  2739. // Bottom
  2740. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2741. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2742. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2743. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2744. frustumPlanes[5].normalize();
  2745. };
  2746. return Frustum;
  2747. }());
  2748. BABYLON.Frustum = Frustum;
  2749. (function (Space) {
  2750. Space[Space["LOCAL"] = 0] = "LOCAL";
  2751. Space[Space["WORLD"] = 1] = "WORLD";
  2752. })(BABYLON.Space || (BABYLON.Space = {}));
  2753. var Space = BABYLON.Space;
  2754. var Axis = (function () {
  2755. function Axis() {
  2756. }
  2757. Axis.X = new Vector3(1, 0, 0);
  2758. Axis.Y = new Vector3(0, 1, 0);
  2759. Axis.Z = new Vector3(0, 0, 1);
  2760. return Axis;
  2761. }());
  2762. BABYLON.Axis = Axis;
  2763. ;
  2764. var BezierCurve = (function () {
  2765. function BezierCurve() {
  2766. }
  2767. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2768. // Extract X (which is equal to time here)
  2769. var f0 = 1 - 3 * x2 + 3 * x1;
  2770. var f1 = 3 * x2 - 6 * x1;
  2771. var f2 = 3 * x1;
  2772. var refinedT = t;
  2773. for (var i = 0; i < 5; i++) {
  2774. var refinedT2 = refinedT * refinedT;
  2775. var refinedT3 = refinedT2 * refinedT;
  2776. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2777. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2778. refinedT -= (x - t) * slope;
  2779. refinedT = Math.min(1, Math.max(0, refinedT));
  2780. }
  2781. // Resolve cubic bezier for the given x
  2782. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2783. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2784. Math.pow(refinedT, 3);
  2785. };
  2786. return BezierCurve;
  2787. }());
  2788. BABYLON.BezierCurve = BezierCurve;
  2789. (function (Orientation) {
  2790. Orientation[Orientation["CW"] = 0] = "CW";
  2791. Orientation[Orientation["CCW"] = 1] = "CCW";
  2792. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2793. var Orientation = BABYLON.Orientation;
  2794. var Angle = (function () {
  2795. function Angle(radians) {
  2796. var _this = this;
  2797. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2798. this.radians = function () { return _this._radians; };
  2799. this._radians = radians;
  2800. if (this._radians < 0)
  2801. this._radians += (2 * Math.PI);
  2802. }
  2803. Angle.BetweenTwoPoints = function (a, b) {
  2804. var delta = b.subtract(a);
  2805. var theta = Math.atan2(delta.y, delta.x);
  2806. return new Angle(theta);
  2807. };
  2808. Angle.FromRadians = function (radians) {
  2809. return new Angle(radians);
  2810. };
  2811. Angle.FromDegrees = function (degrees) {
  2812. return new Angle(degrees * Math.PI / 180);
  2813. };
  2814. return Angle;
  2815. }());
  2816. BABYLON.Angle = Angle;
  2817. var Arc2 = (function () {
  2818. function Arc2(startPoint, midPoint, endPoint) {
  2819. this.startPoint = startPoint;
  2820. this.midPoint = midPoint;
  2821. this.endPoint = endPoint;
  2822. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2823. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2824. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2825. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2826. 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);
  2827. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2828. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2829. var a1 = this.startAngle.degrees();
  2830. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2831. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2832. // angles correction
  2833. if (a2 - a1 > +180.0)
  2834. a2 -= 360.0;
  2835. if (a2 - a1 < -180.0)
  2836. a2 += 360.0;
  2837. if (a3 - a2 > +180.0)
  2838. a3 -= 360.0;
  2839. if (a3 - a2 < -180.0)
  2840. a3 += 360.0;
  2841. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2842. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2843. }
  2844. return Arc2;
  2845. }());
  2846. BABYLON.Arc2 = Arc2;
  2847. var Path2 = (function () {
  2848. function Path2(x, y) {
  2849. this._points = new Array();
  2850. this._length = 0;
  2851. this.closed = false;
  2852. this._points.push(new Vector2(x, y));
  2853. }
  2854. Path2.prototype.addLineTo = function (x, y) {
  2855. if (closed) {
  2856. //Tools.Error("cannot add lines to closed paths");
  2857. return this;
  2858. }
  2859. var newPoint = new Vector2(x, y);
  2860. var previousPoint = this._points[this._points.length - 1];
  2861. this._points.push(newPoint);
  2862. this._length += newPoint.subtract(previousPoint).length();
  2863. return this;
  2864. };
  2865. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2866. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2867. if (closed) {
  2868. //Tools.Error("cannot add arcs to closed paths");
  2869. return this;
  2870. }
  2871. var startPoint = this._points[this._points.length - 1];
  2872. var midPoint = new Vector2(midX, midY);
  2873. var endPoint = new Vector2(endX, endY);
  2874. var arc = new Arc2(startPoint, midPoint, endPoint);
  2875. var increment = arc.angle.radians() / numberOfSegments;
  2876. if (arc.orientation === Orientation.CW)
  2877. increment *= -1;
  2878. var currentAngle = arc.startAngle.radians() + increment;
  2879. for (var i = 0; i < numberOfSegments; i++) {
  2880. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2881. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2882. this.addLineTo(x, y);
  2883. currentAngle += increment;
  2884. }
  2885. return this;
  2886. };
  2887. Path2.prototype.close = function () {
  2888. this.closed = true;
  2889. return this;
  2890. };
  2891. Path2.prototype.length = function () {
  2892. var result = this._length;
  2893. if (!this.closed) {
  2894. var lastPoint = this._points[this._points.length - 1];
  2895. var firstPoint = this._points[0];
  2896. result += (firstPoint.subtract(lastPoint).length());
  2897. }
  2898. return result;
  2899. };
  2900. Path2.prototype.getPoints = function () {
  2901. return this._points;
  2902. };
  2903. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2904. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2905. //Tools.Error("normalized length position should be between 0 and 1.");
  2906. return Vector2.Zero();
  2907. }
  2908. var lengthPosition = normalizedLengthPosition * this.length();
  2909. var previousOffset = 0;
  2910. for (var i = 0; i < this._points.length; i++) {
  2911. var j = (i + 1) % this._points.length;
  2912. var a = this._points[i];
  2913. var b = this._points[j];
  2914. var bToA = b.subtract(a);
  2915. var nextOffset = (bToA.length() + previousOffset);
  2916. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2917. var dir = bToA.normalize();
  2918. var localOffset = lengthPosition - previousOffset;
  2919. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2920. }
  2921. previousOffset = nextOffset;
  2922. }
  2923. //Tools.Error("internal error");
  2924. return Vector2.Zero();
  2925. };
  2926. Path2.StartingAt = function (x, y) {
  2927. return new Path2(x, y);
  2928. };
  2929. return Path2;
  2930. }());
  2931. BABYLON.Path2 = Path2;
  2932. var Path3D = (function () {
  2933. /**
  2934. * new Path3D(path, normal, raw)
  2935. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2936. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2937. * path : an array of Vector3, the curve axis of the Path3D
  2938. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2939. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2940. */
  2941. function Path3D(path, firstNormal, raw) {
  2942. this.path = path;
  2943. this._curve = new Array();
  2944. this._distances = new Array();
  2945. this._tangents = new Array();
  2946. this._normals = new Array();
  2947. this._binormals = new Array();
  2948. for (var p = 0; p < path.length; p++) {
  2949. this._curve[p] = path[p].clone(); // hard copy
  2950. }
  2951. this._raw = raw || false;
  2952. this._compute(firstNormal);
  2953. }
  2954. /**
  2955. * Returns the Path3D array of successive Vector3 designing its curve.
  2956. */
  2957. Path3D.prototype.getCurve = function () {
  2958. return this._curve;
  2959. };
  2960. /**
  2961. * Returns an array populated with tangent vectors on each Path3D curve point.
  2962. */
  2963. Path3D.prototype.getTangents = function () {
  2964. return this._tangents;
  2965. };
  2966. /**
  2967. * Returns an array populated with normal vectors on each Path3D curve point.
  2968. */
  2969. Path3D.prototype.getNormals = function () {
  2970. return this._normals;
  2971. };
  2972. /**
  2973. * Returns an array populated with binormal vectors on each Path3D curve point.
  2974. */
  2975. Path3D.prototype.getBinormals = function () {
  2976. return this._binormals;
  2977. };
  2978. /**
  2979. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2980. */
  2981. Path3D.prototype.getDistances = function () {
  2982. return this._distances;
  2983. };
  2984. /**
  2985. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2986. * Returns the same object updated.
  2987. */
  2988. Path3D.prototype.update = function (path, firstNormal) {
  2989. for (var p = 0; p < path.length; p++) {
  2990. this._curve[p].x = path[p].x;
  2991. this._curve[p].y = path[p].y;
  2992. this._curve[p].z = path[p].z;
  2993. }
  2994. this._compute(firstNormal);
  2995. return this;
  2996. };
  2997. // private function compute() : computes tangents, normals and binormals
  2998. Path3D.prototype._compute = function (firstNormal) {
  2999. var l = this._curve.length;
  3000. // first and last tangents
  3001. this._tangents[0] = this._getFirstNonNullVector(0);
  3002. if (!this._raw) {
  3003. this._tangents[0].normalize();
  3004. }
  3005. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  3006. if (!this._raw) {
  3007. this._tangents[l - 1].normalize();
  3008. }
  3009. // normals and binormals at first point : arbitrary vector with _normalVector()
  3010. var tg0 = this._tangents[0];
  3011. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  3012. this._normals[0] = pp0;
  3013. if (!this._raw) {
  3014. this._normals[0].normalize();
  3015. }
  3016. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  3017. if (!this._raw) {
  3018. this._binormals[0].normalize();
  3019. }
  3020. this._distances[0] = 0.0;
  3021. // normals and binormals : next points
  3022. var prev; // previous vector (segment)
  3023. var cur; // current vector (segment)
  3024. var curTang; // current tangent
  3025. // previous normal
  3026. var prevBinor; // previous binormal
  3027. for (var i = 1; i < l; i++) {
  3028. // tangents
  3029. prev = this._getLastNonNullVector(i);
  3030. if (i < l - 1) {
  3031. cur = this._getFirstNonNullVector(i);
  3032. this._tangents[i] = prev.add(cur);
  3033. this._tangents[i].normalize();
  3034. }
  3035. this._distances[i] = this._distances[i - 1] + prev.length();
  3036. // normals and binormals
  3037. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  3038. curTang = this._tangents[i];
  3039. prevBinor = this._binormals[i - 1];
  3040. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  3041. if (!this._raw) {
  3042. this._normals[i].normalize();
  3043. }
  3044. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  3045. if (!this._raw) {
  3046. this._binormals[i].normalize();
  3047. }
  3048. }
  3049. };
  3050. // private function getFirstNonNullVector(index)
  3051. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  3052. Path3D.prototype._getFirstNonNullVector = function (index) {
  3053. var i = 1;
  3054. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  3055. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  3056. i++;
  3057. nNVector = this._curve[index + i].subtract(this._curve[index]);
  3058. }
  3059. return nNVector;
  3060. };
  3061. // private function getLastNonNullVector(index)
  3062. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3063. Path3D.prototype._getLastNonNullVector = function (index) {
  3064. var i = 1;
  3065. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3066. while (nLVector.length() === 0 && index > i + 1) {
  3067. i++;
  3068. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3069. }
  3070. return nLVector;
  3071. };
  3072. // private function normalVector(v0, vt, va) :
  3073. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3074. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3075. Path3D.prototype._normalVector = function (v0, vt, va) {
  3076. var normal0;
  3077. var tgl = vt.length();
  3078. if (tgl === 0.0) {
  3079. tgl = 1.0;
  3080. }
  3081. if (va === undefined || va === null) {
  3082. var point;
  3083. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3084. point = new Vector3(0.0, -1.0, 0.0);
  3085. }
  3086. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3087. point = new Vector3(1.0, 0.0, 0.0);
  3088. }
  3089. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3090. point = new Vector3(0.0, 0.0, 1.0);
  3091. }
  3092. normal0 = Vector3.Cross(vt, point);
  3093. }
  3094. else {
  3095. normal0 = Vector3.Cross(vt, va);
  3096. Vector3.CrossToRef(normal0, vt, normal0);
  3097. }
  3098. normal0.normalize();
  3099. return normal0;
  3100. };
  3101. return Path3D;
  3102. }());
  3103. BABYLON.Path3D = Path3D;
  3104. var Curve3 = (function () {
  3105. /**
  3106. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3107. * A Curve3 is designed from a series of successive Vector3.
  3108. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3109. */
  3110. function Curve3(points) {
  3111. this._length = 0.0;
  3112. this._points = points;
  3113. this._length = this._computeLength(points);
  3114. }
  3115. /**
  3116. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3117. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3118. * @param v1 (Vector3) the control point
  3119. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3120. * @param nbPoints (integer) the wanted number of points in the curve
  3121. */
  3122. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3123. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3124. var bez = new Array();
  3125. var equation = function (t, val0, val1, val2) {
  3126. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3127. return res;
  3128. };
  3129. for (var i = 0; i <= nbPoints; i++) {
  3130. 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)));
  3131. }
  3132. return new Curve3(bez);
  3133. };
  3134. /**
  3135. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3136. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3137. * @param v1 (Vector3) the first control point
  3138. * @param v2 (Vector3) the second control point
  3139. * @param v3 (Vector3) the end point of the Cubic Bezier
  3140. * @param nbPoints (integer) the wanted number of points in the curve
  3141. */
  3142. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3143. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3144. var bez = new Array();
  3145. var equation = function (t, val0, val1, val2, val3) {
  3146. 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;
  3147. return res;
  3148. };
  3149. for (var i = 0; i <= nbPoints; i++) {
  3150. 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)));
  3151. }
  3152. return new Curve3(bez);
  3153. };
  3154. /**
  3155. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3156. * @param p1 (Vector3) the origin point of the Hermite Spline
  3157. * @param t1 (Vector3) the tangent vector at the origin point
  3158. * @param p2 (Vector3) the end point of the Hermite Spline
  3159. * @param t2 (Vector3) the tangent vector at the end point
  3160. * @param nbPoints (integer) the wanted number of points in the curve
  3161. */
  3162. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3163. var hermite = new Array();
  3164. var step = 1.0 / nbPoints;
  3165. for (var i = 0; i <= nbPoints; i++) {
  3166. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3167. }
  3168. return new Curve3(hermite);
  3169. };
  3170. /**
  3171. * Returns the Curve3 stored array of successive Vector3
  3172. */
  3173. Curve3.prototype.getPoints = function () {
  3174. return this._points;
  3175. };
  3176. /**
  3177. * Returns the computed length (float) of the curve.
  3178. */
  3179. Curve3.prototype.length = function () {
  3180. return this._length;
  3181. };
  3182. /**
  3183. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3184. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3185. * curveA and curveB keep unchanged.
  3186. */
  3187. Curve3.prototype.continue = function (curve) {
  3188. var lastPoint = this._points[this._points.length - 1];
  3189. var continuedPoints = this._points.slice();
  3190. var curvePoints = curve.getPoints();
  3191. for (var i = 1; i < curvePoints.length; i++) {
  3192. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3193. }
  3194. var continuedCurve = new Curve3(continuedPoints);
  3195. return continuedCurve;
  3196. };
  3197. Curve3.prototype._computeLength = function (path) {
  3198. var l = 0;
  3199. for (var i = 1; i < path.length; i++) {
  3200. l += (path[i].subtract(path[i - 1])).length();
  3201. }
  3202. return l;
  3203. };
  3204. return Curve3;
  3205. }());
  3206. BABYLON.Curve3 = Curve3;
  3207. // SphericalHarmonics
  3208. var SphericalHarmonics = (function () {
  3209. function SphericalHarmonics() {
  3210. this.L00 = Vector3.Zero();
  3211. this.L1_1 = Vector3.Zero();
  3212. this.L10 = Vector3.Zero();
  3213. this.L11 = Vector3.Zero();
  3214. this.L2_2 = Vector3.Zero();
  3215. this.L2_1 = Vector3.Zero();
  3216. this.L20 = Vector3.Zero();
  3217. this.L21 = Vector3.Zero();
  3218. this.L22 = Vector3.Zero();
  3219. }
  3220. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3221. var colorVector = new Vector3(color.r, color.g, color.b);
  3222. var c = colorVector.scale(deltaSolidAngle);
  3223. this.L00 = this.L00.add(c.scale(0.282095));
  3224. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3225. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3226. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3227. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3228. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3229. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3230. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3231. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3232. };
  3233. SphericalHarmonics.prototype.scale = function (scale) {
  3234. this.L00 = this.L00.scale(scale);
  3235. this.L1_1 = this.L1_1.scale(scale);
  3236. this.L10 = this.L10.scale(scale);
  3237. this.L11 = this.L11.scale(scale);
  3238. this.L2_2 = this.L2_2.scale(scale);
  3239. this.L2_1 = this.L2_1.scale(scale);
  3240. this.L20 = this.L20.scale(scale);
  3241. this.L21 = this.L21.scale(scale);
  3242. this.L22 = this.L22.scale(scale);
  3243. };
  3244. return SphericalHarmonics;
  3245. }());
  3246. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3247. // SphericalPolynomial
  3248. var SphericalPolynomial = (function () {
  3249. function SphericalPolynomial() {
  3250. this.x = Vector3.Zero();
  3251. this.y = Vector3.Zero();
  3252. this.z = Vector3.Zero();
  3253. this.xx = Vector3.Zero();
  3254. this.yy = Vector3.Zero();
  3255. this.zz = Vector3.Zero();
  3256. this.xy = Vector3.Zero();
  3257. this.yz = Vector3.Zero();
  3258. this.zx = Vector3.Zero();
  3259. }
  3260. SphericalPolynomial.prototype.addAmbient = function (color) {
  3261. var colorVector = new Vector3(color.r, color.g, color.b);
  3262. this.xx = this.xx.add(colorVector);
  3263. this.yy = this.yy.add(colorVector);
  3264. this.zz = this.zz.add(colorVector);
  3265. };
  3266. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3267. var result = new SphericalPolynomial();
  3268. result.x = harmonics.L11.scale(1.02333);
  3269. result.y = harmonics.L1_1.scale(1.02333);
  3270. result.z = harmonics.L10.scale(1.02333);
  3271. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3272. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3273. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3274. result.yz = harmonics.L2_1.scale(0.858086);
  3275. result.zx = harmonics.L21.scale(0.858086);
  3276. result.xy = harmonics.L2_2.scale(0.858086);
  3277. return result;
  3278. };
  3279. return SphericalPolynomial;
  3280. }());
  3281. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3282. // Vertex formats
  3283. var PositionNormalVertex = (function () {
  3284. function PositionNormalVertex(position, normal) {
  3285. if (position === void 0) { position = Vector3.Zero(); }
  3286. if (normal === void 0) { normal = Vector3.Up(); }
  3287. this.position = position;
  3288. this.normal = normal;
  3289. }
  3290. PositionNormalVertex.prototype.clone = function () {
  3291. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3292. };
  3293. return PositionNormalVertex;
  3294. }());
  3295. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3296. var PositionNormalTextureVertex = (function () {
  3297. function PositionNormalTextureVertex(position, normal, uv) {
  3298. if (position === void 0) { position = Vector3.Zero(); }
  3299. if (normal === void 0) { normal = Vector3.Up(); }
  3300. if (uv === void 0) { uv = Vector2.Zero(); }
  3301. this.position = position;
  3302. this.normal = normal;
  3303. this.uv = uv;
  3304. }
  3305. PositionNormalTextureVertex.prototype.clone = function () {
  3306. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3307. };
  3308. return PositionNormalTextureVertex;
  3309. }());
  3310. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3311. // Temporary pre-allocated objects for engine internal use
  3312. // usage in any internal function :
  3313. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3314. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3315. var Tmp = (function () {
  3316. function Tmp() {
  3317. }
  3318. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3319. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3320. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3321. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3322. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3323. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3324. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3325. Matrix.Zero(), Matrix.Zero(),
  3326. Matrix.Zero(), Matrix.Zero(),
  3327. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3328. return Tmp;
  3329. }());
  3330. BABYLON.Tmp = Tmp;
  3331. })(BABYLON || (BABYLON = {}));
  3332. //# sourceMappingURL=babylon.math.js.map
  3333. //# sourceMappingURL=babylon.mixins.js.map
  3334. var BABYLON;
  3335. (function (BABYLON) {
  3336. function generateSerializableMember(type, sourceName) {
  3337. return function (target, propertyKey) {
  3338. if (!target.__serializableMembers) {
  3339. target.__serializableMembers = {};
  3340. }
  3341. if (!target.__serializableMembers[propertyKey]) {
  3342. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3343. }
  3344. };
  3345. }
  3346. function serialize(sourceName) {
  3347. return generateSerializableMember(0, sourceName); // value member
  3348. }
  3349. BABYLON.serialize = serialize;
  3350. function serializeAsTexture(sourceName) {
  3351. return generateSerializableMember(1, sourceName); // texture member
  3352. }
  3353. BABYLON.serializeAsTexture = serializeAsTexture;
  3354. function serializeAsColor3(sourceName) {
  3355. return generateSerializableMember(2, sourceName); // color3 member
  3356. }
  3357. BABYLON.serializeAsColor3 = serializeAsColor3;
  3358. function serializeAsFresnelParameters(sourceName) {
  3359. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3360. }
  3361. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3362. function serializeAsVector2(sourceName) {
  3363. return generateSerializableMember(4, sourceName); // vector2 member
  3364. }
  3365. BABYLON.serializeAsVector2 = serializeAsVector2;
  3366. function serializeAsVector3(sourceName) {
  3367. return generateSerializableMember(5, sourceName); // vector3 member
  3368. }
  3369. BABYLON.serializeAsVector3 = serializeAsVector3;
  3370. function serializeAsMeshReference(sourceName) {
  3371. return generateSerializableMember(6, sourceName); // mesh reference member
  3372. }
  3373. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3374. function serializeAsColorCurves(sourceName) {
  3375. return generateSerializableMember(7, sourceName); // color curves
  3376. }
  3377. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3378. var SerializationHelper = (function () {
  3379. function SerializationHelper() {
  3380. }
  3381. SerializationHelper.Serialize = function (entity, serializationObject) {
  3382. if (!serializationObject) {
  3383. serializationObject = {};
  3384. }
  3385. // Tags
  3386. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3387. // Properties
  3388. for (var property in entity.__serializableMembers) {
  3389. var propertyDescriptor = entity.__serializableMembers[property];
  3390. var targetPropertyName = propertyDescriptor.sourceName || property;
  3391. var propertyType = propertyDescriptor.type;
  3392. var sourceProperty = entity[property];
  3393. if (sourceProperty !== undefined && sourceProperty !== null) {
  3394. switch (propertyType) {
  3395. case 0:
  3396. serializationObject[targetPropertyName] = sourceProperty;
  3397. break;
  3398. case 1:
  3399. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3400. break;
  3401. case 2:
  3402. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3403. break;
  3404. case 3:
  3405. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3406. break;
  3407. case 4:
  3408. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3409. break;
  3410. case 5:
  3411. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3412. break;
  3413. case 6:
  3414. serializationObject[targetPropertyName] = sourceProperty.id;
  3415. break;
  3416. case 7:
  3417. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3418. break;
  3419. }
  3420. }
  3421. }
  3422. return serializationObject;
  3423. };
  3424. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3425. var destination = creationFunction();
  3426. // Tags
  3427. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3428. // Properties
  3429. for (var property in destination.__serializableMembers) {
  3430. var propertyDescriptor = destination.__serializableMembers[property];
  3431. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3432. var propertyType = propertyDescriptor.type;
  3433. if (sourceProperty !== undefined && sourceProperty !== null) {
  3434. switch (propertyType) {
  3435. case 0:
  3436. destination[property] = sourceProperty;
  3437. break;
  3438. case 1:
  3439. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3440. break;
  3441. case 2:
  3442. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3443. break;
  3444. case 3:
  3445. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3446. break;
  3447. case 4:
  3448. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3449. break;
  3450. case 5:
  3451. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3452. break;
  3453. case 6:
  3454. destination[property] = scene.getLastMeshByID(sourceProperty);
  3455. break;
  3456. case 7:
  3457. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3458. break;
  3459. }
  3460. }
  3461. }
  3462. return destination;
  3463. };
  3464. SerializationHelper.Clone = function (creationFunction, source) {
  3465. var destination = creationFunction();
  3466. // Tags
  3467. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3468. // Properties
  3469. for (var property in destination.__serializableMembers) {
  3470. var propertyDescriptor = destination.__serializableMembers[property];
  3471. var sourceProperty = source[property];
  3472. var propertyType = propertyDescriptor.type;
  3473. if (sourceProperty !== undefined && sourceProperty !== null) {
  3474. switch (propertyType) {
  3475. case 0: // Value
  3476. case 6:
  3477. destination[property] = sourceProperty;
  3478. break;
  3479. case 1: // Texture
  3480. case 2: // Color3
  3481. case 3: // FresnelParameters
  3482. case 4: // Vector2
  3483. case 5: // Vector3
  3484. case 7:
  3485. destination[property] = sourceProperty.clone();
  3486. break;
  3487. }
  3488. }
  3489. }
  3490. return destination;
  3491. };
  3492. return SerializationHelper;
  3493. }());
  3494. BABYLON.SerializationHelper = SerializationHelper;
  3495. })(BABYLON || (BABYLON = {}));
  3496. //# sourceMappingURL=babylon.decorators.js.map
  3497. var BABYLON;
  3498. (function (BABYLON) {
  3499. /**
  3500. * A class serves as a medium between the observable and its observers
  3501. */
  3502. var EventState = (function () {
  3503. /**
  3504. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3505. */
  3506. function EventState(mask, skipNextObservers) {
  3507. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3508. this.initalize(mask, skipNextObservers);
  3509. }
  3510. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3511. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3512. this.mask = mask;
  3513. this.skipNextObservers = skipNextObservers;
  3514. return this;
  3515. };
  3516. return EventState;
  3517. }());
  3518. BABYLON.EventState = EventState;
  3519. /**
  3520. * Represent an Observer registered to a given Observable object.
  3521. */
  3522. var Observer = (function () {
  3523. function Observer(callback, mask) {
  3524. this.callback = callback;
  3525. this.mask = mask;
  3526. }
  3527. return Observer;
  3528. }());
  3529. BABYLON.Observer = Observer;
  3530. /**
  3531. * The Observable class is a simple implementation of the Observable pattern.
  3532. * 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.
  3533. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3534. * 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).
  3535. * 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.
  3536. */
  3537. var Observable = (function () {
  3538. function Observable() {
  3539. this._observers = new Array();
  3540. this._eventState = new EventState(0);
  3541. }
  3542. /**
  3543. * Create a new Observer with the specified callback
  3544. * @param callback the callback that will be executed for that Observer
  3545. * @param mask the mask used to filter observers
  3546. * @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.
  3547. */
  3548. Observable.prototype.add = function (callback, mask, insertFirst) {
  3549. if (mask === void 0) { mask = -1; }
  3550. if (insertFirst === void 0) { insertFirst = false; }
  3551. if (!callback) {
  3552. return null;
  3553. }
  3554. var observer = new Observer(callback, mask);
  3555. if (insertFirst) {
  3556. this._observers.unshift(observer);
  3557. }
  3558. else {
  3559. this._observers.push(observer);
  3560. }
  3561. return observer;
  3562. };
  3563. /**
  3564. * Remove an Observer from the Observable object
  3565. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3566. */
  3567. Observable.prototype.remove = function (observer) {
  3568. var index = this._observers.indexOf(observer);
  3569. if (index !== -1) {
  3570. this._observers.splice(index, 1);
  3571. return true;
  3572. }
  3573. return false;
  3574. };
  3575. /**
  3576. * Remove a callback from the Observable object
  3577. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3578. */
  3579. Observable.prototype.removeCallback = function (callback) {
  3580. for (var index = 0; index < this._observers.length; index++) {
  3581. if (this._observers[index].callback === callback) {
  3582. this._observers.splice(index, 1);
  3583. return true;
  3584. }
  3585. }
  3586. return false;
  3587. };
  3588. /**
  3589. * Notify all Observers by calling their respective callback with the given data
  3590. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3591. * @param eventData
  3592. * @param mask
  3593. */
  3594. Observable.prototype.notifyObservers = function (eventData, mask) {
  3595. if (mask === void 0) { mask = -1; }
  3596. var state = this._eventState;
  3597. state.mask = mask;
  3598. state.skipNextObservers = false;
  3599. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3600. var obs = _a[_i];
  3601. if (obs.mask & mask) {
  3602. obs.callback(eventData, state);
  3603. }
  3604. if (state.skipNextObservers) {
  3605. return false;
  3606. }
  3607. }
  3608. return true;
  3609. };
  3610. /**
  3611. * return true is the Observable has at least one Observer registered
  3612. */
  3613. Observable.prototype.hasObservers = function () {
  3614. return this._observers.length > 0;
  3615. };
  3616. /**
  3617. * Clear the list of observers
  3618. */
  3619. Observable.prototype.clear = function () {
  3620. this._observers = new Array();
  3621. };
  3622. /**
  3623. * Clone the current observable
  3624. */
  3625. Observable.prototype.clone = function () {
  3626. var result = new Observable();
  3627. result._observers = this._observers.slice(0);
  3628. return result;
  3629. };
  3630. return Observable;
  3631. }());
  3632. BABYLON.Observable = Observable;
  3633. })(BABYLON || (BABYLON = {}));
  3634. //# sourceMappingURL=babylon.observable.js.map
  3635. var BABYLON;
  3636. (function (BABYLON) {
  3637. var Database = (function () {
  3638. function Database(urlToScene, callbackManifestChecked) {
  3639. // Handling various flavors of prefixed version of IndexedDB
  3640. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3641. this.callbackManifestChecked = callbackManifestChecked;
  3642. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3643. this.db = null;
  3644. this.enableSceneOffline = false;
  3645. this.enableTexturesOffline = false;
  3646. this.manifestVersionFound = 0;
  3647. this.mustUpdateRessources = false;
  3648. this.hasReachedQuota = false;
  3649. if (!Database.IDBStorageEnabled) {
  3650. this.callbackManifestChecked(true);
  3651. }
  3652. else {
  3653. this.checkManifestFile();
  3654. }
  3655. }
  3656. Database.prototype.checkManifestFile = function () {
  3657. var _this = this;
  3658. function noManifestFile() {
  3659. that.enableSceneOffline = false;
  3660. that.enableTexturesOffline = false;
  3661. that.callbackManifestChecked(false);
  3662. }
  3663. var that = this;
  3664. var timeStampUsed = false;
  3665. var manifestURL = this.currentSceneUrl + ".manifest";
  3666. var xhr = new XMLHttpRequest();
  3667. if (navigator.onLine) {
  3668. // Adding a timestamp to by-pass browsers' cache
  3669. timeStampUsed = true;
  3670. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3671. }
  3672. xhr.open("GET", manifestURL, true);
  3673. xhr.addEventListener("load", function () {
  3674. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3675. try {
  3676. var manifestFile = JSON.parse(xhr.response);
  3677. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3678. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3679. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3680. _this.manifestVersionFound = manifestFile.version;
  3681. }
  3682. if (_this.callbackManifestChecked) {
  3683. _this.callbackManifestChecked(true);
  3684. }
  3685. }
  3686. catch (ex) {
  3687. noManifestFile();
  3688. }
  3689. }
  3690. else {
  3691. noManifestFile();
  3692. }
  3693. }, false);
  3694. xhr.addEventListener("error", function (event) {
  3695. if (timeStampUsed) {
  3696. timeStampUsed = false;
  3697. // Let's retry without the timeStamp
  3698. // It could fail when coupled with HTML5 Offline API
  3699. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3700. xhr.open("GET", retryManifestURL, true);
  3701. xhr.send();
  3702. }
  3703. else {
  3704. noManifestFile();
  3705. }
  3706. }, false);
  3707. try {
  3708. xhr.send();
  3709. }
  3710. catch (ex) {
  3711. BABYLON.Tools.Error("Error on XHR send request.");
  3712. that.callbackManifestChecked(false);
  3713. }
  3714. };
  3715. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3716. var _this = this;
  3717. function handleError() {
  3718. that.isSupported = false;
  3719. if (errorCallback)
  3720. errorCallback();
  3721. }
  3722. var that = this;
  3723. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3724. // Your browser doesn't support IndexedDB
  3725. this.isSupported = false;
  3726. if (errorCallback)
  3727. errorCallback();
  3728. }
  3729. else {
  3730. // If the DB hasn't been opened or created yet
  3731. if (!this.db) {
  3732. this.hasReachedQuota = false;
  3733. this.isSupported = true;
  3734. var request = this.idbFactory.open("babylonjs", 1);
  3735. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3736. request.onerror = function (event) {
  3737. handleError();
  3738. };
  3739. // executes when a version change transaction cannot complete due to other active transactions
  3740. request.onblocked = function (event) {
  3741. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3742. handleError();
  3743. };
  3744. // DB has been opened successfully
  3745. request.onsuccess = function (event) {
  3746. _this.db = request.result;
  3747. successCallback();
  3748. };
  3749. // Initialization of the DB. Creating Scenes & Textures stores
  3750. request.onupgradeneeded = function (event) {
  3751. _this.db = (event.target).result;
  3752. try {
  3753. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3754. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3755. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3756. }
  3757. catch (ex) {
  3758. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3759. handleError();
  3760. }
  3761. };
  3762. }
  3763. else {
  3764. if (successCallback)
  3765. successCallback();
  3766. }
  3767. }
  3768. };
  3769. Database.prototype.loadImageFromDB = function (url, image) {
  3770. var _this = this;
  3771. var completeURL = Database.ReturnFullUrlLocation(url);
  3772. var saveAndLoadImage = function () {
  3773. if (!_this.hasReachedQuota && _this.db !== null) {
  3774. // the texture is not yet in the DB, let's try to save it
  3775. _this._saveImageIntoDBAsync(completeURL, image);
  3776. }
  3777. else {
  3778. image.src = url;
  3779. }
  3780. };
  3781. if (!this.mustUpdateRessources) {
  3782. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3783. }
  3784. else {
  3785. saveAndLoadImage();
  3786. }
  3787. };
  3788. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3789. if (this.isSupported && this.db !== null) {
  3790. var texture;
  3791. var transaction = this.db.transaction(["textures"]);
  3792. transaction.onabort = function (event) {
  3793. image.src = url;
  3794. };
  3795. transaction.oncomplete = function (event) {
  3796. var blobTextureURL;
  3797. if (texture) {
  3798. var URL = window.URL || window.webkitURL;
  3799. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3800. image.onerror = function () {
  3801. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3802. image.src = url;
  3803. };
  3804. image.src = blobTextureURL;
  3805. }
  3806. else {
  3807. notInDBCallback();
  3808. }
  3809. };
  3810. var getRequest = transaction.objectStore("textures").get(url);
  3811. getRequest.onsuccess = function (event) {
  3812. texture = (event.target).result;
  3813. };
  3814. getRequest.onerror = function (event) {
  3815. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3816. image.src = url;
  3817. };
  3818. }
  3819. else {
  3820. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3821. image.src = url;
  3822. }
  3823. };
  3824. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3825. var _this = this;
  3826. if (this.isSupported) {
  3827. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3828. var generateBlobUrl = function () {
  3829. var blobTextureURL;
  3830. if (blob) {
  3831. var URL = window.URL || window.webkitURL;
  3832. try {
  3833. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3834. }
  3835. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3836. catch (ex) {
  3837. blobTextureURL = URL.createObjectURL(blob);
  3838. }
  3839. }
  3840. image.src = blobTextureURL;
  3841. };
  3842. if (Database.IsUASupportingBlobStorage) {
  3843. var xhr = new XMLHttpRequest(), blob;
  3844. xhr.open("GET", url, true);
  3845. xhr.responseType = "blob";
  3846. xhr.addEventListener("load", function () {
  3847. if (xhr.status === 200) {
  3848. // Blob as response (XHR2)
  3849. blob = xhr.response;
  3850. var transaction = _this.db.transaction(["textures"], "readwrite");
  3851. // the transaction could abort because of a QuotaExceededError error
  3852. transaction.onabort = function (event) {
  3853. try {
  3854. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3855. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3856. _this.hasReachedQuota = true;
  3857. }
  3858. }
  3859. catch (ex) { }
  3860. generateBlobUrl();
  3861. };
  3862. transaction.oncomplete = function (event) {
  3863. generateBlobUrl();
  3864. };
  3865. var newTexture = { textureUrl: url, data: blob };
  3866. try {
  3867. // Put the blob into the dabase
  3868. var addRequest = transaction.objectStore("textures").put(newTexture);
  3869. addRequest.onsuccess = function (event) {
  3870. };
  3871. addRequest.onerror = function (event) {
  3872. generateBlobUrl();
  3873. };
  3874. }
  3875. catch (ex) {
  3876. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3877. if (ex.code === 25) {
  3878. Database.IsUASupportingBlobStorage = false;
  3879. }
  3880. image.src = url;
  3881. }
  3882. }
  3883. else {
  3884. image.src = url;
  3885. }
  3886. }, false);
  3887. xhr.addEventListener("error", function (event) {
  3888. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3889. image.src = url;
  3890. }, false);
  3891. xhr.send();
  3892. }
  3893. else {
  3894. image.src = url;
  3895. }
  3896. }
  3897. else {
  3898. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3899. image.src = url;
  3900. }
  3901. };
  3902. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3903. var _this = this;
  3904. var updateVersion = function (event) {
  3905. // the version is not yet in the DB or we need to update it
  3906. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3907. };
  3908. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3909. };
  3910. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3911. var _this = this;
  3912. if (this.isSupported) {
  3913. var version;
  3914. try {
  3915. var transaction = this.db.transaction(["versions"]);
  3916. transaction.oncomplete = function (event) {
  3917. if (version) {
  3918. // If the version in the JSON file is > than the version in DB
  3919. if (_this.manifestVersionFound > version.data) {
  3920. _this.mustUpdateRessources = true;
  3921. updateInDBCallback();
  3922. }
  3923. else {
  3924. callback(version.data);
  3925. }
  3926. }
  3927. else {
  3928. _this.mustUpdateRessources = true;
  3929. updateInDBCallback();
  3930. }
  3931. };
  3932. transaction.onabort = function (event) {
  3933. callback(-1);
  3934. };
  3935. var getRequest = transaction.objectStore("versions").get(url);
  3936. getRequest.onsuccess = function (event) {
  3937. version = (event.target).result;
  3938. };
  3939. getRequest.onerror = function (event) {
  3940. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3941. callback(-1);
  3942. };
  3943. }
  3944. catch (ex) {
  3945. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3946. callback(-1);
  3947. }
  3948. }
  3949. else {
  3950. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3951. callback(-1);
  3952. }
  3953. };
  3954. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3955. var _this = this;
  3956. if (this.isSupported && !this.hasReachedQuota) {
  3957. try {
  3958. // Open a transaction to the database
  3959. var transaction = this.db.transaction(["versions"], "readwrite");
  3960. // the transaction could abort because of a QuotaExceededError error
  3961. transaction.onabort = function (event) {
  3962. try {
  3963. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3964. _this.hasReachedQuota = true;
  3965. }
  3966. }
  3967. catch (ex) { }
  3968. callback(-1);
  3969. };
  3970. transaction.oncomplete = function (event) {
  3971. callback(_this.manifestVersionFound);
  3972. };
  3973. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3974. // Put the scene into the database
  3975. var addRequest = transaction.objectStore("versions").put(newVersion);
  3976. addRequest.onsuccess = function (event) {
  3977. };
  3978. addRequest.onerror = function (event) {
  3979. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3980. };
  3981. }
  3982. catch (ex) {
  3983. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3984. callback(-1);
  3985. }
  3986. }
  3987. else {
  3988. callback(-1);
  3989. }
  3990. };
  3991. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3992. var _this = this;
  3993. var completeUrl = Database.ReturnFullUrlLocation(url);
  3994. var saveAndLoadFile = function (event) {
  3995. // the scene is not yet in the DB, let's try to save it
  3996. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3997. };
  3998. this._checkVersionFromDB(completeUrl, function (version) {
  3999. if (version !== -1) {
  4000. if (!_this.mustUpdateRessources) {
  4001. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  4002. }
  4003. else {
  4004. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  4005. }
  4006. }
  4007. else {
  4008. errorCallback();
  4009. }
  4010. });
  4011. };
  4012. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  4013. if (this.isSupported) {
  4014. var targetStore;
  4015. if (url.indexOf(".babylon") !== -1) {
  4016. targetStore = "scenes";
  4017. }
  4018. else {
  4019. targetStore = "textures";
  4020. }
  4021. var file;
  4022. var transaction = this.db.transaction([targetStore]);
  4023. transaction.oncomplete = function (event) {
  4024. if (file) {
  4025. callback(file.data);
  4026. }
  4027. else {
  4028. notInDBCallback();
  4029. }
  4030. };
  4031. transaction.onabort = function (event) {
  4032. notInDBCallback();
  4033. };
  4034. var getRequest = transaction.objectStore(targetStore).get(url);
  4035. getRequest.onsuccess = function (event) {
  4036. file = (event.target).result;
  4037. };
  4038. getRequest.onerror = function (event) {
  4039. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  4040. notInDBCallback();
  4041. };
  4042. }
  4043. else {
  4044. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4045. callback();
  4046. }
  4047. };
  4048. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  4049. var _this = this;
  4050. if (this.isSupported) {
  4051. var targetStore;
  4052. if (url.indexOf(".babylon") !== -1) {
  4053. targetStore = "scenes";
  4054. }
  4055. else {
  4056. targetStore = "textures";
  4057. }
  4058. // Create XHR
  4059. var xhr = new XMLHttpRequest(), fileData;
  4060. xhr.open("GET", url, true);
  4061. if (useArrayBuffer) {
  4062. xhr.responseType = "arraybuffer";
  4063. }
  4064. xhr.onprogress = progressCallback;
  4065. xhr.addEventListener("load", function () {
  4066. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4067. // Blob as response (XHR2)
  4068. //fileData = xhr.responseText;
  4069. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4070. if (!_this.hasReachedQuota) {
  4071. // Open a transaction to the database
  4072. var transaction = _this.db.transaction([targetStore], "readwrite");
  4073. // the transaction could abort because of a QuotaExceededError error
  4074. transaction.onabort = function (event) {
  4075. try {
  4076. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4077. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4078. _this.hasReachedQuota = true;
  4079. }
  4080. }
  4081. catch (ex) { }
  4082. callback(fileData);
  4083. };
  4084. transaction.oncomplete = function (event) {
  4085. callback(fileData);
  4086. };
  4087. var newFile;
  4088. if (targetStore === "scenes") {
  4089. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4090. }
  4091. else {
  4092. newFile = { textureUrl: url, data: fileData };
  4093. }
  4094. try {
  4095. // Put the scene into the database
  4096. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4097. addRequest.onsuccess = function (event) {
  4098. };
  4099. addRequest.onerror = function (event) {
  4100. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4101. };
  4102. }
  4103. catch (ex) {
  4104. callback(fileData);
  4105. }
  4106. }
  4107. else {
  4108. callback(fileData);
  4109. }
  4110. }
  4111. else {
  4112. callback();
  4113. }
  4114. }, false);
  4115. xhr.addEventListener("error", function (event) {
  4116. BABYLON.Tools.Error("error on XHR request.");
  4117. callback();
  4118. }, false);
  4119. xhr.send();
  4120. }
  4121. else {
  4122. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4123. callback();
  4124. }
  4125. };
  4126. Database.IsUASupportingBlobStorage = true;
  4127. Database.IDBStorageEnabled = true;
  4128. Database.parseURL = function (url) {
  4129. var a = document.createElement('a');
  4130. a.href = url;
  4131. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4132. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4133. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4134. return absLocation;
  4135. };
  4136. Database.ReturnFullUrlLocation = function (url) {
  4137. if (url.indexOf("http:/") === -1) {
  4138. return (Database.parseURL(window.location.href) + url);
  4139. }
  4140. else {
  4141. return url;
  4142. }
  4143. };
  4144. return Database;
  4145. }());
  4146. BABYLON.Database = Database;
  4147. })(BABYLON || (BABYLON = {}));
  4148. //# sourceMappingURL=babylon.database.js.map
  4149. var BABYLON;
  4150. (function (BABYLON) {
  4151. var Internals;
  4152. (function (Internals) {
  4153. /*
  4154. * Based on jsTGALoader - Javascript loader for TGA file
  4155. * By Vincent Thibault
  4156. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4157. */
  4158. var TGATools = (function () {
  4159. function TGATools() {
  4160. }
  4161. TGATools.GetTGAHeader = function (data) {
  4162. var offset = 0;
  4163. var header = {
  4164. id_length: data[offset++],
  4165. colormap_type: data[offset++],
  4166. image_type: data[offset++],
  4167. colormap_index: data[offset++] | data[offset++] << 8,
  4168. colormap_length: data[offset++] | data[offset++] << 8,
  4169. colormap_size: data[offset++],
  4170. origin: [
  4171. data[offset++] | data[offset++] << 8,
  4172. data[offset++] | data[offset++] << 8
  4173. ],
  4174. width: data[offset++] | data[offset++] << 8,
  4175. height: data[offset++] | data[offset++] << 8,
  4176. pixel_size: data[offset++],
  4177. flags: data[offset++]
  4178. };
  4179. return header;
  4180. };
  4181. TGATools.UploadContent = function (gl, data) {
  4182. // Not enough data to contain header ?
  4183. if (data.length < 19) {
  4184. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4185. return;
  4186. }
  4187. // Read Header
  4188. var offset = 18;
  4189. var header = TGATools.GetTGAHeader(data);
  4190. // Assume it's a valid Targa file.
  4191. if (header.id_length + offset > data.length) {
  4192. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4193. return;
  4194. }
  4195. // Skip not needed data
  4196. offset += header.id_length;
  4197. var use_rle = false;
  4198. var use_pal = false;
  4199. var use_rgb = false;
  4200. var use_grey = false;
  4201. // Get some informations.
  4202. switch (header.image_type) {
  4203. case TGATools._TYPE_RLE_INDEXED:
  4204. use_rle = true;
  4205. case TGATools._TYPE_INDEXED:
  4206. use_pal = true;
  4207. break;
  4208. case TGATools._TYPE_RLE_RGB:
  4209. use_rle = true;
  4210. case TGATools._TYPE_RGB:
  4211. use_rgb = true;
  4212. break;
  4213. case TGATools._TYPE_RLE_GREY:
  4214. use_rle = true;
  4215. case TGATools._TYPE_GREY:
  4216. use_grey = true;
  4217. break;
  4218. }
  4219. var pixel_data;
  4220. var numAlphaBits = header.flags & 0xf;
  4221. var pixel_size = header.pixel_size >> 3;
  4222. var pixel_total = header.width * header.height * pixel_size;
  4223. // Read palettes
  4224. var palettes;
  4225. if (use_pal) {
  4226. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4227. }
  4228. // Read LRE
  4229. if (use_rle) {
  4230. pixel_data = new Uint8Array(pixel_total);
  4231. var c, count, i;
  4232. var localOffset = 0;
  4233. var pixels = new Uint8Array(pixel_size);
  4234. while (offset < pixel_total && localOffset < pixel_total) {
  4235. c = data[offset++];
  4236. count = (c & 0x7f) + 1;
  4237. // RLE pixels
  4238. if (c & 0x80) {
  4239. // Bind pixel tmp array
  4240. for (i = 0; i < pixel_size; ++i) {
  4241. pixels[i] = data[offset++];
  4242. }
  4243. // Copy pixel array
  4244. for (i = 0; i < count; ++i) {
  4245. pixel_data.set(pixels, localOffset + i * pixel_size);
  4246. }
  4247. localOffset += pixel_size * count;
  4248. }
  4249. else {
  4250. count *= pixel_size;
  4251. for (i = 0; i < count; ++i) {
  4252. pixel_data[localOffset + i] = data[offset++];
  4253. }
  4254. localOffset += count;
  4255. }
  4256. }
  4257. }
  4258. else {
  4259. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4260. }
  4261. // Load to texture
  4262. var x_start, y_start, x_step, y_step, y_end, x_end;
  4263. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4264. default:
  4265. case TGATools._ORIGIN_UL:
  4266. x_start = 0;
  4267. x_step = 1;
  4268. x_end = header.width;
  4269. y_start = 0;
  4270. y_step = 1;
  4271. y_end = header.height;
  4272. break;
  4273. case TGATools._ORIGIN_BL:
  4274. x_start = 0;
  4275. x_step = 1;
  4276. x_end = header.width;
  4277. y_start = header.height - 1;
  4278. y_step = -1;
  4279. y_end = -1;
  4280. break;
  4281. case TGATools._ORIGIN_UR:
  4282. x_start = header.width - 1;
  4283. x_step = -1;
  4284. x_end = -1;
  4285. y_start = 0;
  4286. y_step = 1;
  4287. y_end = header.height;
  4288. break;
  4289. case TGATools._ORIGIN_BR:
  4290. x_start = header.width - 1;
  4291. x_step = -1;
  4292. x_end = -1;
  4293. y_start = header.height - 1;
  4294. y_step = -1;
  4295. y_end = -1;
  4296. break;
  4297. }
  4298. // Load the specify method
  4299. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4300. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4301. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4302. };
  4303. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4304. var image = pixel_data, colormap = palettes;
  4305. var width = header.width, height = header.height;
  4306. var color, i = 0, x, y;
  4307. var imageData = new Uint8Array(width * height * 4);
  4308. for (y = y_start; y !== y_end; y += y_step) {
  4309. for (x = x_start; x !== x_end; x += x_step, i++) {
  4310. color = image[i];
  4311. imageData[(x + width * y) * 4 + 3] = 255;
  4312. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4313. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4314. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4315. }
  4316. }
  4317. return imageData;
  4318. };
  4319. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4320. var image = pixel_data;
  4321. var width = header.width, height = header.height;
  4322. var color, i = 0, x, y;
  4323. var imageData = new Uint8Array(width * height * 4);
  4324. for (y = y_start; y !== y_end; y += y_step) {
  4325. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4326. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4327. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4328. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4329. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4330. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4331. }
  4332. }
  4333. return imageData;
  4334. };
  4335. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4336. var image = pixel_data;
  4337. var width = header.width, height = header.height;
  4338. var i = 0, x, y;
  4339. var imageData = new Uint8Array(width * height * 4);
  4340. for (y = y_start; y !== y_end; y += y_step) {
  4341. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4342. imageData[(x + width * y) * 4 + 3] = 255;
  4343. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4344. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4345. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4346. }
  4347. }
  4348. return imageData;
  4349. };
  4350. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4351. var image = pixel_data;
  4352. var width = header.width, height = header.height;
  4353. var i = 0, x, y;
  4354. var imageData = new Uint8Array(width * height * 4);
  4355. for (y = y_start; y !== y_end; y += y_step) {
  4356. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4357. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4358. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4359. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4360. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4361. }
  4362. }
  4363. return imageData;
  4364. };
  4365. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4366. var image = pixel_data;
  4367. var width = header.width, height = header.height;
  4368. var color, i = 0, x, y;
  4369. var imageData = new Uint8Array(width * height * 4);
  4370. for (y = y_start; y !== y_end; y += y_step) {
  4371. for (x = x_start; x !== x_end; x += x_step, i++) {
  4372. color = image[i];
  4373. imageData[(x + width * y) * 4 + 0] = color;
  4374. imageData[(x + width * y) * 4 + 1] = color;
  4375. imageData[(x + width * y) * 4 + 2] = color;
  4376. imageData[(x + width * y) * 4 + 3] = 255;
  4377. }
  4378. }
  4379. return imageData;
  4380. };
  4381. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4382. var image = pixel_data;
  4383. var width = header.width, height = header.height;
  4384. var i = 0, x, y;
  4385. var imageData = new Uint8Array(width * height * 4);
  4386. for (y = y_start; y !== y_end; y += y_step) {
  4387. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4388. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4389. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4390. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4391. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4392. }
  4393. }
  4394. return imageData;
  4395. };
  4396. TGATools._TYPE_NO_DATA = 0;
  4397. TGATools._TYPE_INDEXED = 1;
  4398. TGATools._TYPE_RGB = 2;
  4399. TGATools._TYPE_GREY = 3;
  4400. TGATools._TYPE_RLE_INDEXED = 9;
  4401. TGATools._TYPE_RLE_RGB = 10;
  4402. TGATools._TYPE_RLE_GREY = 11;
  4403. TGATools._ORIGIN_MASK = 0x30;
  4404. TGATools._ORIGIN_SHIFT = 0x04;
  4405. TGATools._ORIGIN_BL = 0x00;
  4406. TGATools._ORIGIN_BR = 0x01;
  4407. TGATools._ORIGIN_UL = 0x02;
  4408. TGATools._ORIGIN_UR = 0x03;
  4409. return TGATools;
  4410. }());
  4411. Internals.TGATools = TGATools;
  4412. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4413. })(BABYLON || (BABYLON = {}));
  4414. //# sourceMappingURL=babylon.tools.tga.js.map
  4415. var BABYLON;
  4416. (function (BABYLON) {
  4417. var SmartArray = (function () {
  4418. function SmartArray(capacity) {
  4419. this.length = 0;
  4420. this._duplicateId = 0;
  4421. this.data = new Array(capacity);
  4422. this._id = SmartArray._GlobalId++;
  4423. }
  4424. SmartArray.prototype.push = function (value) {
  4425. this.data[this.length++] = value;
  4426. if (this.length > this.data.length) {
  4427. this.data.length *= 2;
  4428. }
  4429. if (!value.__smartArrayFlags) {
  4430. value.__smartArrayFlags = {};
  4431. }
  4432. value.__smartArrayFlags[this._id] = this._duplicateId;
  4433. };
  4434. SmartArray.prototype.pushNoDuplicate = function (value) {
  4435. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4436. return false;
  4437. }
  4438. this.push(value);
  4439. return true;
  4440. };
  4441. SmartArray.prototype.sort = function (compareFn) {
  4442. this.data.sort(compareFn);
  4443. };
  4444. SmartArray.prototype.reset = function () {
  4445. this.length = 0;
  4446. this._duplicateId++;
  4447. };
  4448. SmartArray.prototype.concat = function (array) {
  4449. if (array.length === 0) {
  4450. return;
  4451. }
  4452. if (this.length + array.length > this.data.length) {
  4453. this.data.length = (this.length + array.length) * 2;
  4454. }
  4455. for (var index = 0; index < array.length; index++) {
  4456. this.data[this.length++] = (array.data || array)[index];
  4457. }
  4458. };
  4459. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4460. if (array.length === 0) {
  4461. return;
  4462. }
  4463. if (this.length + array.length > this.data.length) {
  4464. this.data.length = (this.length + array.length) * 2;
  4465. }
  4466. for (var index = 0; index < array.length; index++) {
  4467. var item = (array.data || array)[index];
  4468. this.pushNoDuplicate(item);
  4469. }
  4470. };
  4471. SmartArray.prototype.indexOf = function (value) {
  4472. var position = this.data.indexOf(value);
  4473. if (position >= this.length) {
  4474. return -1;
  4475. }
  4476. return position;
  4477. };
  4478. // Statics
  4479. SmartArray._GlobalId = 0;
  4480. return SmartArray;
  4481. }());
  4482. BABYLON.SmartArray = SmartArray;
  4483. })(BABYLON || (BABYLON = {}));
  4484. //# sourceMappingURL=babylon.smartArray.js.map
  4485. var BABYLON;
  4486. (function (BABYLON) {
  4487. /**
  4488. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4489. * The underlying implementation relies on an associative array to ensure the best performances.
  4490. * The value can be anything including 'null' but except 'undefined'
  4491. */
  4492. var StringDictionary = (function () {
  4493. function StringDictionary() {
  4494. this._count = 0;
  4495. this._data = {};
  4496. }
  4497. /**
  4498. * This will clear this dictionary and copy the content from the 'source' one.
  4499. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4500. * @param source the dictionary to take the content from and copy to this dictionary
  4501. */
  4502. StringDictionary.prototype.copyFrom = function (source) {
  4503. var _this = this;
  4504. this.clear();
  4505. source.forEach(function (t, v) { return _this.add(t, v); });
  4506. };
  4507. /**
  4508. * Get a value based from its key
  4509. * @param key the given key to get the matching value from
  4510. * @return the value if found, otherwise undefined is returned
  4511. */
  4512. StringDictionary.prototype.get = function (key) {
  4513. var val = this._data[key];
  4514. if (val !== undefined) {
  4515. return val;
  4516. }
  4517. return undefined;
  4518. };
  4519. /**
  4520. * Get a value from its key or add it if it doesn't exist.
  4521. * This method will ensure you that a given key/data will be present in the dictionary.
  4522. * @param key the given key to get the matching value from
  4523. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4524. * The factory will only be invoked if there's no data for the given key.
  4525. * @return the value corresponding to the key.
  4526. */
  4527. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4528. var val = this.get(key);
  4529. if (val !== undefined) {
  4530. return val;
  4531. }
  4532. val = factory(key);
  4533. if (val) {
  4534. this.add(key, val);
  4535. }
  4536. return val;
  4537. };
  4538. /**
  4539. * Get a value from its key if present in the dictionary otherwise add it
  4540. * @param key the key to get the value from
  4541. * @param val if there's no such key/value pair in the dictionary add it with this value
  4542. * @return the value corresponding to the key
  4543. */
  4544. StringDictionary.prototype.getOrAdd = function (key, val) {
  4545. var curVal = this.get(key);
  4546. if (curVal !== undefined) {
  4547. return curVal;
  4548. }
  4549. this.add(key, val);
  4550. return val;
  4551. };
  4552. /**
  4553. * Check if there's a given key in the dictionary
  4554. * @param key the key to check for
  4555. * @return true if the key is present, false otherwise
  4556. */
  4557. StringDictionary.prototype.contains = function (key) {
  4558. return this._data[key] !== undefined;
  4559. };
  4560. /**
  4561. * Add a new key and its corresponding value
  4562. * @param key the key to add
  4563. * @param value the value corresponding to the key
  4564. * @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
  4565. */
  4566. StringDictionary.prototype.add = function (key, value) {
  4567. if (this._data[key] !== undefined) {
  4568. return false;
  4569. }
  4570. this._data[key] = value;
  4571. ++this._count;
  4572. return true;
  4573. };
  4574. StringDictionary.prototype.set = function (key, value) {
  4575. if (this._data[key] === undefined) {
  4576. return false;
  4577. }
  4578. this._data[key] = value;
  4579. return true;
  4580. };
  4581. /**
  4582. * Get the element of the given key and remove it from the dictionary
  4583. * @param key
  4584. */
  4585. StringDictionary.prototype.getAndRemove = function (key) {
  4586. var val = this.get(key);
  4587. if (val !== undefined) {
  4588. delete this._data[key];
  4589. --this._count;
  4590. return val;
  4591. }
  4592. return null;
  4593. };
  4594. /**
  4595. * Remove a key/value from the dictionary.
  4596. * @param key the key to remove
  4597. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4598. */
  4599. StringDictionary.prototype.remove = function (key) {
  4600. if (this.contains(key)) {
  4601. delete this._data[key];
  4602. --this._count;
  4603. return true;
  4604. }
  4605. return false;
  4606. };
  4607. /**
  4608. * Clear the whole content of the dictionary
  4609. */
  4610. StringDictionary.prototype.clear = function () {
  4611. this._data = {};
  4612. this._count = 0;
  4613. };
  4614. Object.defineProperty(StringDictionary.prototype, "count", {
  4615. get: function () {
  4616. return this._count;
  4617. },
  4618. enumerable: true,
  4619. configurable: true
  4620. });
  4621. /**
  4622. * Execute a callback on each key/val of the dictionary.
  4623. * Note that you can remove any element in this dictionary in the callback implementation
  4624. * @param callback the callback to execute on a given key/value pair
  4625. */
  4626. StringDictionary.prototype.forEach = function (callback) {
  4627. for (var cur in this._data) {
  4628. var val = this._data[cur];
  4629. callback(cur, val);
  4630. }
  4631. };
  4632. /**
  4633. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4634. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4635. * Note that you can remove any element in this dictionary in the callback implementation
  4636. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4637. */
  4638. StringDictionary.prototype.first = function (callback) {
  4639. for (var cur in this._data) {
  4640. var val = this._data[cur];
  4641. var res = callback(cur, val);
  4642. if (res) {
  4643. return res;
  4644. }
  4645. }
  4646. return null;
  4647. };
  4648. return StringDictionary;
  4649. }());
  4650. BABYLON.StringDictionary = StringDictionary;
  4651. })(BABYLON || (BABYLON = {}));
  4652. //# sourceMappingURL=babylon.stringDictionary.js.map
  4653. var BABYLON;
  4654. (function (BABYLON) {
  4655. // Screenshots
  4656. var screenshotCanvas;
  4657. var cloneValue = function (source, destinationObject) {
  4658. if (!source)
  4659. return null;
  4660. if (source instanceof BABYLON.Mesh) {
  4661. return null;
  4662. }
  4663. if (source instanceof BABYLON.SubMesh) {
  4664. return source.clone(destinationObject);
  4665. }
  4666. else if (source.clone) {
  4667. return source.clone();
  4668. }
  4669. return null;
  4670. };
  4671. var Tools = (function () {
  4672. function Tools() {
  4673. }
  4674. Tools.Instantiate = function (className) {
  4675. var arr = className.split(".");
  4676. var fn = (window || this);
  4677. for (var i = 0, len = arr.length; i < len; i++) {
  4678. fn = fn[arr[i]];
  4679. }
  4680. if (typeof fn !== "function") {
  4681. return null;
  4682. }
  4683. return fn;
  4684. };
  4685. Tools.SetImmediate = function (action) {
  4686. if (window.setImmediate) {
  4687. window.setImmediate(action);
  4688. }
  4689. else {
  4690. setTimeout(action, 1);
  4691. }
  4692. };
  4693. Tools.IsExponentOfTwo = function (value) {
  4694. var count = 1;
  4695. do {
  4696. count *= 2;
  4697. } while (count < value);
  4698. return count === value;
  4699. };
  4700. Tools.GetExponentOfTwo = function (value, max) {
  4701. var count = 1;
  4702. do {
  4703. count *= 2;
  4704. } while (count < value);
  4705. if (count > max)
  4706. count = max;
  4707. return count;
  4708. };
  4709. Tools.GetFilename = function (path) {
  4710. var index = path.lastIndexOf("/");
  4711. if (index < 0)
  4712. return path;
  4713. return path.substring(index + 1);
  4714. };
  4715. Tools.GetDOMTextContent = function (element) {
  4716. var result = "";
  4717. var child = element.firstChild;
  4718. while (child) {
  4719. if (child.nodeType === 3) {
  4720. result += child.textContent;
  4721. }
  4722. child = child.nextSibling;
  4723. }
  4724. return result;
  4725. };
  4726. Tools.ToDegrees = function (angle) {
  4727. return angle * 180 / Math.PI;
  4728. };
  4729. Tools.ToRadians = function (angle) {
  4730. return angle * Math.PI / 180;
  4731. };
  4732. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4733. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4734. var output = "";
  4735. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4736. var i = 0;
  4737. var bytes = new Uint8Array(buffer);
  4738. while (i < bytes.length) {
  4739. chr1 = bytes[i++];
  4740. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4741. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4742. enc1 = chr1 >> 2;
  4743. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4744. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4745. enc4 = chr3 & 63;
  4746. if (isNaN(chr2)) {
  4747. enc3 = enc4 = 64;
  4748. }
  4749. else if (isNaN(chr3)) {
  4750. enc4 = 64;
  4751. }
  4752. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4753. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4754. }
  4755. return "data:image/png;base64," + output;
  4756. };
  4757. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4758. if (bias === void 0) { bias = null; }
  4759. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4760. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4761. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4762. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4763. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4764. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4765. }
  4766. if (bias) {
  4767. minimum.x -= minimum.x * bias.x + bias.y;
  4768. minimum.y -= minimum.y * bias.x + bias.y;
  4769. minimum.z -= minimum.z * bias.x + bias.y;
  4770. maximum.x += maximum.x * bias.x + bias.y;
  4771. maximum.y += maximum.y * bias.x + bias.y;
  4772. maximum.z += maximum.z * bias.x + bias.y;
  4773. }
  4774. return {
  4775. minimum: minimum,
  4776. maximum: maximum
  4777. };
  4778. };
  4779. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4780. if (bias === void 0) { bias = null; }
  4781. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4782. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4783. if (!stride) {
  4784. stride = 3;
  4785. }
  4786. for (var index = start; index < start + count; index++) {
  4787. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4788. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4789. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4790. }
  4791. if (bias) {
  4792. minimum.x -= minimum.x * bias.x + bias.y;
  4793. minimum.y -= minimum.y * bias.x + bias.y;
  4794. minimum.z -= minimum.z * bias.x + bias.y;
  4795. maximum.x += maximum.x * bias.x + bias.y;
  4796. maximum.y += maximum.y * bias.x + bias.y;
  4797. maximum.z += maximum.z * bias.x + bias.y;
  4798. }
  4799. return {
  4800. minimum: minimum,
  4801. maximum: maximum
  4802. };
  4803. };
  4804. Tools.Vector2ArrayFeeder = function (array) {
  4805. return function (index) {
  4806. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4807. var length = isFloatArray ? array.length / 2 : array.length;
  4808. if (index >= length) {
  4809. return null;
  4810. }
  4811. if (isFloatArray) {
  4812. var fa = array;
  4813. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4814. }
  4815. var a = array;
  4816. return a[index];
  4817. };
  4818. };
  4819. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4820. if (bias === void 0) { bias = null; }
  4821. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4822. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4823. var i = 0;
  4824. var cur = feeder(i++);
  4825. while (cur) {
  4826. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4827. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4828. cur = feeder(i++);
  4829. }
  4830. if (bias) {
  4831. minimum.x -= minimum.x * bias.x + bias.y;
  4832. minimum.y -= minimum.y * bias.x + bias.y;
  4833. maximum.x += maximum.x * bias.x + bias.y;
  4834. maximum.y += maximum.y * bias.x + bias.y;
  4835. }
  4836. return {
  4837. minimum: minimum,
  4838. maximum: maximum
  4839. };
  4840. };
  4841. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4842. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4843. return undefined;
  4844. return Array.isArray(obj) ? obj : [obj];
  4845. };
  4846. // Misc.
  4847. Tools.GetPointerPrefix = function () {
  4848. var eventPrefix = "pointer";
  4849. // Check if pointer events are supported
  4850. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4851. eventPrefix = "mouse";
  4852. }
  4853. return eventPrefix;
  4854. };
  4855. /**
  4856. * @param func - the function to be called
  4857. * @param requester - the object that will request the next frame. Falls back to window.
  4858. */
  4859. Tools.QueueNewFrame = function (func, requester) {
  4860. if (requester === void 0) { requester = window; }
  4861. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4862. /*if(requester.isPresenting) {
  4863. return;
  4864. } else*/ if (requester.requestAnimationFrame)
  4865. requester.requestAnimationFrame(func);
  4866. else if (requester.msRequestAnimationFrame)
  4867. requester.msRequestAnimationFrame(func);
  4868. else if (requester.webkitRequestAnimationFrame)
  4869. requester.webkitRequestAnimationFrame(func);
  4870. else if (requester.mozRequestAnimationFrame)
  4871. requester.mozRequestAnimationFrame(func);
  4872. else if (requester.oRequestAnimationFrame)
  4873. requester.oRequestAnimationFrame(func);
  4874. else {
  4875. window.setTimeout(func, 16);
  4876. }
  4877. };
  4878. Tools.RequestFullscreen = function (element) {
  4879. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4880. if (!requestFunction)
  4881. return;
  4882. requestFunction.call(element);
  4883. };
  4884. Tools.ExitFullscreen = function () {
  4885. if (document.exitFullscreen) {
  4886. document.exitFullscreen();
  4887. }
  4888. else if (document.mozCancelFullScreen) {
  4889. document.mozCancelFullScreen();
  4890. }
  4891. else if (document.webkitCancelFullScreen) {
  4892. document.webkitCancelFullScreen();
  4893. }
  4894. else if (document.msCancelFullScreen) {
  4895. document.msCancelFullScreen();
  4896. }
  4897. };
  4898. Tools.SetCorsBehavior = function (url, img) {
  4899. if (Tools.CorsBehavior) {
  4900. switch (typeof (Tools.CorsBehavior)) {
  4901. case "function":
  4902. var result = Tools.CorsBehavior(url);
  4903. if (result) {
  4904. return result;
  4905. }
  4906. break;
  4907. case "string":
  4908. default:
  4909. img.crossOrigin = Tools.CorsBehavior;
  4910. break;
  4911. }
  4912. }
  4913. };
  4914. // External files
  4915. Tools.CleanUrl = function (url) {
  4916. url = url.replace(/#/mg, "%23");
  4917. return url;
  4918. };
  4919. Tools.LoadImage = function (url, onload, onerror, database) {
  4920. if (url instanceof ArrayBuffer) {
  4921. url = Tools.EncodeArrayBufferTobase64(url);
  4922. }
  4923. url = Tools.CleanUrl(url);
  4924. var img = new Image();
  4925. if (url.substr(0, 5) !== "data:") {
  4926. Tools.SetCorsBehavior(url, img);
  4927. }
  4928. img.onload = function () {
  4929. onload(img);
  4930. };
  4931. img.onerror = function (err) {
  4932. Tools.Error("Error while trying to load texture: " + url);
  4933. if (Tools.UseFallbackTexture) {
  4934. 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";
  4935. onload(img);
  4936. }
  4937. else {
  4938. onerror();
  4939. }
  4940. };
  4941. var noIndexedDB = function () {
  4942. img.src = url;
  4943. };
  4944. var loadFromIndexedDB = function () {
  4945. database.loadImageFromDB(url, img);
  4946. };
  4947. //ANY database to do!
  4948. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4949. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4950. }
  4951. else {
  4952. if (url.indexOf("file:") === -1) {
  4953. noIndexedDB();
  4954. }
  4955. else {
  4956. try {
  4957. var textureName = url.substring(5).toLowerCase();
  4958. var blobURL;
  4959. try {
  4960. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4961. }
  4962. catch (ex) {
  4963. // Chrome doesn't support oneTimeOnly parameter
  4964. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4965. }
  4966. img.src = blobURL;
  4967. }
  4968. catch (e) {
  4969. img.src = null;
  4970. }
  4971. }
  4972. }
  4973. return img;
  4974. };
  4975. //ANY
  4976. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4977. url = Tools.CleanUrl(url);
  4978. var noIndexedDB = function () {
  4979. var request = new XMLHttpRequest();
  4980. var loadUrl = Tools.BaseUrl + url;
  4981. request.open('GET', loadUrl, true);
  4982. if (useArrayBuffer) {
  4983. request.responseType = "arraybuffer";
  4984. }
  4985. request.onprogress = progressCallBack;
  4986. request.onreadystatechange = function () {
  4987. if (request.readyState === 4) {
  4988. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4989. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4990. callback(!useArrayBuffer ? request.responseText : request.response);
  4991. }
  4992. else {
  4993. if (onError) {
  4994. onError();
  4995. }
  4996. else {
  4997. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4998. }
  4999. }
  5000. }
  5001. };
  5002. request.send(null);
  5003. };
  5004. var loadFromIndexedDB = function () {
  5005. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5006. };
  5007. if (url.indexOf("file:") !== -1) {
  5008. var fileName = url.substring(5).toLowerCase();
  5009. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5010. }
  5011. else {
  5012. // Caching all files
  5013. if (database && database.enableSceneOffline) {
  5014. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5015. }
  5016. else {
  5017. noIndexedDB();
  5018. }
  5019. }
  5020. };
  5021. /**
  5022. * Load a script (identified by an url). When the url returns, the
  5023. * content of this file is added into a new script element, attached to the DOM (body element)
  5024. */
  5025. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5026. var head = document.getElementsByTagName('head')[0];
  5027. var script = document.createElement('script');
  5028. script.type = 'text/javascript';
  5029. script.src = scriptUrl;
  5030. var self = this;
  5031. script.onload = function () {
  5032. if (onSuccess) {
  5033. onSuccess();
  5034. }
  5035. };
  5036. script.onerror = function () {
  5037. if (onError) {
  5038. onError();
  5039. }
  5040. };
  5041. head.appendChild(script);
  5042. };
  5043. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5044. var reader = new FileReader();
  5045. reader.onload = function (e) {
  5046. //target doesn't have result from ts 1.3
  5047. callback(e.target['result']);
  5048. };
  5049. reader.onprogress = progressCallback;
  5050. reader.readAsDataURL(fileToLoad);
  5051. };
  5052. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5053. var reader = new FileReader();
  5054. reader.onerror = function (e) {
  5055. Tools.Log("Error while reading file: " + fileToLoad.name);
  5056. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5057. };
  5058. reader.onload = function (e) {
  5059. //target doesn't have result from ts 1.3
  5060. callback(e.target['result']);
  5061. };
  5062. reader.onprogress = progressCallBack;
  5063. if (!useArrayBuffer) {
  5064. // Asynchronous read
  5065. reader.readAsText(fileToLoad);
  5066. }
  5067. else {
  5068. reader.readAsArrayBuffer(fileToLoad);
  5069. }
  5070. };
  5071. //returns a downloadable url to a file content.
  5072. Tools.FileAsURL = function (content) {
  5073. var fileBlob = new Blob([content]);
  5074. var url = window.URL || window.webkitURL;
  5075. var link = url.createObjectURL(fileBlob);
  5076. return link;
  5077. };
  5078. // Misc.
  5079. Tools.Format = function (value, decimals) {
  5080. if (decimals === void 0) { decimals = 2; }
  5081. return value.toFixed(decimals);
  5082. };
  5083. Tools.CheckExtends = function (v, min, max) {
  5084. if (v.x < min.x)
  5085. min.x = v.x;
  5086. if (v.y < min.y)
  5087. min.y = v.y;
  5088. if (v.z < min.z)
  5089. min.z = v.z;
  5090. if (v.x > max.x)
  5091. max.x = v.x;
  5092. if (v.y > max.y)
  5093. max.y = v.y;
  5094. if (v.z > max.z)
  5095. max.z = v.z;
  5096. };
  5097. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5098. for (var prop in source) {
  5099. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5100. continue;
  5101. }
  5102. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5103. continue;
  5104. }
  5105. var sourceValue = source[prop];
  5106. var typeOfSourceValue = typeof sourceValue;
  5107. if (typeOfSourceValue === "function") {
  5108. continue;
  5109. }
  5110. if (typeOfSourceValue === "object") {
  5111. if (sourceValue instanceof Array) {
  5112. destination[prop] = [];
  5113. if (sourceValue.length > 0) {
  5114. if (typeof sourceValue[0] == "object") {
  5115. for (var index = 0; index < sourceValue.length; index++) {
  5116. var clonedValue = cloneValue(sourceValue[index], destination);
  5117. if (destination[prop].indexOf(clonedValue) === -1) {
  5118. destination[prop].push(clonedValue);
  5119. }
  5120. }
  5121. }
  5122. else {
  5123. destination[prop] = sourceValue.slice(0);
  5124. }
  5125. }
  5126. }
  5127. else {
  5128. destination[prop] = cloneValue(sourceValue, destination);
  5129. }
  5130. }
  5131. else {
  5132. destination[prop] = sourceValue;
  5133. }
  5134. }
  5135. };
  5136. Tools.IsEmpty = function (obj) {
  5137. for (var i in obj) {
  5138. return false;
  5139. }
  5140. return true;
  5141. };
  5142. Tools.RegisterTopRootEvents = function (events) {
  5143. for (var index = 0; index < events.length; index++) {
  5144. var event = events[index];
  5145. window.addEventListener(event.name, event.handler, false);
  5146. try {
  5147. if (window.parent) {
  5148. window.parent.addEventListener(event.name, event.handler, false);
  5149. }
  5150. }
  5151. catch (e) {
  5152. }
  5153. }
  5154. };
  5155. Tools.UnregisterTopRootEvents = function (events) {
  5156. for (var index = 0; index < events.length; index++) {
  5157. var event = events[index];
  5158. window.removeEventListener(event.name, event.handler);
  5159. try {
  5160. if (window.parent) {
  5161. window.parent.removeEventListener(event.name, event.handler);
  5162. }
  5163. }
  5164. catch (e) {
  5165. }
  5166. }
  5167. };
  5168. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5169. if (mimeType === void 0) { mimeType = "image/png"; }
  5170. // Read the contents of the framebuffer
  5171. var numberOfChannelsByLine = width * 4;
  5172. var halfHeight = height / 2;
  5173. //Reading datas from WebGL
  5174. var data = engine.readPixels(0, 0, width, height);
  5175. //To flip image on Y axis.
  5176. for (var i = 0; i < halfHeight; i++) {
  5177. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5178. var currentCell = j + i * numberOfChannelsByLine;
  5179. var targetLine = height - i - 1;
  5180. var targetCell = j + targetLine * numberOfChannelsByLine;
  5181. var temp = data[currentCell];
  5182. data[currentCell] = data[targetCell];
  5183. data[targetCell] = temp;
  5184. }
  5185. }
  5186. // Create a 2D canvas to store the result
  5187. if (!screenshotCanvas) {
  5188. screenshotCanvas = document.createElement('canvas');
  5189. }
  5190. screenshotCanvas.width = width;
  5191. screenshotCanvas.height = height;
  5192. var context = screenshotCanvas.getContext('2d');
  5193. // Copy the pixels to a 2D canvas
  5194. var imageData = context.createImageData(width, height);
  5195. var castData = (imageData.data);
  5196. castData.set(data);
  5197. context.putImageData(imageData, 0, 0);
  5198. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5199. };
  5200. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5201. if (mimeType === void 0) { mimeType = "image/png"; }
  5202. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5203. if (successCallback) {
  5204. successCallback(base64Image);
  5205. }
  5206. else {
  5207. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5208. if (("download" in document.createElement("a"))) {
  5209. var a = window.document.createElement("a");
  5210. a.href = base64Image;
  5211. var date = new Date();
  5212. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5213. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5214. window.document.body.appendChild(a);
  5215. a.addEventListener("click", function () {
  5216. a.parentElement.removeChild(a);
  5217. });
  5218. a.click();
  5219. }
  5220. else {
  5221. var newWindow = window.open("");
  5222. var img = newWindow.document.createElement("img");
  5223. img.src = base64Image;
  5224. newWindow.document.body.appendChild(img);
  5225. }
  5226. }
  5227. };
  5228. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5229. if (mimeType === void 0) { mimeType = "image/png"; }
  5230. var width;
  5231. var height;
  5232. // If a precision value is specified
  5233. if (size.precision) {
  5234. width = Math.round(engine.getRenderWidth() * size.precision);
  5235. height = Math.round(width / engine.getAspectRatio(camera));
  5236. }
  5237. else if (size.width && size.height) {
  5238. width = size.width;
  5239. height = size.height;
  5240. }
  5241. else if (size.width && !size.height) {
  5242. width = size.width;
  5243. height = Math.round(width / engine.getAspectRatio(camera));
  5244. }
  5245. else if (size.height && !size.width) {
  5246. height = size.height;
  5247. width = Math.round(height * engine.getAspectRatio(camera));
  5248. }
  5249. else if (!isNaN(size)) {
  5250. height = size;
  5251. width = size;
  5252. }
  5253. else {
  5254. Tools.Error("Invalid 'size' parameter !");
  5255. return;
  5256. }
  5257. if (!screenshotCanvas) {
  5258. screenshotCanvas = document.createElement('canvas');
  5259. }
  5260. screenshotCanvas.width = width;
  5261. screenshotCanvas.height = height;
  5262. var renderContext = screenshotCanvas.getContext("2d");
  5263. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5264. var newWidth = width;
  5265. var newHeight = newWidth / ratio;
  5266. if (newHeight > height) {
  5267. newHeight = height;
  5268. newWidth = newHeight * ratio;
  5269. }
  5270. var offsetX = Math.max(0, width - newWidth) / 2;
  5271. var offsetY = Math.max(0, height - newHeight) / 2;
  5272. renderContext.fillStyle = camera.getScene().clearColor.toHexString();
  5273. renderContext.fillRect(0, 0, width, height);
  5274. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5275. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5276. };
  5277. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5278. if (mimeType === void 0) { mimeType = "image/png"; }
  5279. var width;
  5280. var height;
  5281. //If a precision value is specified
  5282. if (size.precision) {
  5283. width = Math.round(engine.getRenderWidth() * size.precision);
  5284. height = Math.round(width / engine.getAspectRatio(camera));
  5285. size = { width: width, height: height };
  5286. }
  5287. else if (size.width && size.height) {
  5288. width = size.width;
  5289. height = size.height;
  5290. }
  5291. else if (size.width && !size.height) {
  5292. width = size.width;
  5293. height = Math.round(width / engine.getAspectRatio(camera));
  5294. size = { width: width, height: height };
  5295. }
  5296. else if (size.height && !size.width) {
  5297. height = size.height;
  5298. width = Math.round(height * engine.getAspectRatio(camera));
  5299. size = { width: width, height: height };
  5300. }
  5301. else if (!isNaN(size)) {
  5302. height = size;
  5303. width = size;
  5304. }
  5305. else {
  5306. Tools.Error("Invalid 'size' parameter !");
  5307. return;
  5308. }
  5309. var scene = camera.getScene();
  5310. var previousCamera = null;
  5311. if (scene.activeCamera !== camera) {
  5312. previousCamera = scene.activeCamera;
  5313. scene.activeCamera = camera;
  5314. }
  5315. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5316. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5317. texture.renderList = scene.meshes;
  5318. texture.onAfterRenderObservable.add(function () {
  5319. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5320. });
  5321. scene.incrementRenderId();
  5322. scene.resetCachedMaterial();
  5323. texture.render(true);
  5324. texture.dispose();
  5325. if (previousCamera) {
  5326. scene.activeCamera = previousCamera;
  5327. }
  5328. camera.getProjectionMatrix(true); // Force cache refresh;
  5329. };
  5330. // XHR response validator for local file scenario
  5331. Tools.ValidateXHRData = function (xhr, dataType) {
  5332. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5333. if (dataType === void 0) { dataType = 7; }
  5334. try {
  5335. if (dataType & 1) {
  5336. if (xhr.responseText && xhr.responseText.length > 0) {
  5337. return true;
  5338. }
  5339. else if (dataType === 1) {
  5340. return false;
  5341. }
  5342. }
  5343. if (dataType & 2) {
  5344. // Check header width and height since there is no "TGA" magic number
  5345. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5346. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5347. return true;
  5348. }
  5349. else if (dataType === 2) {
  5350. return false;
  5351. }
  5352. }
  5353. if (dataType & 4) {
  5354. // Check for the "DDS" magic number
  5355. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5356. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5357. return true;
  5358. }
  5359. else {
  5360. return false;
  5361. }
  5362. }
  5363. }
  5364. catch (e) {
  5365. }
  5366. return false;
  5367. };
  5368. /**
  5369. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5370. * Be aware Math.random() could cause collisions, but:
  5371. * "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"
  5372. */
  5373. Tools.RandomId = function () {
  5374. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5375. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5376. return v.toString(16);
  5377. });
  5378. };
  5379. Object.defineProperty(Tools, "NoneLogLevel", {
  5380. get: function () {
  5381. return Tools._NoneLogLevel;
  5382. },
  5383. enumerable: true,
  5384. configurable: true
  5385. });
  5386. Object.defineProperty(Tools, "MessageLogLevel", {
  5387. get: function () {
  5388. return Tools._MessageLogLevel;
  5389. },
  5390. enumerable: true,
  5391. configurable: true
  5392. });
  5393. Object.defineProperty(Tools, "WarningLogLevel", {
  5394. get: function () {
  5395. return Tools._WarningLogLevel;
  5396. },
  5397. enumerable: true,
  5398. configurable: true
  5399. });
  5400. Object.defineProperty(Tools, "ErrorLogLevel", {
  5401. get: function () {
  5402. return Tools._ErrorLogLevel;
  5403. },
  5404. enumerable: true,
  5405. configurable: true
  5406. });
  5407. Object.defineProperty(Tools, "AllLogLevel", {
  5408. get: function () {
  5409. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5410. },
  5411. enumerable: true,
  5412. configurable: true
  5413. });
  5414. Tools._AddLogEntry = function (entry) {
  5415. Tools._LogCache = entry + Tools._LogCache;
  5416. if (Tools.OnNewCacheEntry) {
  5417. Tools.OnNewCacheEntry(entry);
  5418. }
  5419. };
  5420. Tools._FormatMessage = function (message) {
  5421. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5422. var date = new Date();
  5423. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5424. };
  5425. Tools._LogDisabled = function (message) {
  5426. // nothing to do
  5427. };
  5428. Tools._LogEnabled = function (message) {
  5429. var formattedMessage = Tools._FormatMessage(message);
  5430. console.log("BJS - " + formattedMessage);
  5431. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5432. Tools._AddLogEntry(entry);
  5433. };
  5434. Tools._WarnDisabled = function (message) {
  5435. // nothing to do
  5436. };
  5437. Tools._WarnEnabled = function (message) {
  5438. var formattedMessage = Tools._FormatMessage(message);
  5439. console.warn("BJS - " + formattedMessage);
  5440. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5441. Tools._AddLogEntry(entry);
  5442. };
  5443. Tools._ErrorDisabled = function (message) {
  5444. // nothing to do
  5445. };
  5446. Tools._ErrorEnabled = function (message) {
  5447. Tools.errorsCount++;
  5448. var formattedMessage = Tools._FormatMessage(message);
  5449. console.error("BJS - " + formattedMessage);
  5450. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5451. Tools._AddLogEntry(entry);
  5452. };
  5453. Object.defineProperty(Tools, "LogCache", {
  5454. get: function () {
  5455. return Tools._LogCache;
  5456. },
  5457. enumerable: true,
  5458. configurable: true
  5459. });
  5460. Tools.ClearLogCache = function () {
  5461. Tools._LogCache = "";
  5462. Tools.errorsCount = 0;
  5463. };
  5464. Object.defineProperty(Tools, "LogLevels", {
  5465. set: function (level) {
  5466. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5467. Tools.Log = Tools._LogEnabled;
  5468. }
  5469. else {
  5470. Tools.Log = Tools._LogDisabled;
  5471. }
  5472. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5473. Tools.Warn = Tools._WarnEnabled;
  5474. }
  5475. else {
  5476. Tools.Warn = Tools._WarnDisabled;
  5477. }
  5478. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5479. Tools.Error = Tools._ErrorEnabled;
  5480. }
  5481. else {
  5482. Tools.Error = Tools._ErrorDisabled;
  5483. }
  5484. },
  5485. enumerable: true,
  5486. configurable: true
  5487. });
  5488. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5489. get: function () {
  5490. return Tools._PerformanceNoneLogLevel;
  5491. },
  5492. enumerable: true,
  5493. configurable: true
  5494. });
  5495. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5496. get: function () {
  5497. return Tools._PerformanceUserMarkLogLevel;
  5498. },
  5499. enumerable: true,
  5500. configurable: true
  5501. });
  5502. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5503. get: function () {
  5504. return Tools._PerformanceConsoleLogLevel;
  5505. },
  5506. enumerable: true,
  5507. configurable: true
  5508. });
  5509. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5510. set: function (level) {
  5511. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5512. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5513. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5514. return;
  5515. }
  5516. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5517. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5518. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5519. return;
  5520. }
  5521. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5522. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5523. },
  5524. enumerable: true,
  5525. configurable: true
  5526. });
  5527. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5528. };
  5529. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5530. };
  5531. Tools._StartUserMark = function (counterName, condition) {
  5532. if (condition === void 0) { condition = true; }
  5533. if (!condition || !Tools._performance.mark) {
  5534. return;
  5535. }
  5536. Tools._performance.mark(counterName + "-Begin");
  5537. };
  5538. Tools._EndUserMark = function (counterName, condition) {
  5539. if (condition === void 0) { condition = true; }
  5540. if (!condition || !Tools._performance.mark) {
  5541. return;
  5542. }
  5543. Tools._performance.mark(counterName + "-End");
  5544. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5545. };
  5546. Tools._StartPerformanceConsole = function (counterName, condition) {
  5547. if (condition === void 0) { condition = true; }
  5548. if (!condition) {
  5549. return;
  5550. }
  5551. Tools._StartUserMark(counterName, condition);
  5552. if (console.time) {
  5553. console.time(counterName);
  5554. }
  5555. };
  5556. Tools._EndPerformanceConsole = function (counterName, condition) {
  5557. if (condition === void 0) { condition = true; }
  5558. if (!condition) {
  5559. return;
  5560. }
  5561. Tools._EndUserMark(counterName, condition);
  5562. if (console.time) {
  5563. console.timeEnd(counterName);
  5564. }
  5565. };
  5566. Object.defineProperty(Tools, "Now", {
  5567. get: function () {
  5568. if (window.performance && window.performance.now) {
  5569. return window.performance.now();
  5570. }
  5571. return new Date().getTime();
  5572. },
  5573. enumerable: true,
  5574. configurable: true
  5575. });
  5576. /**
  5577. * This method will return the name of the class used to create the instance of the given object.
  5578. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5579. * @param object the object to get the class name from
  5580. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5581. */
  5582. Tools.getClassName = function (object, isType) {
  5583. if (isType === void 0) { isType = false; }
  5584. var name = null;
  5585. if (!isType && object.getClassName) {
  5586. name = object.getClassName();
  5587. }
  5588. else {
  5589. if (object instanceof Object) {
  5590. var classObj = isType ? object : Object.getPrototypeOf(object);
  5591. name = classObj.constructor["__bjsclassName__"];
  5592. }
  5593. if (!name) {
  5594. name = typeof object;
  5595. }
  5596. }
  5597. return name;
  5598. };
  5599. Tools.first = function (array, predicate) {
  5600. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5601. var el = array_1[_i];
  5602. if (predicate(el)) {
  5603. return el;
  5604. }
  5605. }
  5606. };
  5607. /**
  5608. * This method will return the name of the full name of the class, including its owning module (if any).
  5609. * 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).
  5610. * @param object the object to get the class name from
  5611. * @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.
  5612. */
  5613. Tools.getFullClassName = function (object, isType) {
  5614. if (isType === void 0) { isType = false; }
  5615. var className = null;
  5616. var moduleName = null;
  5617. if (!isType && object.getClassName) {
  5618. className = object.getClassName();
  5619. }
  5620. else {
  5621. if (object instanceof Object) {
  5622. var classObj = isType ? object : Object.getPrototypeOf(object);
  5623. className = classObj.constructor["__bjsclassName__"];
  5624. moduleName = classObj.constructor["__bjsmoduleName__"];
  5625. }
  5626. if (!className) {
  5627. className = typeof object;
  5628. }
  5629. }
  5630. if (!className) {
  5631. return null;
  5632. }
  5633. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5634. };
  5635. /**
  5636. * 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.
  5637. * @param array
  5638. */
  5639. Tools.arrayOrStringFeeder = function (array) {
  5640. return function (index) {
  5641. if (index >= array.length) {
  5642. return null;
  5643. }
  5644. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5645. if (val && val.getHashCode) {
  5646. val = val.getHashCode();
  5647. }
  5648. if (typeof val === "string") {
  5649. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5650. }
  5651. return val;
  5652. };
  5653. };
  5654. /**
  5655. * Compute the hashCode of a stream of number
  5656. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5657. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5658. * @return the hash code computed
  5659. */
  5660. Tools.hashCodeFromStream = function (feeder) {
  5661. // Based from here: http://stackoverflow.com/a/7616484/802124
  5662. var hash = 0;
  5663. var index = 0;
  5664. var chr = feeder(index++);
  5665. while (chr != null) {
  5666. hash = ((hash << 5) - hash) + chr;
  5667. hash |= 0; // Convert to 32bit integer
  5668. chr = feeder(index++);
  5669. }
  5670. return hash;
  5671. };
  5672. Tools.BaseUrl = "";
  5673. Tools.CorsBehavior = "anonymous";
  5674. Tools.UseFallbackTexture = true;
  5675. // Logs
  5676. Tools._NoneLogLevel = 0;
  5677. Tools._MessageLogLevel = 1;
  5678. Tools._WarningLogLevel = 2;
  5679. Tools._ErrorLogLevel = 4;
  5680. Tools._LogCache = "";
  5681. Tools.errorsCount = 0;
  5682. Tools.Log = Tools._LogEnabled;
  5683. Tools.Warn = Tools._WarnEnabled;
  5684. Tools.Error = Tools._ErrorEnabled;
  5685. // Performances
  5686. Tools._PerformanceNoneLogLevel = 0;
  5687. Tools._PerformanceUserMarkLogLevel = 1;
  5688. Tools._PerformanceConsoleLogLevel = 2;
  5689. Tools._performance = window.performance;
  5690. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5691. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5692. return Tools;
  5693. }());
  5694. BABYLON.Tools = Tools;
  5695. /**
  5696. * This class is used to track a performance counter which is number based.
  5697. * The user has access to many properties which give statistics of different nature
  5698. *
  5699. * The implementer can track two kinds of Performance Counter: time and count
  5700. * 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.
  5701. * 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.
  5702. */
  5703. var PerfCounter = (function () {
  5704. function PerfCounter() {
  5705. this._startMonitoringTime = 0;
  5706. this._min = 0;
  5707. this._max = 0;
  5708. this._average = 0;
  5709. this._lastSecAverage = 0;
  5710. this._current = 0;
  5711. this._totalValueCount = 0;
  5712. this._totalAccumulated = 0;
  5713. this._lastSecAccumulated = 0;
  5714. this._lastSecTime = 0;
  5715. this._lastSecValueCount = 0;
  5716. }
  5717. Object.defineProperty(PerfCounter.prototype, "min", {
  5718. /**
  5719. * Returns the smallest value ever
  5720. */
  5721. get: function () {
  5722. return this._min;
  5723. },
  5724. enumerable: true,
  5725. configurable: true
  5726. });
  5727. Object.defineProperty(PerfCounter.prototype, "max", {
  5728. /**
  5729. * Returns the biggest value ever
  5730. */
  5731. get: function () {
  5732. return this._max;
  5733. },
  5734. enumerable: true,
  5735. configurable: true
  5736. });
  5737. Object.defineProperty(PerfCounter.prototype, "average", {
  5738. /**
  5739. * Returns the average value since the performance counter is running
  5740. */
  5741. get: function () {
  5742. return this._average;
  5743. },
  5744. enumerable: true,
  5745. configurable: true
  5746. });
  5747. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5748. /**
  5749. * Returns the average value of the last second the counter was monitored
  5750. */
  5751. get: function () {
  5752. return this._lastSecAverage;
  5753. },
  5754. enumerable: true,
  5755. configurable: true
  5756. });
  5757. Object.defineProperty(PerfCounter.prototype, "current", {
  5758. /**
  5759. * Returns the current value
  5760. */
  5761. get: function () {
  5762. return this._current;
  5763. },
  5764. enumerable: true,
  5765. configurable: true
  5766. });
  5767. Object.defineProperty(PerfCounter.prototype, "total", {
  5768. get: function () {
  5769. return this._totalAccumulated;
  5770. },
  5771. enumerable: true,
  5772. configurable: true
  5773. });
  5774. /**
  5775. * Call this method to start monitoring a new frame.
  5776. * 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.
  5777. */
  5778. PerfCounter.prototype.fetchNewFrame = function () {
  5779. this._totalValueCount++;
  5780. this._current = 0;
  5781. this._lastSecValueCount++;
  5782. };
  5783. /**
  5784. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5785. * @param newCount the count value to add to the monitored count
  5786. * @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.
  5787. */
  5788. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5789. this._current += newCount;
  5790. if (fetchResult) {
  5791. this._fetchResult();
  5792. }
  5793. };
  5794. /**
  5795. * Start monitoring this performance counter
  5796. */
  5797. PerfCounter.prototype.beginMonitoring = function () {
  5798. this._startMonitoringTime = Tools.Now;
  5799. };
  5800. /**
  5801. * Compute the time lapsed since the previous beginMonitoring() call.
  5802. * @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
  5803. */
  5804. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5805. if (newFrame === void 0) { newFrame = true; }
  5806. if (newFrame) {
  5807. this.fetchNewFrame();
  5808. }
  5809. var currentTime = Tools.Now;
  5810. this._current = currentTime - this._startMonitoringTime;
  5811. if (newFrame) {
  5812. this._fetchResult();
  5813. }
  5814. };
  5815. PerfCounter.prototype._fetchResult = function () {
  5816. this._totalAccumulated += this._current;
  5817. this._lastSecAccumulated += this._current;
  5818. // Min/Max update
  5819. this._min = Math.min(this._min, this._current);
  5820. this._max = Math.max(this._max, this._current);
  5821. this._average = this._totalAccumulated / this._totalValueCount;
  5822. // Reset last sec?
  5823. var now = Tools.Now;
  5824. if ((now - this._lastSecTime) > 1000) {
  5825. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5826. this._lastSecTime = now;
  5827. this._lastSecAccumulated = 0;
  5828. this._lastSecValueCount = 0;
  5829. }
  5830. };
  5831. return PerfCounter;
  5832. }());
  5833. BABYLON.PerfCounter = PerfCounter;
  5834. /**
  5835. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5836. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5837. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5838. * @param name The name of the class, case should be preserved
  5839. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5840. */
  5841. function className(name, module) {
  5842. return function (target) {
  5843. target["__bjsclassName__"] = name;
  5844. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5845. };
  5846. }
  5847. BABYLON.className = className;
  5848. /**
  5849. * An implementation of a loop for asynchronous functions.
  5850. */
  5851. var AsyncLoop = (function () {
  5852. /**
  5853. * Constroctor.
  5854. * @param iterations the number of iterations.
  5855. * @param _fn the function to run each iteration
  5856. * @param _successCallback the callback that will be called upon succesful execution
  5857. * @param offset starting offset.
  5858. */
  5859. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5860. if (offset === void 0) { offset = 0; }
  5861. this.iterations = iterations;
  5862. this._fn = _fn;
  5863. this._successCallback = _successCallback;
  5864. this.index = offset - 1;
  5865. this._done = false;
  5866. }
  5867. /**
  5868. * Execute the next iteration. Must be called after the last iteration was finished.
  5869. */
  5870. AsyncLoop.prototype.executeNext = function () {
  5871. if (!this._done) {
  5872. if (this.index + 1 < this.iterations) {
  5873. ++this.index;
  5874. this._fn(this);
  5875. }
  5876. else {
  5877. this.breakLoop();
  5878. }
  5879. }
  5880. };
  5881. /**
  5882. * Break the loop and run the success callback.
  5883. */
  5884. AsyncLoop.prototype.breakLoop = function () {
  5885. this._done = true;
  5886. this._successCallback();
  5887. };
  5888. /**
  5889. * Helper function
  5890. */
  5891. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5892. if (offset === void 0) { offset = 0; }
  5893. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5894. loop.executeNext();
  5895. return loop;
  5896. };
  5897. /**
  5898. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5899. * @param iterations total number of iterations
  5900. * @param syncedIterations number of synchronous iterations in each async iteration.
  5901. * @param fn the function to call each iteration.
  5902. * @param callback a success call back that will be called when iterating stops.
  5903. * @param breakFunction a break condition (optional)
  5904. * @param timeout timeout settings for the setTimeout function. default - 0.
  5905. * @constructor
  5906. */
  5907. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5908. if (timeout === void 0) { timeout = 0; }
  5909. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5910. if (breakFunction && breakFunction())
  5911. loop.breakLoop();
  5912. else {
  5913. setTimeout(function () {
  5914. for (var i = 0; i < syncedIterations; ++i) {
  5915. var iteration = (loop.index * syncedIterations) + i;
  5916. if (iteration >= iterations)
  5917. break;
  5918. fn(iteration);
  5919. if (breakFunction && breakFunction()) {
  5920. loop.breakLoop();
  5921. break;
  5922. }
  5923. }
  5924. loop.executeNext();
  5925. }, timeout);
  5926. }
  5927. }, callback);
  5928. };
  5929. return AsyncLoop;
  5930. }());
  5931. BABYLON.AsyncLoop = AsyncLoop;
  5932. })(BABYLON || (BABYLON = {}));
  5933. //# sourceMappingURL=babylon.tools.js.map
  5934. var BABYLON;
  5935. (function (BABYLON) {
  5936. var Internals;
  5937. (function (Internals) {
  5938. var _AlphaState = (function () {
  5939. /**
  5940. * Initializes the state.
  5941. */
  5942. function _AlphaState() {
  5943. this._isAlphaBlendDirty = false;
  5944. this._isBlendFunctionParametersDirty = false;
  5945. this._alphaBlend = false;
  5946. this._blendFunctionParameters = new Array(4);
  5947. this.reset();
  5948. }
  5949. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5950. get: function () {
  5951. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5952. },
  5953. enumerable: true,
  5954. configurable: true
  5955. });
  5956. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5957. get: function () {
  5958. return this._alphaBlend;
  5959. },
  5960. set: function (value) {
  5961. if (this._alphaBlend === value) {
  5962. return;
  5963. }
  5964. this._alphaBlend = value;
  5965. this._isAlphaBlendDirty = true;
  5966. },
  5967. enumerable: true,
  5968. configurable: true
  5969. });
  5970. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5971. if (this._blendFunctionParameters[0] === value0 &&
  5972. this._blendFunctionParameters[1] === value1 &&
  5973. this._blendFunctionParameters[2] === value2 &&
  5974. this._blendFunctionParameters[3] === value3) {
  5975. return;
  5976. }
  5977. this._blendFunctionParameters[0] = value0;
  5978. this._blendFunctionParameters[1] = value1;
  5979. this._blendFunctionParameters[2] = value2;
  5980. this._blendFunctionParameters[3] = value3;
  5981. this._isBlendFunctionParametersDirty = true;
  5982. };
  5983. _AlphaState.prototype.reset = function () {
  5984. this._alphaBlend = false;
  5985. this._blendFunctionParameters[0] = null;
  5986. this._blendFunctionParameters[1] = null;
  5987. this._blendFunctionParameters[2] = null;
  5988. this._blendFunctionParameters[3] = null;
  5989. this._isAlphaBlendDirty = true;
  5990. this._isBlendFunctionParametersDirty = false;
  5991. };
  5992. _AlphaState.prototype.apply = function (gl) {
  5993. if (!this.isDirty) {
  5994. return;
  5995. }
  5996. // Alpha blend
  5997. if (this._isAlphaBlendDirty) {
  5998. if (this._alphaBlend) {
  5999. gl.enable(gl.BLEND);
  6000. }
  6001. else {
  6002. gl.disable(gl.BLEND);
  6003. }
  6004. this._isAlphaBlendDirty = false;
  6005. }
  6006. // Alpha function
  6007. if (this._isBlendFunctionParametersDirty) {
  6008. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6009. this._isBlendFunctionParametersDirty = false;
  6010. }
  6011. };
  6012. return _AlphaState;
  6013. }());
  6014. Internals._AlphaState = _AlphaState;
  6015. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6016. })(BABYLON || (BABYLON = {}));
  6017. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6018. var BABYLON;
  6019. (function (BABYLON) {
  6020. var Internals;
  6021. (function (Internals) {
  6022. var _DepthCullingState = (function () {
  6023. /**
  6024. * Initializes the state.
  6025. */
  6026. function _DepthCullingState() {
  6027. this._isDepthTestDirty = false;
  6028. this._isDepthMaskDirty = false;
  6029. this._isDepthFuncDirty = false;
  6030. this._isCullFaceDirty = false;
  6031. this._isCullDirty = false;
  6032. this._isZOffsetDirty = false;
  6033. this.reset();
  6034. }
  6035. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6036. get: function () {
  6037. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6038. },
  6039. enumerable: true,
  6040. configurable: true
  6041. });
  6042. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6043. get: function () {
  6044. return this._zOffset;
  6045. },
  6046. set: function (value) {
  6047. if (this._zOffset === value) {
  6048. return;
  6049. }
  6050. this._zOffset = value;
  6051. this._isZOffsetDirty = true;
  6052. },
  6053. enumerable: true,
  6054. configurable: true
  6055. });
  6056. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6057. get: function () {
  6058. return this._cullFace;
  6059. },
  6060. set: function (value) {
  6061. if (this._cullFace === value) {
  6062. return;
  6063. }
  6064. this._cullFace = value;
  6065. this._isCullFaceDirty = true;
  6066. },
  6067. enumerable: true,
  6068. configurable: true
  6069. });
  6070. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6071. get: function () {
  6072. return this._cull;
  6073. },
  6074. set: function (value) {
  6075. if (this._cull === value) {
  6076. return;
  6077. }
  6078. this._cull = value;
  6079. this._isCullDirty = true;
  6080. },
  6081. enumerable: true,
  6082. configurable: true
  6083. });
  6084. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6085. get: function () {
  6086. return this._depthFunc;
  6087. },
  6088. set: function (value) {
  6089. if (this._depthFunc === value) {
  6090. return;
  6091. }
  6092. this._depthFunc = value;
  6093. this._isDepthFuncDirty = true;
  6094. },
  6095. enumerable: true,
  6096. configurable: true
  6097. });
  6098. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6099. get: function () {
  6100. return this._depthMask;
  6101. },
  6102. set: function (value) {
  6103. if (this._depthMask === value) {
  6104. return;
  6105. }
  6106. this._depthMask = value;
  6107. this._isDepthMaskDirty = true;
  6108. },
  6109. enumerable: true,
  6110. configurable: true
  6111. });
  6112. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6113. get: function () {
  6114. return this._depthTest;
  6115. },
  6116. set: function (value) {
  6117. if (this._depthTest === value) {
  6118. return;
  6119. }
  6120. this._depthTest = value;
  6121. this._isDepthTestDirty = true;
  6122. },
  6123. enumerable: true,
  6124. configurable: true
  6125. });
  6126. _DepthCullingState.prototype.reset = function () {
  6127. this._depthMask = true;
  6128. this._depthTest = true;
  6129. this._depthFunc = null;
  6130. this._cullFace = null;
  6131. this._cull = null;
  6132. this._zOffset = 0;
  6133. this._isDepthTestDirty = true;
  6134. this._isDepthMaskDirty = true;
  6135. this._isDepthFuncDirty = false;
  6136. this._isCullFaceDirty = false;
  6137. this._isCullDirty = false;
  6138. this._isZOffsetDirty = false;
  6139. };
  6140. _DepthCullingState.prototype.apply = function (gl) {
  6141. if (!this.isDirty) {
  6142. return;
  6143. }
  6144. // Cull
  6145. if (this._isCullDirty) {
  6146. if (this.cull) {
  6147. gl.enable(gl.CULL_FACE);
  6148. }
  6149. else {
  6150. gl.disable(gl.CULL_FACE);
  6151. }
  6152. this._isCullDirty = false;
  6153. }
  6154. // Cull face
  6155. if (this._isCullFaceDirty) {
  6156. gl.cullFace(this.cullFace);
  6157. this._isCullFaceDirty = false;
  6158. }
  6159. // Depth mask
  6160. if (this._isDepthMaskDirty) {
  6161. gl.depthMask(this.depthMask);
  6162. this._isDepthMaskDirty = false;
  6163. }
  6164. // Depth test
  6165. if (this._isDepthTestDirty) {
  6166. if (this.depthTest) {
  6167. gl.enable(gl.DEPTH_TEST);
  6168. }
  6169. else {
  6170. gl.disable(gl.DEPTH_TEST);
  6171. }
  6172. this._isDepthTestDirty = false;
  6173. }
  6174. // Depth func
  6175. if (this._isDepthFuncDirty) {
  6176. gl.depthFunc(this.depthFunc);
  6177. this._isDepthFuncDirty = false;
  6178. }
  6179. // zOffset
  6180. if (this._isZOffsetDirty) {
  6181. if (this.zOffset) {
  6182. gl.enable(gl.POLYGON_OFFSET_FILL);
  6183. gl.polygonOffset(this.zOffset, 0);
  6184. }
  6185. else {
  6186. gl.disable(gl.POLYGON_OFFSET_FILL);
  6187. }
  6188. this._isZOffsetDirty = false;
  6189. }
  6190. };
  6191. return _DepthCullingState;
  6192. }());
  6193. Internals._DepthCullingState = _DepthCullingState;
  6194. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6195. })(BABYLON || (BABYLON = {}));
  6196. //# sourceMappingURL=babylon.depthCullingState.js.map
  6197. var BABYLON;
  6198. (function (BABYLON) {
  6199. var Internals;
  6200. (function (Internals) {
  6201. var _StencilState = (function () {
  6202. function _StencilState() {
  6203. this._isStencilTestDirty = false;
  6204. this._isStencilMaskDirty = false;
  6205. this._isStencilFuncDirty = false;
  6206. this._isStencilOpDirty = false;
  6207. this.reset();
  6208. }
  6209. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6210. get: function () {
  6211. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6217. get: function () {
  6218. return this._stencilFunc;
  6219. },
  6220. set: function (value) {
  6221. if (this._stencilFunc === value) {
  6222. return;
  6223. }
  6224. this._stencilFunc = value;
  6225. this._isStencilFuncDirty = true;
  6226. },
  6227. enumerable: true,
  6228. configurable: true
  6229. });
  6230. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6231. get: function () {
  6232. return this._stencilFuncRef;
  6233. },
  6234. set: function (value) {
  6235. if (this._stencilFuncRef === value) {
  6236. return;
  6237. }
  6238. this._stencilFuncRef = value;
  6239. this._isStencilFuncDirty = true;
  6240. },
  6241. enumerable: true,
  6242. configurable: true
  6243. });
  6244. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6245. get: function () {
  6246. return this._stencilFuncMask;
  6247. },
  6248. set: function (value) {
  6249. if (this._stencilFuncMask === value) {
  6250. return;
  6251. }
  6252. this._stencilFuncMask = value;
  6253. this._isStencilFuncDirty = true;
  6254. },
  6255. enumerable: true,
  6256. configurable: true
  6257. });
  6258. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6259. get: function () {
  6260. return this._stencilOpStencilFail;
  6261. },
  6262. set: function (value) {
  6263. if (this._stencilOpStencilFail === value) {
  6264. return;
  6265. }
  6266. this._stencilOpStencilFail = value;
  6267. this._isStencilOpDirty = true;
  6268. },
  6269. enumerable: true,
  6270. configurable: true
  6271. });
  6272. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6273. get: function () {
  6274. return this._stencilOpDepthFail;
  6275. },
  6276. set: function (value) {
  6277. if (this._stencilOpDepthFail === value) {
  6278. return;
  6279. }
  6280. this._stencilOpDepthFail = value;
  6281. this._isStencilOpDirty = true;
  6282. },
  6283. enumerable: true,
  6284. configurable: true
  6285. });
  6286. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6287. get: function () {
  6288. return this._stencilOpStencilDepthPass;
  6289. },
  6290. set: function (value) {
  6291. if (this._stencilOpStencilDepthPass === value) {
  6292. return;
  6293. }
  6294. this._stencilOpStencilDepthPass = value;
  6295. this._isStencilOpDirty = true;
  6296. },
  6297. enumerable: true,
  6298. configurable: true
  6299. });
  6300. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6301. get: function () {
  6302. return this._stencilMask;
  6303. },
  6304. set: function (value) {
  6305. if (this._stencilMask === value) {
  6306. return;
  6307. }
  6308. this._stencilMask = value;
  6309. this._isStencilMaskDirty = true;
  6310. },
  6311. enumerable: true,
  6312. configurable: true
  6313. });
  6314. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6315. get: function () {
  6316. return this._stencilTest;
  6317. },
  6318. set: function (value) {
  6319. if (this._stencilTest === value) {
  6320. return;
  6321. }
  6322. this._stencilTest = value;
  6323. this._isStencilTestDirty = true;
  6324. },
  6325. enumerable: true,
  6326. configurable: true
  6327. });
  6328. _StencilState.prototype.reset = function () {
  6329. this._stencilTest = false;
  6330. this._stencilMask = 0xFF;
  6331. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6332. this._stencilFuncRef = 1;
  6333. this._stencilFuncMask = 0xFF;
  6334. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6335. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6336. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6337. this._isStencilTestDirty = true;
  6338. this._isStencilMaskDirty = true;
  6339. this._isStencilFuncDirty = true;
  6340. this._isStencilOpDirty = true;
  6341. };
  6342. _StencilState.prototype.apply = function (gl) {
  6343. if (!this.isDirty) {
  6344. return;
  6345. }
  6346. // Stencil test
  6347. if (this._isStencilTestDirty) {
  6348. if (this.stencilTest) {
  6349. gl.enable(gl.STENCIL_TEST);
  6350. }
  6351. else {
  6352. gl.disable(gl.STENCIL_TEST);
  6353. }
  6354. this._isStencilTestDirty = false;
  6355. }
  6356. // Stencil mask
  6357. if (this._isStencilMaskDirty) {
  6358. gl.stencilMask(this.stencilMask);
  6359. this._isStencilMaskDirty = false;
  6360. }
  6361. // Stencil func
  6362. if (this._isStencilFuncDirty) {
  6363. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6364. this._isStencilFuncDirty = false;
  6365. }
  6366. // Stencil op
  6367. if (this._isStencilOpDirty) {
  6368. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6369. this._isStencilOpDirty = false;
  6370. }
  6371. };
  6372. return _StencilState;
  6373. }());
  6374. Internals._StencilState = _StencilState;
  6375. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6376. })(BABYLON || (BABYLON = {}));
  6377. //# sourceMappingURL=babylon.stencilState.js.map
  6378. var BABYLON;
  6379. (function (BABYLON) {
  6380. var compileShader = function (gl, source, type, defines) {
  6381. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6382. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6383. gl.compileShader(shader);
  6384. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6385. throw new Error(gl.getShaderInfoLog(shader));
  6386. }
  6387. return shader;
  6388. };
  6389. var HALF_FLOAT_OES = 0x8D61;
  6390. var getWebGLTextureType = function (gl, type) {
  6391. if (type === Engine.TEXTURETYPE_FLOAT) {
  6392. return gl.FLOAT;
  6393. }
  6394. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6395. // Add Half Float Constant.
  6396. return HALF_FLOAT_OES;
  6397. }
  6398. return gl.UNSIGNED_BYTE;
  6399. };
  6400. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6401. var magFilter = gl.NEAREST;
  6402. var minFilter = gl.NEAREST;
  6403. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6404. magFilter = gl.LINEAR;
  6405. if (generateMipMaps) {
  6406. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6407. }
  6408. else {
  6409. minFilter = gl.LINEAR;
  6410. }
  6411. }
  6412. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6413. magFilter = gl.LINEAR;
  6414. if (generateMipMaps) {
  6415. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6416. }
  6417. else {
  6418. minFilter = gl.LINEAR;
  6419. }
  6420. }
  6421. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6422. magFilter = gl.NEAREST;
  6423. if (generateMipMaps) {
  6424. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6425. }
  6426. else {
  6427. minFilter = gl.NEAREST;
  6428. }
  6429. }
  6430. return {
  6431. min: minFilter,
  6432. mag: magFilter
  6433. };
  6434. };
  6435. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6437. var engine = scene.getEngine();
  6438. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6439. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6440. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6441. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6442. texture._baseWidth = width;
  6443. texture._baseHeight = height;
  6444. texture._width = potWidth;
  6445. texture._height = potHeight;
  6446. texture.isReady = true;
  6447. processFunction(potWidth, potHeight);
  6448. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6450. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6451. if (!noMipmap && !isCompressed) {
  6452. gl.generateMipmap(gl.TEXTURE_2D);
  6453. }
  6454. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6455. engine.resetTextureCache();
  6456. scene._removePendingData(texture);
  6457. texture.onLoadedCallbacks.forEach(function (callback) {
  6458. callback();
  6459. });
  6460. texture.onLoadedCallbacks = [];
  6461. };
  6462. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6463. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6464. var img;
  6465. var onload = function () {
  6466. loadedImages[index] = img;
  6467. loadedImages._internalCount++;
  6468. scene._removePendingData(img);
  6469. if (loadedImages._internalCount === 6) {
  6470. onfinish(loadedImages);
  6471. }
  6472. };
  6473. var onerror = function () {
  6474. scene._removePendingData(img);
  6475. if (onErrorCallBack) {
  6476. onErrorCallBack();
  6477. }
  6478. };
  6479. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6480. scene._addPendingData(img);
  6481. };
  6482. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6483. if (onError === void 0) { onError = null; }
  6484. var loadedImages = [];
  6485. loadedImages._internalCount = 0;
  6486. for (var index = 0; index < 6; index++) {
  6487. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6488. }
  6489. };
  6490. var InstancingAttributeInfo = (function () {
  6491. function InstancingAttributeInfo() {
  6492. }
  6493. return InstancingAttributeInfo;
  6494. }());
  6495. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6496. var EngineCapabilities = (function () {
  6497. function EngineCapabilities() {
  6498. }
  6499. return EngineCapabilities;
  6500. }());
  6501. BABYLON.EngineCapabilities = EngineCapabilities;
  6502. /**
  6503. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6504. */
  6505. var Engine = (function () {
  6506. /**
  6507. * @constructor
  6508. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6509. * @param {boolean} [antialias] - enable antialias
  6510. * @param options - further options to be sent to the getContext function
  6511. */
  6512. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6513. var _this = this;
  6514. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6515. // Public members
  6516. this.isFullscreen = false;
  6517. this.isPointerLock = false;
  6518. this.cullBackFaces = true;
  6519. this.renderEvenInBackground = true;
  6520. // To enable/disable IDB support and avoid XHR on .manifest
  6521. this.enableOfflineSupport = true;
  6522. this.scenes = new Array();
  6523. this._windowIsBackground = false;
  6524. this._webGLVersion = "1.0";
  6525. this._badOS = false;
  6526. this._drawCalls = new BABYLON.PerfCounter();
  6527. this._renderingQueueLaunched = false;
  6528. this._activeRenderLoops = [];
  6529. // FPS
  6530. this.fpsRange = 60;
  6531. this.previousFramesDuration = [];
  6532. this.fps = 60;
  6533. this.deltaTime = 0;
  6534. // States
  6535. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6536. this._stencilState = new BABYLON.Internals._StencilState();
  6537. this._alphaState = new BABYLON.Internals._AlphaState();
  6538. this._alphaMode = Engine.ALPHA_DISABLE;
  6539. // Cache
  6540. this._loadedTexturesCache = new Array();
  6541. this._maxTextureChannels = 16;
  6542. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6543. this._compiledEffects = {};
  6544. this._vertexAttribArraysEnabled = [];
  6545. this._uintIndicesCurrentlySet = false;
  6546. this._currentBoundBuffer = new Array();
  6547. this._currentBufferPointers = [];
  6548. this._currentInstanceLocations = new Array();
  6549. this._currentInstanceBuffers = new Array();
  6550. // Hardware supported Compressed Textures
  6551. this._texturesSupported = new Array();
  6552. this._onVRFullScreenTriggered = function () {
  6553. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6554. //get the old size before we change
  6555. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6556. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6557. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6558. //But actually, no browser follow the specs...
  6559. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6560. //get the width and height, change the render size
  6561. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6562. var width, height;
  6563. _this.setHardwareScalingLevel(1);
  6564. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6565. }
  6566. else {
  6567. //When the specs are implemented, need to uncomment this.
  6568. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6569. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6570. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6571. _this._vrDisplayEnabled = undefined;
  6572. }
  6573. };
  6574. this._renderingCanvas = canvas;
  6575. this._externalData = new BABYLON.StringDictionary();
  6576. options = options || {};
  6577. if (antialias != null) {
  6578. options.antialias = antialias;
  6579. }
  6580. if (options.preserveDrawingBuffer === undefined) {
  6581. options.preserveDrawingBuffer = false;
  6582. }
  6583. // Checks if some of the format renders first to allow the use of webgl inspector.
  6584. var renderToFullFloat = this._canRenderToFloatTexture();
  6585. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6586. // GL
  6587. //try {
  6588. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6589. // if (this._gl) {
  6590. // this._webGLVersion = "2.0";
  6591. // }
  6592. //} catch (e) {
  6593. // // Do nothing
  6594. //}
  6595. if (!this._gl) {
  6596. if (!canvas) {
  6597. throw new Error("The provided canvas is null or undefined.");
  6598. }
  6599. try {
  6600. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6601. }
  6602. catch (e) {
  6603. throw new Error("WebGL not supported");
  6604. }
  6605. }
  6606. if (!this._gl) {
  6607. throw new Error("WebGL not supported");
  6608. }
  6609. this._onBlur = function () {
  6610. _this._windowIsBackground = true;
  6611. };
  6612. this._onFocus = function () {
  6613. _this._windowIsBackground = false;
  6614. };
  6615. window.addEventListener("blur", this._onBlur);
  6616. window.addEventListener("focus", this._onFocus);
  6617. // Viewport
  6618. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6619. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6620. this.resize();
  6621. // Caps
  6622. this._isStencilEnable = options.stencil;
  6623. this._caps = new EngineCapabilities();
  6624. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6625. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6626. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6627. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6628. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6629. // Infos
  6630. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6631. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6632. if (rendererInfo != null) {
  6633. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6634. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6635. }
  6636. if (!this._glVendor) {
  6637. this._glVendor = "Unknown vendor";
  6638. }
  6639. if (!this._glRenderer) {
  6640. this._glRenderer = "Unknown renderer";
  6641. }
  6642. // Extensions
  6643. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6644. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc');
  6645. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6646. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); // 2nd is what iOS reports
  6647. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1');
  6648. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // first is the final name, found hardware using 2nd
  6649. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6650. 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');
  6651. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6652. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6653. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6654. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6655. this._caps.highPrecisionShaderSupported = true;
  6656. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6657. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6658. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6659. this._caps.textureFloatRender = renderToFullFloat;
  6660. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6661. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6662. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6663. // Intelligently add supported commpressed formats in order to check for.
  6664. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6665. // Next PVR & S3, which are probably superior to ETC1/2.
  6666. // Likely no hardware which supports both PVR & S3, so order matters little.
  6667. // ETC2 is newer and handles ETC1, so check for first.
  6668. if (this._caps.astc)
  6669. this.texturesSupported.push('.astc');
  6670. if (this._caps.s3tc)
  6671. this.texturesSupported.push('.dds');
  6672. if (this._caps.pvrtc)
  6673. this.texturesSupported.push('.pvr');
  6674. if (this._caps.etc2)
  6675. this.texturesSupported.push('.etc2');
  6676. if (this._caps.etc1)
  6677. this.texturesSupported.push('.etc1');
  6678. if (this._gl.getShaderPrecisionFormat) {
  6679. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6680. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6681. }
  6682. // Depth buffer
  6683. this.setDepthBuffer(true);
  6684. this.setDepthFunctionToLessOrEqual();
  6685. this.setDepthWrite(true);
  6686. // Fullscreen
  6687. this._onFullscreenChange = function () {
  6688. if (document.fullscreen !== undefined) {
  6689. _this.isFullscreen = document.fullscreen;
  6690. }
  6691. else if (document.mozFullScreen !== undefined) {
  6692. _this.isFullscreen = document.mozFullScreen;
  6693. }
  6694. else if (document.webkitIsFullScreen !== undefined) {
  6695. _this.isFullscreen = document.webkitIsFullScreen;
  6696. }
  6697. else if (document.msIsFullScreen !== undefined) {
  6698. _this.isFullscreen = document.msIsFullScreen;
  6699. }
  6700. // Pointer lock
  6701. if (_this.isFullscreen && _this._pointerLockRequested) {
  6702. canvas.requestPointerLock = canvas.requestPointerLock ||
  6703. canvas.msRequestPointerLock ||
  6704. canvas.mozRequestPointerLock ||
  6705. canvas.webkitRequestPointerLock;
  6706. if (canvas.requestPointerLock) {
  6707. canvas.requestPointerLock();
  6708. }
  6709. }
  6710. };
  6711. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6712. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6713. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6714. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6715. // Pointer lock
  6716. this._onPointerLockChange = function () {
  6717. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6718. document.webkitPointerLockElement === canvas ||
  6719. document.msPointerLockElement === canvas ||
  6720. document.pointerLockElement === canvas);
  6721. };
  6722. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6723. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6724. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6725. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6726. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6727. Engine.audioEngine = new BABYLON.AudioEngine();
  6728. }
  6729. //default loading screen
  6730. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6731. //Load WebVR Devices
  6732. if (options.autoEnableWebVR) {
  6733. this.initWebVR();
  6734. }
  6735. //Detect if we are running on a faulty buggy OS.
  6736. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6737. //ua sniffing is the tool of the devil.
  6738. this._badOS = regexp.test(navigator.userAgent);
  6739. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6740. }
  6741. Object.defineProperty(Engine, "NEVER", {
  6742. get: function () {
  6743. return Engine._NEVER;
  6744. },
  6745. enumerable: true,
  6746. configurable: true
  6747. });
  6748. Object.defineProperty(Engine, "ALWAYS", {
  6749. get: function () {
  6750. return Engine._ALWAYS;
  6751. },
  6752. enumerable: true,
  6753. configurable: true
  6754. });
  6755. Object.defineProperty(Engine, "LESS", {
  6756. get: function () {
  6757. return Engine._LESS;
  6758. },
  6759. enumerable: true,
  6760. configurable: true
  6761. });
  6762. Object.defineProperty(Engine, "EQUAL", {
  6763. get: function () {
  6764. return Engine._EQUAL;
  6765. },
  6766. enumerable: true,
  6767. configurable: true
  6768. });
  6769. Object.defineProperty(Engine, "LEQUAL", {
  6770. get: function () {
  6771. return Engine._LEQUAL;
  6772. },
  6773. enumerable: true,
  6774. configurable: true
  6775. });
  6776. Object.defineProperty(Engine, "GREATER", {
  6777. get: function () {
  6778. return Engine._GREATER;
  6779. },
  6780. enumerable: true,
  6781. configurable: true
  6782. });
  6783. Object.defineProperty(Engine, "GEQUAL", {
  6784. get: function () {
  6785. return Engine._GEQUAL;
  6786. },
  6787. enumerable: true,
  6788. configurable: true
  6789. });
  6790. Object.defineProperty(Engine, "NOTEQUAL", {
  6791. get: function () {
  6792. return Engine._NOTEQUAL;
  6793. },
  6794. enumerable: true,
  6795. configurable: true
  6796. });
  6797. Object.defineProperty(Engine, "KEEP", {
  6798. get: function () {
  6799. return Engine._KEEP;
  6800. },
  6801. enumerable: true,
  6802. configurable: true
  6803. });
  6804. Object.defineProperty(Engine, "REPLACE", {
  6805. get: function () {
  6806. return Engine._REPLACE;
  6807. },
  6808. enumerable: true,
  6809. configurable: true
  6810. });
  6811. Object.defineProperty(Engine, "INCR", {
  6812. get: function () {
  6813. return Engine._INCR;
  6814. },
  6815. enumerable: true,
  6816. configurable: true
  6817. });
  6818. Object.defineProperty(Engine, "DECR", {
  6819. get: function () {
  6820. return Engine._DECR;
  6821. },
  6822. enumerable: true,
  6823. configurable: true
  6824. });
  6825. Object.defineProperty(Engine, "INVERT", {
  6826. get: function () {
  6827. return Engine._INVERT;
  6828. },
  6829. enumerable: true,
  6830. configurable: true
  6831. });
  6832. Object.defineProperty(Engine, "INCR_WRAP", {
  6833. get: function () {
  6834. return Engine._INCR_WRAP;
  6835. },
  6836. enumerable: true,
  6837. configurable: true
  6838. });
  6839. Object.defineProperty(Engine, "DECR_WRAP", {
  6840. get: function () {
  6841. return Engine._DECR_WRAP;
  6842. },
  6843. enumerable: true,
  6844. configurable: true
  6845. });
  6846. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6847. get: function () {
  6848. return Engine._ALPHA_DISABLE;
  6849. },
  6850. enumerable: true,
  6851. configurable: true
  6852. });
  6853. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6854. get: function () {
  6855. return Engine._ALPHA_ONEONE;
  6856. },
  6857. enumerable: true,
  6858. configurable: true
  6859. });
  6860. Object.defineProperty(Engine, "ALPHA_ADD", {
  6861. get: function () {
  6862. return Engine._ALPHA_ADD;
  6863. },
  6864. enumerable: true,
  6865. configurable: true
  6866. });
  6867. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6868. get: function () {
  6869. return Engine._ALPHA_COMBINE;
  6870. },
  6871. enumerable: true,
  6872. configurable: true
  6873. });
  6874. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6875. get: function () {
  6876. return Engine._ALPHA_SUBTRACT;
  6877. },
  6878. enumerable: true,
  6879. configurable: true
  6880. });
  6881. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6882. get: function () {
  6883. return Engine._ALPHA_MULTIPLY;
  6884. },
  6885. enumerable: true,
  6886. configurable: true
  6887. });
  6888. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6889. get: function () {
  6890. return Engine._ALPHA_MAXIMIZED;
  6891. },
  6892. enumerable: true,
  6893. configurable: true
  6894. });
  6895. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6896. get: function () {
  6897. return Engine._DELAYLOADSTATE_NONE;
  6898. },
  6899. enumerable: true,
  6900. configurable: true
  6901. });
  6902. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6903. get: function () {
  6904. return Engine._DELAYLOADSTATE_LOADED;
  6905. },
  6906. enumerable: true,
  6907. configurable: true
  6908. });
  6909. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6910. get: function () {
  6911. return Engine._DELAYLOADSTATE_LOADING;
  6912. },
  6913. enumerable: true,
  6914. configurable: true
  6915. });
  6916. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6917. get: function () {
  6918. return Engine._DELAYLOADSTATE_NOTLOADED;
  6919. },
  6920. enumerable: true,
  6921. configurable: true
  6922. });
  6923. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6924. get: function () {
  6925. return Engine._TEXTUREFORMAT_ALPHA;
  6926. },
  6927. enumerable: true,
  6928. configurable: true
  6929. });
  6930. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6931. get: function () {
  6932. return Engine._TEXTUREFORMAT_LUMINANCE;
  6933. },
  6934. enumerable: true,
  6935. configurable: true
  6936. });
  6937. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6938. get: function () {
  6939. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6940. },
  6941. enumerable: true,
  6942. configurable: true
  6943. });
  6944. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6945. get: function () {
  6946. return Engine._TEXTUREFORMAT_RGB;
  6947. },
  6948. enumerable: true,
  6949. configurable: true
  6950. });
  6951. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6952. get: function () {
  6953. return Engine._TEXTUREFORMAT_RGBA;
  6954. },
  6955. enumerable: true,
  6956. configurable: true
  6957. });
  6958. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6959. get: function () {
  6960. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6961. },
  6962. enumerable: true,
  6963. configurable: true
  6964. });
  6965. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6966. get: function () {
  6967. return Engine._TEXTURETYPE_FLOAT;
  6968. },
  6969. enumerable: true,
  6970. configurable: true
  6971. });
  6972. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6973. get: function () {
  6974. return Engine._TEXTURETYPE_HALF_FLOAT;
  6975. },
  6976. enumerable: true,
  6977. configurable: true
  6978. });
  6979. Object.defineProperty(Engine, "Version", {
  6980. get: function () {
  6981. return "2.6-alpha";
  6982. },
  6983. enumerable: true,
  6984. configurable: true
  6985. });
  6986. Object.defineProperty(Engine.prototype, "texturesSupported", {
  6987. get: function () {
  6988. return this._texturesSupported;
  6989. },
  6990. enumerable: true,
  6991. configurable: true
  6992. });
  6993. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  6994. get: function () {
  6995. return this._textureFormatInUse;
  6996. },
  6997. enumerable: true,
  6998. configurable: true
  6999. });
  7000. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7001. get: function () {
  7002. return this._webGLVersion;
  7003. },
  7004. enumerable: true,
  7005. configurable: true
  7006. });
  7007. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7008. /**
  7009. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7010. */
  7011. get: function () {
  7012. return this._isStencilEnable;
  7013. },
  7014. enumerable: true,
  7015. configurable: true
  7016. });
  7017. Engine.prototype._prepareWorkingCanvas = function () {
  7018. if (this._workingCanvas) {
  7019. return;
  7020. }
  7021. this._workingCanvas = document.createElement("canvas");
  7022. this._workingContext = this._workingCanvas.getContext("2d");
  7023. };
  7024. Engine.prototype.resetTextureCache = function () {
  7025. for (var index = 0; index < this._maxTextureChannels; index++) {
  7026. this._activeTexturesCache[index] = null;
  7027. }
  7028. };
  7029. Engine.prototype.getGlInfo = function () {
  7030. return {
  7031. vendor: this._glVendor,
  7032. renderer: this._glRenderer,
  7033. version: this._glVersion
  7034. };
  7035. };
  7036. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7037. if (useScreen === void 0) { useScreen = false; }
  7038. var viewport = camera.viewport;
  7039. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7040. };
  7041. Engine.prototype.getRenderWidth = function (useScreen) {
  7042. if (useScreen === void 0) { useScreen = false; }
  7043. if (!useScreen && this._currentRenderTarget) {
  7044. return this._currentRenderTarget._width;
  7045. }
  7046. return this._renderingCanvas.width;
  7047. };
  7048. Engine.prototype.getRenderHeight = function (useScreen) {
  7049. if (useScreen === void 0) { useScreen = false; }
  7050. if (!useScreen && this._currentRenderTarget) {
  7051. return this._currentRenderTarget._height;
  7052. }
  7053. return this._renderingCanvas.height;
  7054. };
  7055. Engine.prototype.getRenderingCanvas = function () {
  7056. return this._renderingCanvas;
  7057. };
  7058. Engine.prototype.getRenderingCanvasClientRect = function () {
  7059. return this._renderingCanvas.getBoundingClientRect();
  7060. };
  7061. Engine.prototype.setHardwareScalingLevel = function (level) {
  7062. this._hardwareScalingLevel = level;
  7063. this.resize();
  7064. };
  7065. Engine.prototype.getHardwareScalingLevel = function () {
  7066. return this._hardwareScalingLevel;
  7067. };
  7068. Engine.prototype.getLoadedTexturesCache = function () {
  7069. return this._loadedTexturesCache;
  7070. };
  7071. Engine.prototype.getCaps = function () {
  7072. return this._caps;
  7073. };
  7074. Object.defineProperty(Engine.prototype, "drawCalls", {
  7075. get: function () {
  7076. return this._drawCalls.current;
  7077. },
  7078. enumerable: true,
  7079. configurable: true
  7080. });
  7081. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7082. get: function () {
  7083. return this._drawCalls;
  7084. },
  7085. enumerable: true,
  7086. configurable: true
  7087. });
  7088. Engine.prototype.getDepthFunction = function () {
  7089. return this._depthCullingState.depthFunc;
  7090. };
  7091. Engine.prototype.setDepthFunction = function (depthFunc) {
  7092. this._depthCullingState.depthFunc = depthFunc;
  7093. };
  7094. Engine.prototype.setDepthFunctionToGreater = function () {
  7095. this._depthCullingState.depthFunc = this._gl.GREATER;
  7096. };
  7097. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7098. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7099. };
  7100. Engine.prototype.setDepthFunctionToLess = function () {
  7101. this._depthCullingState.depthFunc = this._gl.LESS;
  7102. };
  7103. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7104. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7105. };
  7106. Engine.prototype.getStencilBuffer = function () {
  7107. return this._stencilState.stencilTest;
  7108. };
  7109. Engine.prototype.setStencilBuffer = function (enable) {
  7110. this._stencilState.stencilTest = enable;
  7111. };
  7112. Engine.prototype.getStencilMask = function () {
  7113. return this._stencilState.stencilMask;
  7114. };
  7115. Engine.prototype.setStencilMask = function (mask) {
  7116. this._stencilState.stencilMask = mask;
  7117. };
  7118. Engine.prototype.getStencilFunction = function () {
  7119. return this._stencilState.stencilFunc;
  7120. };
  7121. Engine.prototype.getStencilFunctionReference = function () {
  7122. return this._stencilState.stencilFuncRef;
  7123. };
  7124. Engine.prototype.getStencilFunctionMask = function () {
  7125. return this._stencilState.stencilFuncMask;
  7126. };
  7127. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7128. this._stencilState.stencilFunc = stencilFunc;
  7129. };
  7130. Engine.prototype.setStencilFunctionReference = function (reference) {
  7131. this._stencilState.stencilFuncRef = reference;
  7132. };
  7133. Engine.prototype.setStencilFunctionMask = function (mask) {
  7134. this._stencilState.stencilFuncMask = mask;
  7135. };
  7136. Engine.prototype.getStencilOperationFail = function () {
  7137. return this._stencilState.stencilOpStencilFail;
  7138. };
  7139. Engine.prototype.getStencilOperationDepthFail = function () {
  7140. return this._stencilState.stencilOpDepthFail;
  7141. };
  7142. Engine.prototype.getStencilOperationPass = function () {
  7143. return this._stencilState.stencilOpStencilDepthPass;
  7144. };
  7145. Engine.prototype.setStencilOperationFail = function (operation) {
  7146. this._stencilState.stencilOpStencilFail = operation;
  7147. };
  7148. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7149. this._stencilState.stencilOpDepthFail = operation;
  7150. };
  7151. Engine.prototype.setStencilOperationPass = function (operation) {
  7152. this._stencilState.stencilOpStencilDepthPass = operation;
  7153. };
  7154. /**
  7155. * stop executing a render loop function and remove it from the execution array
  7156. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7157. */
  7158. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7159. if (!renderFunction) {
  7160. this._activeRenderLoops = [];
  7161. return;
  7162. }
  7163. var index = this._activeRenderLoops.indexOf(renderFunction);
  7164. if (index >= 0) {
  7165. this._activeRenderLoops.splice(index, 1);
  7166. }
  7167. };
  7168. Engine.prototype._renderLoop = function () {
  7169. var shouldRender = true;
  7170. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7171. shouldRender = false;
  7172. }
  7173. if (shouldRender) {
  7174. // Start new frame
  7175. this.beginFrame();
  7176. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7177. var renderFunction = this._activeRenderLoops[index];
  7178. renderFunction();
  7179. }
  7180. // Present
  7181. this.endFrame();
  7182. }
  7183. if (this._activeRenderLoops.length > 0) {
  7184. // Register new frame
  7185. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7186. }
  7187. else {
  7188. this._renderingQueueLaunched = false;
  7189. }
  7190. };
  7191. /**
  7192. * Register and execute a render loop. The engine can have more than one render function.
  7193. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7194. * @example
  7195. * engine.runRenderLoop(function () {
  7196. * scene.render()
  7197. * })
  7198. */
  7199. Engine.prototype.runRenderLoop = function (renderFunction) {
  7200. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7201. return;
  7202. }
  7203. this._activeRenderLoops.push(renderFunction);
  7204. if (!this._renderingQueueLaunched) {
  7205. this._renderingQueueLaunched = true;
  7206. this._bindedRenderFunction = this._renderLoop.bind(this);
  7207. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7208. }
  7209. };
  7210. /**
  7211. * Toggle full screen mode.
  7212. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7213. * @param {any} options - an options object to be sent to the requestFullscreen function
  7214. */
  7215. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7216. if (this.isFullscreen) {
  7217. BABYLON.Tools.ExitFullscreen();
  7218. }
  7219. else {
  7220. this._pointerLockRequested = requestPointerLock;
  7221. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7222. }
  7223. };
  7224. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7225. if (stencil === void 0) { stencil = false; }
  7226. this.applyStates();
  7227. var mode = 0;
  7228. if (backBuffer) {
  7229. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7230. mode |= this._gl.COLOR_BUFFER_BIT;
  7231. }
  7232. if (depth) {
  7233. this._gl.clearDepth(1.0);
  7234. mode |= this._gl.DEPTH_BUFFER_BIT;
  7235. }
  7236. if (stencil) {
  7237. this._gl.clearStencil(0);
  7238. mode |= this._gl.STENCIL_BUFFER_BIT;
  7239. }
  7240. this._gl.clear(mode);
  7241. };
  7242. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7243. var gl = this._gl;
  7244. // Save state
  7245. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7246. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7247. // Change state
  7248. gl.enable(gl.SCISSOR_TEST);
  7249. gl.scissor(x, y, width, height);
  7250. // Clear
  7251. this.clear(clearColor, true, true, true);
  7252. // Restore state
  7253. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7254. if (curScissor === true) {
  7255. gl.enable(gl.SCISSOR_TEST);
  7256. }
  7257. else {
  7258. gl.disable(gl.SCISSOR_TEST);
  7259. }
  7260. };
  7261. /**
  7262. * Set the WebGL's viewport
  7263. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7264. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7265. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7266. */
  7267. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7268. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7269. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7270. var x = viewport.x || 0;
  7271. var y = viewport.y || 0;
  7272. this._cachedViewport = viewport;
  7273. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7274. };
  7275. /**
  7276. * Directly set the WebGL Viewport
  7277. * The x, y, width & height are directly passed to the WebGL call
  7278. * @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.
  7279. */
  7280. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7281. var currentViewport = this._cachedViewport;
  7282. this._cachedViewport = null;
  7283. this._gl.viewport(x, y, width, height);
  7284. return currentViewport;
  7285. };
  7286. Engine.prototype.beginFrame = function () {
  7287. this._measureFps();
  7288. };
  7289. Engine.prototype.endFrame = function () {
  7290. //force a flush in case we are using a bad OS.
  7291. if (this._badOS) {
  7292. this.flushFramebuffer();
  7293. }
  7294. //submit frame to the vr device, if enabled
  7295. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7296. this._vrDisplayEnabled.submitFrame();
  7297. }
  7298. };
  7299. /**
  7300. * resize the view according to the canvas' size.
  7301. * @example
  7302. * window.addEventListener("resize", function () {
  7303. * engine.resize();
  7304. * });
  7305. */
  7306. Engine.prototype.resize = function () {
  7307. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7308. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7309. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7310. };
  7311. /**
  7312. * force a specific size of the canvas
  7313. * @param {number} width - the new canvas' width
  7314. * @param {number} height - the new canvas' height
  7315. */
  7316. Engine.prototype.setSize = function (width, height) {
  7317. this._renderingCanvas.width = width;
  7318. this._renderingCanvas.height = height;
  7319. for (var index = 0; index < this.scenes.length; index++) {
  7320. var scene = this.scenes[index];
  7321. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7322. var cam = scene.cameras[camIndex];
  7323. cam._currentRenderId = 0;
  7324. }
  7325. }
  7326. };
  7327. //WebVR functions
  7328. Engine.prototype.initWebVR = function () {
  7329. if (!this.vrDisplaysPromise) {
  7330. this._getVRDisplays();
  7331. }
  7332. };
  7333. Engine.prototype.enableVR = function (vrDevice) {
  7334. this._vrDisplayEnabled = vrDevice;
  7335. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7336. };
  7337. Engine.prototype.disableVR = function () {
  7338. if (this._vrDisplayEnabled) {
  7339. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7340. }
  7341. };
  7342. Engine.prototype._getVRDisplays = function () {
  7343. var _this = this;
  7344. var getWebVRDevices = function (devices) {
  7345. var size = devices.length;
  7346. var i = 0;
  7347. _this._vrDisplays = devices.filter(function (device) {
  7348. return devices[i] instanceof VRDisplay;
  7349. });
  7350. return _this._vrDisplays;
  7351. };
  7352. //using a key due to typescript
  7353. if (navigator.getVRDisplays) {
  7354. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7355. }
  7356. };
  7357. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7358. this._currentRenderTarget = texture;
  7359. this.bindUnboundFramebuffer(texture._framebuffer);
  7360. var gl = this._gl;
  7361. if (texture.isCube) {
  7362. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7363. }
  7364. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7365. this.wipeCaches();
  7366. };
  7367. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7368. if (this._currentFramebuffer !== framebuffer) {
  7369. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7370. this._currentFramebuffer = framebuffer;
  7371. }
  7372. };
  7373. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7374. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7375. this._currentRenderTarget = null;
  7376. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7377. var gl = this._gl;
  7378. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7379. gl.generateMipmap(gl.TEXTURE_2D);
  7380. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7381. }
  7382. this.bindUnboundFramebuffer(null);
  7383. };
  7384. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7385. if (texture.generateMipMaps) {
  7386. var gl = this._gl;
  7387. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7388. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7389. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7390. }
  7391. };
  7392. Engine.prototype.flushFramebuffer = function () {
  7393. this._gl.flush();
  7394. };
  7395. Engine.prototype.restoreDefaultFramebuffer = function () {
  7396. this._currentRenderTarget = null;
  7397. this.bindUnboundFramebuffer(null);
  7398. this.setViewport(this._cachedViewport);
  7399. this.wipeCaches();
  7400. };
  7401. // VBOs
  7402. Engine.prototype._resetVertexBufferBinding = function () {
  7403. this.bindArrayBuffer(null);
  7404. this._cachedVertexBuffers = null;
  7405. };
  7406. Engine.prototype.createVertexBuffer = function (vertices) {
  7407. var vbo = this._gl.createBuffer();
  7408. this.bindArrayBuffer(vbo);
  7409. if (vertices instanceof Float32Array) {
  7410. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7411. }
  7412. else {
  7413. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7414. }
  7415. this._resetVertexBufferBinding();
  7416. vbo.references = 1;
  7417. return vbo;
  7418. };
  7419. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7420. var vbo = this._gl.createBuffer();
  7421. this.bindArrayBuffer(vbo);
  7422. if (vertices instanceof Float32Array) {
  7423. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7424. }
  7425. else {
  7426. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7427. }
  7428. this._resetVertexBufferBinding();
  7429. vbo.references = 1;
  7430. return vbo;
  7431. };
  7432. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7433. this.bindArrayBuffer(vertexBuffer);
  7434. if (offset === undefined) {
  7435. offset = 0;
  7436. }
  7437. if (count === undefined) {
  7438. if (vertices instanceof Float32Array) {
  7439. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7440. }
  7441. else {
  7442. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7443. }
  7444. }
  7445. else {
  7446. if (vertices instanceof Float32Array) {
  7447. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7448. }
  7449. else {
  7450. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7451. }
  7452. }
  7453. this._resetVertexBufferBinding();
  7454. };
  7455. Engine.prototype._resetIndexBufferBinding = function () {
  7456. this.bindIndexBuffer(null);
  7457. this._cachedIndexBuffer = null;
  7458. };
  7459. Engine.prototype.createIndexBuffer = function (indices) {
  7460. var vbo = this._gl.createBuffer();
  7461. this.bindIndexBuffer(vbo);
  7462. // Check for 32 bits indices
  7463. var arrayBuffer;
  7464. var need32Bits = false;
  7465. if (this._caps.uintIndices) {
  7466. for (var index = 0; index < indices.length; index++) {
  7467. if (indices[index] > 65535) {
  7468. need32Bits = true;
  7469. break;
  7470. }
  7471. }
  7472. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7473. }
  7474. else {
  7475. arrayBuffer = new Uint16Array(indices);
  7476. }
  7477. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7478. this._resetIndexBufferBinding();
  7479. vbo.references = 1;
  7480. vbo.is32Bits = need32Bits;
  7481. return vbo;
  7482. };
  7483. Engine.prototype.bindArrayBuffer = function (buffer) {
  7484. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7485. };
  7486. Engine.prototype.bindIndexBuffer = function (buffer) {
  7487. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7488. };
  7489. Engine.prototype.bindBuffer = function (buffer, target) {
  7490. if (this._currentBoundBuffer[target] !== buffer) {
  7491. this._gl.bindBuffer(target, buffer);
  7492. this._currentBoundBuffer[target] = buffer;
  7493. }
  7494. };
  7495. Engine.prototype.updateArrayBuffer = function (data) {
  7496. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7497. };
  7498. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7499. var pointer = this._currentBufferPointers[indx];
  7500. var changed = false;
  7501. if (!pointer) {
  7502. changed = true;
  7503. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7504. }
  7505. else {
  7506. if (pointer.buffer !== buffer) {
  7507. pointer.buffer = buffer;
  7508. changed = true;
  7509. }
  7510. if (pointer.size !== size) {
  7511. pointer.size = size;
  7512. changed = true;
  7513. }
  7514. if (pointer.type !== type) {
  7515. pointer.type = type;
  7516. changed = true;
  7517. }
  7518. if (pointer.normalized !== normalized) {
  7519. pointer.normalized = normalized;
  7520. changed = true;
  7521. }
  7522. if (pointer.stride !== stride) {
  7523. pointer.stride = stride;
  7524. changed = true;
  7525. }
  7526. if (pointer.offset !== offset) {
  7527. pointer.offset = offset;
  7528. changed = true;
  7529. }
  7530. }
  7531. if (changed) {
  7532. this.bindArrayBuffer(buffer);
  7533. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7534. }
  7535. };
  7536. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7537. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7538. this._cachedVertexBuffers = vertexBuffer;
  7539. this._cachedEffectForVertexBuffers = effect;
  7540. var attributesCount = effect.getAttributesCount();
  7541. var offset = 0;
  7542. for (var index = 0; index < attributesCount; index++) {
  7543. if (index < vertexDeclaration.length) {
  7544. var order = effect.getAttributeLocation(index);
  7545. if (order >= 0) {
  7546. if (!this._vertexAttribArraysEnabled[order]) {
  7547. this._gl.enableVertexAttribArray(order);
  7548. this._vertexAttribArraysEnabled[order] = true;
  7549. }
  7550. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7551. }
  7552. offset += vertexDeclaration[index] * 4;
  7553. }
  7554. else {
  7555. //disable effect attributes that have no data
  7556. var order = effect.getAttributeLocation(index);
  7557. if (this._vertexAttribArraysEnabled[order]) {
  7558. this._gl.disableVertexAttribArray(order);
  7559. this._vertexAttribArraysEnabled[order] = false;
  7560. }
  7561. }
  7562. }
  7563. }
  7564. if (this._cachedIndexBuffer !== indexBuffer) {
  7565. this._cachedIndexBuffer = indexBuffer;
  7566. this.bindIndexBuffer(indexBuffer);
  7567. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7568. }
  7569. };
  7570. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7571. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7572. this._cachedVertexBuffers = vertexBuffers;
  7573. this._cachedEffectForVertexBuffers = effect;
  7574. var attributes = effect.getAttributesNames();
  7575. for (var index = 0; index < attributes.length; index++) {
  7576. var order = effect.getAttributeLocation(index);
  7577. if (order >= 0) {
  7578. var vertexBuffer = vertexBuffers[attributes[index]];
  7579. if (!vertexBuffer) {
  7580. if (this._vertexAttribArraysEnabled[order]) {
  7581. this._gl.disableVertexAttribArray(order);
  7582. this._vertexAttribArraysEnabled[order] = false;
  7583. }
  7584. continue;
  7585. }
  7586. if (!this._vertexAttribArraysEnabled[order]) {
  7587. this._gl.enableVertexAttribArray(order);
  7588. this._vertexAttribArraysEnabled[order] = true;
  7589. }
  7590. var buffer = vertexBuffer.getBuffer();
  7591. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7592. if (vertexBuffer.getIsInstanced()) {
  7593. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7594. this._currentInstanceLocations.push(order);
  7595. this._currentInstanceBuffers.push(buffer);
  7596. }
  7597. }
  7598. }
  7599. }
  7600. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7601. this._cachedIndexBuffer = indexBuffer;
  7602. this.bindIndexBuffer(indexBuffer);
  7603. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7604. }
  7605. };
  7606. Engine.prototype.unbindInstanceAttributes = function () {
  7607. var boundBuffer;
  7608. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7609. var instancesBuffer = this._currentInstanceBuffers[i];
  7610. if (boundBuffer != instancesBuffer) {
  7611. boundBuffer = instancesBuffer;
  7612. this.bindArrayBuffer(instancesBuffer);
  7613. }
  7614. var offsetLocation = this._currentInstanceLocations[i];
  7615. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7616. }
  7617. this._currentInstanceBuffers.length = 0;
  7618. this._currentInstanceLocations.length = 0;
  7619. };
  7620. Engine.prototype._releaseBuffer = function (buffer) {
  7621. buffer.references--;
  7622. if (buffer.references === 0) {
  7623. this._gl.deleteBuffer(buffer);
  7624. return true;
  7625. }
  7626. return false;
  7627. };
  7628. Engine.prototype.createInstancesBuffer = function (capacity) {
  7629. var buffer = this._gl.createBuffer();
  7630. buffer.capacity = capacity;
  7631. this.bindArrayBuffer(buffer);
  7632. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7633. return buffer;
  7634. };
  7635. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7636. this._gl.deleteBuffer(buffer);
  7637. };
  7638. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7639. this.bindArrayBuffer(instancesBuffer);
  7640. if (data) {
  7641. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7642. }
  7643. if (offsetLocations[0].index !== undefined) {
  7644. var stride = 0;
  7645. for (var i = 0; i < offsetLocations.length; i++) {
  7646. var ai = offsetLocations[i];
  7647. stride += ai.attributeSize * 4;
  7648. }
  7649. for (var i = 0; i < offsetLocations.length; i++) {
  7650. var ai = offsetLocations[i];
  7651. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7652. this._gl.enableVertexAttribArray(ai.index);
  7653. this._vertexAttribArraysEnabled[ai.index] = true;
  7654. }
  7655. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7656. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7657. this._currentInstanceLocations.push(ai.index);
  7658. this._currentInstanceBuffers.push(instancesBuffer);
  7659. }
  7660. }
  7661. else {
  7662. for (var index = 0; index < 4; index++) {
  7663. var offsetLocation = offsetLocations[index];
  7664. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7665. this._gl.enableVertexAttribArray(offsetLocation);
  7666. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7667. }
  7668. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7669. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7670. this._currentInstanceLocations.push(offsetLocation);
  7671. this._currentInstanceBuffers.push(instancesBuffer);
  7672. }
  7673. }
  7674. };
  7675. Engine.prototype.applyStates = function () {
  7676. this._depthCullingState.apply(this._gl);
  7677. this._stencilState.apply(this._gl);
  7678. this._alphaState.apply(this._gl);
  7679. };
  7680. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7681. // Apply states
  7682. this.applyStates();
  7683. this._drawCalls.addCount(1, false);
  7684. // Render
  7685. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7686. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7687. if (instancesCount) {
  7688. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7689. return;
  7690. }
  7691. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7692. };
  7693. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7694. // Apply states
  7695. this.applyStates();
  7696. this._drawCalls.addCount(1, false);
  7697. if (instancesCount) {
  7698. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7699. return;
  7700. }
  7701. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7702. };
  7703. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7704. // Apply states
  7705. this.applyStates();
  7706. this._drawCalls.addCount(1, false);
  7707. if (instancesCount) {
  7708. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7709. return;
  7710. }
  7711. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7712. };
  7713. // Shaders
  7714. Engine.prototype._releaseEffect = function (effect) {
  7715. if (this._compiledEffects[effect._key]) {
  7716. delete this._compiledEffects[effect._key];
  7717. if (effect.getProgram()) {
  7718. this._gl.deleteProgram(effect.getProgram());
  7719. }
  7720. }
  7721. };
  7722. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7723. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7724. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7725. var name = vertex + "+" + fragment + "@" + defines;
  7726. if (this._compiledEffects[name]) {
  7727. return this._compiledEffects[name];
  7728. }
  7729. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7730. effect._key = name;
  7731. this._compiledEffects[name] = effect;
  7732. return effect;
  7733. };
  7734. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7735. if (uniformsNames === void 0) { uniformsNames = []; }
  7736. if (samplers === void 0) { samplers = []; }
  7737. if (defines === void 0) { defines = ""; }
  7738. return this.createEffect({
  7739. vertex: "particles",
  7740. fragmentElement: fragmentName
  7741. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7742. };
  7743. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7744. context = context || this._gl;
  7745. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7746. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7747. var shaderProgram = context.createProgram();
  7748. context.attachShader(shaderProgram, vertexShader);
  7749. context.attachShader(shaderProgram, fragmentShader);
  7750. context.linkProgram(shaderProgram);
  7751. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7752. if (!linked) {
  7753. var error = context.getProgramInfoLog(shaderProgram);
  7754. if (error) {
  7755. throw new Error(error);
  7756. }
  7757. }
  7758. context.deleteShader(vertexShader);
  7759. context.deleteShader(fragmentShader);
  7760. return shaderProgram;
  7761. };
  7762. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7763. var results = [];
  7764. for (var index = 0; index < uniformsNames.length; index++) {
  7765. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7766. }
  7767. return results;
  7768. };
  7769. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7770. var results = [];
  7771. for (var index = 0; index < attributesNames.length; index++) {
  7772. try {
  7773. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7774. }
  7775. catch (e) {
  7776. results.push(-1);
  7777. }
  7778. }
  7779. return results;
  7780. };
  7781. Engine.prototype.enableEffect = function (effect) {
  7782. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7783. // if (effect && effect.onBind) {
  7784. // effect.onBind(effect);
  7785. // }
  7786. // return;
  7787. //}
  7788. // Use program
  7789. this.setProgram(effect.getProgram());
  7790. this._currentEffect = effect;
  7791. if (effect.onBind) {
  7792. effect.onBind(effect);
  7793. }
  7794. };
  7795. Engine.prototype.setIntArray = function (uniform, array) {
  7796. if (!uniform)
  7797. return;
  7798. this._gl.uniform1iv(uniform, array);
  7799. };
  7800. Engine.prototype.setIntArray2 = function (uniform, array) {
  7801. if (!uniform || array.length % 2 !== 0)
  7802. return;
  7803. this._gl.uniform2iv(uniform, array);
  7804. };
  7805. Engine.prototype.setIntArray3 = function (uniform, array) {
  7806. if (!uniform || array.length % 3 !== 0)
  7807. return;
  7808. this._gl.uniform3iv(uniform, array);
  7809. };
  7810. Engine.prototype.setIntArray4 = function (uniform, array) {
  7811. if (!uniform || array.length % 4 !== 0)
  7812. return;
  7813. this._gl.uniform4iv(uniform, array);
  7814. };
  7815. Engine.prototype.setFloatArray = function (uniform, array) {
  7816. if (!uniform)
  7817. return;
  7818. this._gl.uniform1fv(uniform, array);
  7819. };
  7820. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7821. if (!uniform || array.length % 2 !== 0)
  7822. return;
  7823. this._gl.uniform2fv(uniform, array);
  7824. };
  7825. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7826. if (!uniform || array.length % 3 !== 0)
  7827. return;
  7828. this._gl.uniform3fv(uniform, array);
  7829. };
  7830. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7831. if (!uniform || array.length % 4 !== 0)
  7832. return;
  7833. this._gl.uniform4fv(uniform, array);
  7834. };
  7835. Engine.prototype.setArray = function (uniform, array) {
  7836. if (!uniform)
  7837. return;
  7838. this._gl.uniform1fv(uniform, array);
  7839. };
  7840. Engine.prototype.setArray2 = function (uniform, array) {
  7841. if (!uniform || array.length % 2 !== 0)
  7842. return;
  7843. this._gl.uniform2fv(uniform, array);
  7844. };
  7845. Engine.prototype.setArray3 = function (uniform, array) {
  7846. if (!uniform || array.length % 3 !== 0)
  7847. return;
  7848. this._gl.uniform3fv(uniform, array);
  7849. };
  7850. Engine.prototype.setArray4 = function (uniform, array) {
  7851. if (!uniform || array.length % 4 !== 0)
  7852. return;
  7853. this._gl.uniform4fv(uniform, array);
  7854. };
  7855. Engine.prototype.setMatrices = function (uniform, matrices) {
  7856. if (!uniform)
  7857. return;
  7858. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7859. };
  7860. Engine.prototype.setMatrix = function (uniform, matrix) {
  7861. if (!uniform)
  7862. return;
  7863. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7864. };
  7865. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7866. if (!uniform)
  7867. return;
  7868. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7869. };
  7870. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7871. if (!uniform)
  7872. return;
  7873. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7874. };
  7875. Engine.prototype.setFloat = function (uniform, value) {
  7876. if (!uniform)
  7877. return;
  7878. this._gl.uniform1f(uniform, value);
  7879. };
  7880. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7881. if (!uniform)
  7882. return;
  7883. this._gl.uniform2f(uniform, x, y);
  7884. };
  7885. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7886. if (!uniform)
  7887. return;
  7888. this._gl.uniform3f(uniform, x, y, z);
  7889. };
  7890. Engine.prototype.setBool = function (uniform, bool) {
  7891. if (!uniform)
  7892. return;
  7893. this._gl.uniform1i(uniform, bool);
  7894. };
  7895. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7896. if (!uniform)
  7897. return;
  7898. this._gl.uniform4f(uniform, x, y, z, w);
  7899. };
  7900. Engine.prototype.setColor3 = function (uniform, color3) {
  7901. if (!uniform)
  7902. return;
  7903. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7904. };
  7905. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7906. if (!uniform)
  7907. return;
  7908. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7909. };
  7910. // States
  7911. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7912. if (zOffset === void 0) { zOffset = 0; }
  7913. if (reverseSide === void 0) { reverseSide = false; }
  7914. // Culling
  7915. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7916. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7917. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7918. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7919. if (culling) {
  7920. this._depthCullingState.cullFace = cullFace;
  7921. this._depthCullingState.cull = true;
  7922. }
  7923. else {
  7924. this._depthCullingState.cull = false;
  7925. }
  7926. }
  7927. // Z offset
  7928. this._depthCullingState.zOffset = zOffset;
  7929. };
  7930. Engine.prototype.setDepthBuffer = function (enable) {
  7931. this._depthCullingState.depthTest = enable;
  7932. };
  7933. Engine.prototype.getDepthWrite = function () {
  7934. return this._depthCullingState.depthMask;
  7935. };
  7936. Engine.prototype.setDepthWrite = function (enable) {
  7937. this._depthCullingState.depthMask = enable;
  7938. };
  7939. Engine.prototype.setColorWrite = function (enable) {
  7940. this._gl.colorMask(enable, enable, enable, enable);
  7941. };
  7942. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7943. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7944. if (this._alphaMode === mode) {
  7945. return;
  7946. }
  7947. switch (mode) {
  7948. case Engine.ALPHA_DISABLE:
  7949. this._alphaState.alphaBlend = false;
  7950. break;
  7951. case Engine.ALPHA_COMBINE:
  7952. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7953. this._alphaState.alphaBlend = true;
  7954. break;
  7955. case Engine.ALPHA_ONEONE:
  7956. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7957. this._alphaState.alphaBlend = true;
  7958. break;
  7959. case Engine.ALPHA_ADD:
  7960. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7961. this._alphaState.alphaBlend = true;
  7962. break;
  7963. case Engine.ALPHA_SUBTRACT:
  7964. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7965. this._alphaState.alphaBlend = true;
  7966. break;
  7967. case Engine.ALPHA_MULTIPLY:
  7968. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7969. this._alphaState.alphaBlend = true;
  7970. break;
  7971. case Engine.ALPHA_MAXIMIZED:
  7972. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7973. this._alphaState.alphaBlend = true;
  7974. break;
  7975. }
  7976. if (!noDepthWriteChange) {
  7977. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7978. }
  7979. this._alphaMode = mode;
  7980. };
  7981. Engine.prototype.getAlphaMode = function () {
  7982. return this._alphaMode;
  7983. };
  7984. Engine.prototype.setAlphaTesting = function (enable) {
  7985. this._alphaTest = enable;
  7986. };
  7987. Engine.prototype.getAlphaTesting = function () {
  7988. return this._alphaTest;
  7989. };
  7990. // Textures
  7991. Engine.prototype.wipeCaches = function () {
  7992. this.resetTextureCache();
  7993. this._currentEffect = null;
  7994. this._stencilState.reset();
  7995. this._depthCullingState.reset();
  7996. this.setDepthFunctionToLessOrEqual();
  7997. this._alphaState.reset();
  7998. this._cachedVertexBuffers = null;
  7999. this._cachedIndexBuffer = null;
  8000. this._cachedEffectForVertexBuffers = null;
  8001. };
  8002. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  8003. var gl = this._gl;
  8004. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8005. var magFilter = gl.NEAREST;
  8006. var minFilter = gl.NEAREST;
  8007. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  8008. magFilter = gl.LINEAR;
  8009. minFilter = gl.LINEAR;
  8010. }
  8011. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  8012. magFilter = gl.LINEAR;
  8013. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8014. }
  8015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  8016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  8017. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8018. texture.samplingMode = samplingMode;
  8019. };
  8020. /**
  8021. * Set the compressed texture format to use, based on the formats you have,
  8022. * the formats supported by the hardware / browser, and those currently implemented
  8023. * in BJS.
  8024. *
  8025. * Note: The result of this call is not taken into account texture is base64 or when
  8026. * using a database / manifest.
  8027. *
  8028. * @param {Array<string>} formatsAvailable - Extension names including dot. Case
  8029. * and order do not matter.
  8030. * @returns The extension selected.
  8031. */
  8032. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8033. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8034. // code to allow the formats to be added as they can be developed / hw tested
  8035. if (this._texturesSupported[i] === '.astc')
  8036. continue;
  8037. if (this._texturesSupported[i] === '.pvr')
  8038. continue;
  8039. if (this._texturesSupported[i] === '.etc1')
  8040. continue;
  8041. if (this._texturesSupported[i] === '.etc2')
  8042. continue;
  8043. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8044. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8045. return this._textureFormatInUse = this._texturesSupported[i];
  8046. }
  8047. }
  8048. }
  8049. // actively set format to nothing, to allow this to be called more than once
  8050. // and possibly fail the 2nd time
  8051. return this._textureFormatInUse = null;
  8052. };
  8053. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  8054. var _this = this;
  8055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8056. if (onLoad === void 0) { onLoad = null; }
  8057. if (onError === void 0) { onError = null; }
  8058. if (buffer === void 0) { buffer = null; }
  8059. var texture = this._gl.createTexture();
  8060. var extension;
  8061. var fromData = false;
  8062. if (url.substr(0, 5) === "data:") {
  8063. fromData = true;
  8064. }
  8065. if (!fromData) {
  8066. var lastDot = url.lastIndexOf('.');
  8067. extension = url.substring(lastDot).toLowerCase();
  8068. if (this._textureFormatInUse && !fromData && !scene.database) {
  8069. extension = this._textureFormatInUse;
  8070. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8071. }
  8072. }
  8073. else {
  8074. var oldUrl = url;
  8075. fromData = oldUrl.split(':');
  8076. url = oldUrl;
  8077. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8078. }
  8079. var isDDS = (extension === ".dds");
  8080. var isTGA = (extension === ".tga");
  8081. scene._addPendingData(texture);
  8082. texture.url = url;
  8083. texture.noMipmap = noMipmap;
  8084. texture.references = 1;
  8085. texture.samplingMode = samplingMode;
  8086. texture.onLoadedCallbacks = [onLoad];
  8087. this._loadedTexturesCache.push(texture);
  8088. var onerror = function () {
  8089. scene._removePendingData(texture);
  8090. if (onError) {
  8091. onError();
  8092. }
  8093. };
  8094. var callback;
  8095. if (isTGA) {
  8096. callback = function (arrayBuffer) {
  8097. var data = new Uint8Array(arrayBuffer);
  8098. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8099. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8100. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8101. }, samplingMode);
  8102. };
  8103. if (!(fromData instanceof Array))
  8104. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  8105. callback(arrayBuffer);
  8106. }, null, scene.database, true, onerror);
  8107. else
  8108. callback(buffer);
  8109. }
  8110. else if (isDDS) {
  8111. callback = function (data) {
  8112. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8113. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8114. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8115. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8116. }, samplingMode);
  8117. };
  8118. if (!(fromData instanceof Array))
  8119. BABYLON.Tools.LoadFile(url, function (data) {
  8120. callback(data);
  8121. }, null, scene.database, true, onerror);
  8122. else
  8123. callback(buffer);
  8124. }
  8125. else {
  8126. var onload = function (img) {
  8127. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8128. var isPot = (img.width === potWidth && img.height === potHeight);
  8129. if (!isPot) {
  8130. _this._prepareWorkingCanvas();
  8131. _this._workingCanvas.width = potWidth;
  8132. _this._workingCanvas.height = potHeight;
  8133. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8134. _this._workingContext.imageSmoothingEnabled = false;
  8135. _this._workingContext.mozImageSmoothingEnabled = false;
  8136. _this._workingContext.oImageSmoothingEnabled = false;
  8137. _this._workingContext.webkitImageSmoothingEnabled = false;
  8138. _this._workingContext.msImageSmoothingEnabled = false;
  8139. }
  8140. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8141. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8142. _this._workingContext.imageSmoothingEnabled = true;
  8143. _this._workingContext.mozImageSmoothingEnabled = true;
  8144. _this._workingContext.oImageSmoothingEnabled = true;
  8145. _this._workingContext.webkitImageSmoothingEnabled = true;
  8146. _this._workingContext.msImageSmoothingEnabled = true;
  8147. }
  8148. }
  8149. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8150. }, samplingMode);
  8151. };
  8152. if (!(fromData instanceof Array))
  8153. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8154. else
  8155. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8156. }
  8157. return texture;
  8158. };
  8159. Engine.prototype._getInternalFormat = function (format) {
  8160. var internalFormat = this._gl.RGBA;
  8161. switch (format) {
  8162. case Engine.TEXTUREFORMAT_ALPHA:
  8163. internalFormat = this._gl.ALPHA;
  8164. break;
  8165. case Engine.TEXTUREFORMAT_LUMINANCE:
  8166. internalFormat = this._gl.LUMINANCE;
  8167. break;
  8168. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8169. internalFormat = this._gl.LUMINANCE_ALPHA;
  8170. break;
  8171. case Engine.TEXTUREFORMAT_RGB:
  8172. internalFormat = this._gl.RGB;
  8173. break;
  8174. case Engine.TEXTUREFORMAT_RGBA:
  8175. internalFormat = this._gl.RGBA;
  8176. break;
  8177. }
  8178. return internalFormat;
  8179. };
  8180. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8181. if (compression === void 0) { compression = null; }
  8182. var internalFormat = this._getInternalFormat(format);
  8183. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8184. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8185. if (texture._width % 4 !== 0) {
  8186. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8187. }
  8188. if (compression) {
  8189. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8190. }
  8191. else {
  8192. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8193. }
  8194. if (texture.generateMipMaps) {
  8195. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8196. }
  8197. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8198. this.resetTextureCache();
  8199. texture.isReady = true;
  8200. };
  8201. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8202. if (compression === void 0) { compression = null; }
  8203. var texture = this._gl.createTexture();
  8204. texture._baseWidth = width;
  8205. texture._baseHeight = height;
  8206. texture._width = width;
  8207. texture._height = height;
  8208. texture.references = 1;
  8209. this.updateRawTexture(texture, data, format, invertY, compression);
  8210. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8211. // Filters
  8212. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8213. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8214. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8215. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8216. texture.samplingMode = samplingMode;
  8217. this._loadedTexturesCache.push(texture);
  8218. return texture;
  8219. };
  8220. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8221. var texture = this._gl.createTexture();
  8222. texture._baseWidth = width;
  8223. texture._baseHeight = height;
  8224. if (generateMipMaps) {
  8225. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8226. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8227. }
  8228. this.resetTextureCache();
  8229. texture._width = width;
  8230. texture._height = height;
  8231. texture.isReady = false;
  8232. texture.generateMipMaps = generateMipMaps;
  8233. texture.references = 1;
  8234. texture.samplingMode = samplingMode;
  8235. this.updateTextureSamplingMode(samplingMode, texture);
  8236. this._loadedTexturesCache.push(texture);
  8237. return texture;
  8238. };
  8239. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8240. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8241. if (texture.isCube) {
  8242. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8243. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8244. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8245. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8246. }
  8247. else {
  8248. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8249. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8250. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8251. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8252. }
  8253. };
  8254. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8255. if (premulAlpha === void 0) { premulAlpha = false; }
  8256. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8257. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8258. if (premulAlpha) {
  8259. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8260. }
  8261. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8262. if (texture.generateMipMaps) {
  8263. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8264. }
  8265. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8266. if (premulAlpha) {
  8267. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8268. }
  8269. this.resetTextureCache();
  8270. texture.isReady = true;
  8271. };
  8272. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8273. if (texture._isDisabled) {
  8274. return;
  8275. }
  8276. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8277. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8278. try {
  8279. // Testing video texture support
  8280. if (this._videoTextureSupported === undefined) {
  8281. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8282. if (this._gl.getError() !== 0) {
  8283. this._videoTextureSupported = false;
  8284. }
  8285. else {
  8286. this._videoTextureSupported = true;
  8287. }
  8288. }
  8289. // Copy video through the current working canvas if video texture is not supported
  8290. if (!this._videoTextureSupported) {
  8291. if (!texture._workingCanvas) {
  8292. texture._workingCanvas = document.createElement("canvas");
  8293. texture._workingContext = texture._workingCanvas.getContext("2d");
  8294. texture._workingCanvas.width = texture._width;
  8295. texture._workingCanvas.height = texture._height;
  8296. }
  8297. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8298. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8299. }
  8300. else {
  8301. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8302. }
  8303. if (texture.generateMipMaps) {
  8304. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8305. }
  8306. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8307. this.resetTextureCache();
  8308. texture.isReady = true;
  8309. }
  8310. catch (ex) {
  8311. // Something unexpected
  8312. // Let's disable the texture
  8313. texture._isDisabled = true;
  8314. }
  8315. };
  8316. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8317. // old version had a "generateMipMaps" arg instead of options.
  8318. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8319. // in the same way, generateDepthBuffer is defaulted to true
  8320. var generateMipMaps = false;
  8321. var generateDepthBuffer = true;
  8322. var generateStencilBuffer = false;
  8323. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8324. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8325. if (options !== undefined) {
  8326. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8327. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8328. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8329. type = options.type === undefined ? type : options.type;
  8330. if (options.samplingMode !== undefined) {
  8331. samplingMode = options.samplingMode;
  8332. }
  8333. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8334. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8335. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8336. }
  8337. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8338. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8339. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8340. }
  8341. }
  8342. var gl = this._gl;
  8343. var texture = gl.createTexture();
  8344. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8345. var width = size.width || size;
  8346. var height = size.height || size;
  8347. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8348. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8349. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8350. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8351. }
  8352. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8353. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8354. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8355. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8356. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8357. var depthStencilBuffer;
  8358. // Create the depth/stencil buffer
  8359. if (generateStencilBuffer) {
  8360. depthStencilBuffer = gl.createRenderbuffer();
  8361. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8362. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8363. }
  8364. else if (generateDepthBuffer) {
  8365. depthStencilBuffer = gl.createRenderbuffer();
  8366. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8367. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8368. }
  8369. // Create the framebuffer
  8370. var framebuffer = gl.createFramebuffer();
  8371. this.bindUnboundFramebuffer(framebuffer);
  8372. // Manage attachments
  8373. if (generateStencilBuffer) {
  8374. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8375. }
  8376. else if (generateDepthBuffer) {
  8377. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8378. }
  8379. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8380. if (generateMipMaps) {
  8381. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8382. }
  8383. // Unbind
  8384. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8385. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8386. this.bindUnboundFramebuffer(null);
  8387. texture._framebuffer = framebuffer;
  8388. if (generateDepthBuffer) {
  8389. texture._depthBuffer = depthStencilBuffer;
  8390. }
  8391. texture._baseWidth = width;
  8392. texture._baseHeight = height;
  8393. texture._width = width;
  8394. texture._height = height;
  8395. texture.isReady = true;
  8396. texture.generateMipMaps = generateMipMaps;
  8397. texture.references = 1;
  8398. texture.samplingMode = samplingMode;
  8399. texture.type = type;
  8400. this.resetTextureCache();
  8401. this._loadedTexturesCache.push(texture);
  8402. return texture;
  8403. };
  8404. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8405. var gl = this._gl;
  8406. var texture = gl.createTexture();
  8407. var generateMipMaps = true;
  8408. var generateDepthBuffer = true;
  8409. var generateStencilBuffer = false;
  8410. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8411. if (options !== undefined) {
  8412. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8413. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8414. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8415. if (options.samplingMode !== undefined) {
  8416. samplingMode = options.samplingMode;
  8417. }
  8418. }
  8419. texture.isCube = true;
  8420. texture.references = 1;
  8421. texture.generateMipMaps = generateMipMaps;
  8422. texture.references = 1;
  8423. texture.samplingMode = samplingMode;
  8424. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8425. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8426. for (var face = 0; face < 6; face++) {
  8427. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8428. }
  8429. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8430. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8431. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8432. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8433. // Create the depth buffer
  8434. var depthStencilBuffer;
  8435. // Create the depth/stencil buffer
  8436. if (generateStencilBuffer) {
  8437. depthStencilBuffer = gl.createRenderbuffer();
  8438. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8439. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8440. }
  8441. else if (generateDepthBuffer) {
  8442. depthStencilBuffer = gl.createRenderbuffer();
  8443. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8444. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8445. }
  8446. // Create the framebuffer
  8447. var framebuffer = gl.createFramebuffer();
  8448. this.bindUnboundFramebuffer(framebuffer);
  8449. // Manage attachments
  8450. if (generateStencilBuffer) {
  8451. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8452. }
  8453. else if (generateDepthBuffer) {
  8454. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8455. }
  8456. // Mipmaps
  8457. if (texture.generateMipMaps) {
  8458. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8459. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8460. }
  8461. // Unbind
  8462. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8463. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8464. this.bindUnboundFramebuffer(null);
  8465. texture._framebuffer = framebuffer;
  8466. if (generateDepthBuffer) {
  8467. texture._depthBuffer = depthStencilBuffer;
  8468. }
  8469. texture._width = size;
  8470. texture._height = size;
  8471. texture.isReady = true;
  8472. this.resetTextureCache();
  8473. this._loadedTexturesCache.push(texture);
  8474. return texture;
  8475. };
  8476. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8477. var _this = this;
  8478. if (onLoad === void 0) { onLoad = null; }
  8479. if (onError === void 0) { onError = null; }
  8480. var gl = this._gl;
  8481. var texture = gl.createTexture();
  8482. texture.isCube = true;
  8483. texture.url = rootUrl;
  8484. texture.references = 1;
  8485. texture.onLoadedCallbacks = [];
  8486. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8487. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8488. if (isDDS) {
  8489. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8490. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8491. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8492. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8493. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8494. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8495. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8496. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8497. }
  8498. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8499. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8501. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8502. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8503. _this.resetTextureCache();
  8504. texture._width = info.width;
  8505. texture._height = info.height;
  8506. texture.isReady = true;
  8507. }, null, null, true, onError);
  8508. }
  8509. else {
  8510. cascadeLoad(rootUrl, scene, function (imgs) {
  8511. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8512. var height = width;
  8513. _this._prepareWorkingCanvas();
  8514. _this._workingCanvas.width = width;
  8515. _this._workingCanvas.height = height;
  8516. var faces = [
  8517. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8518. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8519. ];
  8520. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8521. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8522. for (var index = 0; index < faces.length; index++) {
  8523. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8524. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8525. }
  8526. if (!noMipmap) {
  8527. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8528. }
  8529. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8530. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8531. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8532. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8533. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8534. _this.resetTextureCache();
  8535. texture._width = width;
  8536. texture._height = height;
  8537. texture.isReady = true;
  8538. texture.onLoadedCallbacks.forEach(function (callback) {
  8539. callback();
  8540. });
  8541. if (onLoad) {
  8542. onLoad();
  8543. }
  8544. }, files, onError);
  8545. }
  8546. this._loadedTexturesCache.push(texture);
  8547. return texture;
  8548. };
  8549. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8550. texture._width = width;
  8551. texture._height = height;
  8552. texture._size = width * height;
  8553. texture._baseWidth = width;
  8554. texture._baseHeight = height;
  8555. };
  8556. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8557. var _this = this;
  8558. var gl = this._gl;
  8559. var texture = gl.createTexture();
  8560. scene._addPendingData(texture);
  8561. texture.isCube = true;
  8562. texture.references = 1;
  8563. texture.url = url;
  8564. var internalFormat = this._getInternalFormat(format);
  8565. var textureType = gl.UNSIGNED_BYTE;
  8566. if (type === Engine.TEXTURETYPE_FLOAT) {
  8567. textureType = gl.FLOAT;
  8568. }
  8569. var width = size;
  8570. var height = width;
  8571. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8572. texture._width = width;
  8573. texture._height = height;
  8574. var onerror = function () {
  8575. scene._removePendingData(texture);
  8576. };
  8577. var internalCallback = function (data) {
  8578. var rgbeDataArrays = callback(data);
  8579. var facesIndex = [
  8580. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8581. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8582. ];
  8583. width = texture._width;
  8584. height = texture._height;
  8585. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8586. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8587. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8588. if (!noMipmap && isPot) {
  8589. if (mipmmapGenerator) {
  8590. var arrayTemp = [];
  8591. // Data are known to be in +X +Y +Z -X -Y -Z
  8592. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8593. arrayTemp.push(rgbeDataArrays[0]); // +X
  8594. arrayTemp.push(rgbeDataArrays[3]); // -X
  8595. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8596. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8597. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8598. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8599. var mipData = mipmmapGenerator(arrayTemp);
  8600. for (var level = 0; level < mipData.length; level++) {
  8601. var mipSize = width >> level;
  8602. // mipData is order in +X -X +Y -Y +Z -Z
  8603. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8604. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8605. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8606. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8607. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8608. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8609. }
  8610. }
  8611. else {
  8612. // Data are known to be in +X +Y +Z -X -Y -Z
  8613. for (var index = 0; index < facesIndex.length; index++) {
  8614. var faceData = rgbeDataArrays[index];
  8615. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8616. }
  8617. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8618. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8619. // By following the webgl standard changes from Revision 7, 2014/11/24
  8620. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8621. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8622. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8623. // Data are known to be in +X +Y +Z -X -Y -Z
  8624. for (var index = 0; index < facesIndex.length; index++) {
  8625. var faceData = rgbeDataArrays[index];
  8626. // Create a new RGBA Face.
  8627. var newFaceData = new Float32Array(width * height * 4);
  8628. for (var x = 0; x < width; x++) {
  8629. for (var y = 0; y < height; y++) {
  8630. var index_1 = (y * width + x) * 3;
  8631. var newIndex = (y * width + x) * 4;
  8632. // Map Old Value to new value.
  8633. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8634. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8635. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8636. // Add fully opaque alpha channel.
  8637. newFaceData[newIndex + 3] = 1;
  8638. }
  8639. }
  8640. // Reupload the face.
  8641. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8642. }
  8643. // Try to generate mipmap again.
  8644. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8645. }
  8646. }
  8647. }
  8648. else {
  8649. noMipmap = true;
  8650. }
  8651. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8654. }
  8655. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8656. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8657. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8658. }
  8659. else {
  8660. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8661. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8662. }
  8663. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8665. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8666. texture.isReady = true;
  8667. _this.resetTextureCache();
  8668. scene._removePendingData(texture);
  8669. };
  8670. BABYLON.Tools.LoadFile(url, function (data) {
  8671. internalCallback(data);
  8672. }, onerror, scene.database, true);
  8673. return texture;
  8674. };
  8675. ;
  8676. Engine.prototype._releaseTexture = function (texture) {
  8677. var gl = this._gl;
  8678. if (texture._framebuffer) {
  8679. gl.deleteFramebuffer(texture._framebuffer);
  8680. }
  8681. if (texture._depthBuffer) {
  8682. gl.deleteRenderbuffer(texture._depthBuffer);
  8683. }
  8684. gl.deleteTexture(texture);
  8685. // Unbind channels
  8686. this.unbindAllTextures();
  8687. var index = this._loadedTexturesCache.indexOf(texture);
  8688. if (index !== -1) {
  8689. this._loadedTexturesCache.splice(index, 1);
  8690. }
  8691. };
  8692. Engine.prototype.setProgram = function (program) {
  8693. if (this._currentProgram !== program) {
  8694. this._gl.useProgram(program);
  8695. this._currentProgram = program;
  8696. }
  8697. };
  8698. Engine.prototype.bindSamplers = function (effect) {
  8699. this.setProgram(effect.getProgram());
  8700. var samplers = effect.getSamplers();
  8701. for (var index = 0; index < samplers.length; index++) {
  8702. var uniform = effect.getUniform(samplers[index]);
  8703. this._gl.uniform1i(uniform, index);
  8704. }
  8705. this._currentEffect = null;
  8706. };
  8707. Engine.prototype.activateTexture = function (texture) {
  8708. if (this._activeTexture !== texture) {
  8709. this._gl.activeTexture(texture);
  8710. this._activeTexture = texture;
  8711. }
  8712. };
  8713. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8714. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8715. this._gl.bindTexture(target, texture);
  8716. this._activeTexturesCache[this._activeTexture] = texture;
  8717. }
  8718. };
  8719. Engine.prototype._bindTexture = function (channel, texture) {
  8720. if (channel < 0) {
  8721. return;
  8722. }
  8723. this.activateTexture(this._gl["TEXTURE" + channel]);
  8724. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8725. };
  8726. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8727. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8728. };
  8729. Engine.prototype.unbindAllTextures = function () {
  8730. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8731. this.activateTexture(this._gl["TEXTURE" + channel]);
  8732. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8733. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8734. }
  8735. };
  8736. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8737. if (channel < 0) {
  8738. return;
  8739. }
  8740. this._gl.uniform1i(uniform, channel);
  8741. this._setTexture(channel, texture);
  8742. };
  8743. Engine.prototype._setTexture = function (channel, texture) {
  8744. // Not ready?
  8745. if (!texture || !texture.isReady()) {
  8746. if (this._activeTexturesCache[channel] != null) {
  8747. this.activateTexture(this._gl["TEXTURE" + channel]);
  8748. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8749. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8750. }
  8751. return;
  8752. }
  8753. // Video
  8754. var alreadyActivated = false;
  8755. if (texture instanceof BABYLON.VideoTexture) {
  8756. this.activateTexture(this._gl["TEXTURE" + channel]);
  8757. alreadyActivated = true;
  8758. texture.update();
  8759. }
  8760. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8761. texture.delayLoad();
  8762. return;
  8763. }
  8764. var internalTexture = texture.getInternalTexture();
  8765. if (this._activeTexturesCache[channel] === internalTexture) {
  8766. return;
  8767. }
  8768. if (!alreadyActivated) {
  8769. this.activateTexture(this._gl["TEXTURE" + channel]);
  8770. }
  8771. if (internalTexture.isCube) {
  8772. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8773. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8774. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8775. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8776. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8777. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8778. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8779. }
  8780. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8781. }
  8782. else {
  8783. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8784. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8785. internalTexture._cachedWrapU = texture.wrapU;
  8786. switch (texture.wrapU) {
  8787. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8788. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8789. break;
  8790. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8791. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8792. break;
  8793. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8794. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8795. break;
  8796. }
  8797. }
  8798. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8799. internalTexture._cachedWrapV = texture.wrapV;
  8800. switch (texture.wrapV) {
  8801. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8802. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8803. break;
  8804. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8805. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8806. break;
  8807. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8808. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8809. break;
  8810. }
  8811. }
  8812. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8813. }
  8814. };
  8815. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8816. if (channel < 0) {
  8817. return;
  8818. }
  8819. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8820. this._textureUnits = new Int32Array(textures.length);
  8821. }
  8822. for (var i = 0; i < textures.length; i++) {
  8823. this._textureUnits[i] = channel + i;
  8824. }
  8825. this._gl.uniform1iv(uniform, this._textureUnits);
  8826. for (var index = 0; index < textures.length; index++) {
  8827. this._setTexture(channel + index, textures[index]);
  8828. }
  8829. };
  8830. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8831. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8832. var value = texture.anisotropicFilteringLevel;
  8833. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8834. value = 1;
  8835. }
  8836. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8837. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8838. texture._cachedAnisotropicFilteringLevel = value;
  8839. }
  8840. };
  8841. Engine.prototype.readPixels = function (x, y, width, height) {
  8842. var data = new Uint8Array(height * width * 4);
  8843. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8844. return data;
  8845. };
  8846. /**
  8847. * Add an externaly attached data from its key.
  8848. * This method call will fail and return false, if such key already exists.
  8849. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8850. * @param key the unique key that identifies the data
  8851. * @param data the data object to associate to the key for this Engine instance
  8852. * @return true if no such key were already present and the data was added successfully, false otherwise
  8853. */
  8854. Engine.prototype.addExternalData = function (key, data) {
  8855. return this._externalData.add(key, data);
  8856. };
  8857. /**
  8858. * Get an externaly attached data from its key
  8859. * @param key the unique key that identifies the data
  8860. * @return the associated data, if present (can be null), or undefined if not present
  8861. */
  8862. Engine.prototype.getExternalData = function (key) {
  8863. return this._externalData.get(key);
  8864. };
  8865. /**
  8866. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8867. * @param key the unique key that identifies the data
  8868. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8869. * @return the associated data, can be null if the factory returned null.
  8870. */
  8871. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8872. return this._externalData.getOrAddWithFactory(key, factory);
  8873. };
  8874. /**
  8875. * Remove an externaly attached data from the Engine instance
  8876. * @param key the unique key that identifies the data
  8877. * @return true if the data was successfully removed, false if it doesn't exist
  8878. */
  8879. Engine.prototype.removeExternalData = function (key) {
  8880. return this._externalData.remove(key);
  8881. };
  8882. Engine.prototype.releaseInternalTexture = function (texture) {
  8883. if (!texture) {
  8884. return;
  8885. }
  8886. texture.references--;
  8887. // Final reference ?
  8888. if (texture.references === 0) {
  8889. var texturesCache = this.getLoadedTexturesCache();
  8890. var index = texturesCache.indexOf(texture);
  8891. if (index > -1) {
  8892. texturesCache.splice(index, 1);
  8893. }
  8894. this._releaseTexture(texture);
  8895. }
  8896. };
  8897. Engine.prototype.unbindAllAttributes = function () {
  8898. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8899. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8900. continue;
  8901. }
  8902. this._gl.disableVertexAttribArray(i);
  8903. this._vertexAttribArraysEnabled[i] = false;
  8904. }
  8905. };
  8906. // Dispose
  8907. Engine.prototype.dispose = function () {
  8908. this.hideLoadingUI();
  8909. this.stopRenderLoop();
  8910. // Release scenes
  8911. while (this.scenes.length) {
  8912. this.scenes[0].dispose();
  8913. }
  8914. // Release audio engine
  8915. Engine.audioEngine.dispose();
  8916. // Release effects
  8917. for (var name in this._compiledEffects) {
  8918. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8919. }
  8920. // Unbind
  8921. this.unbindAllAttributes();
  8922. this._gl = null;
  8923. //WebVR
  8924. this.disableVR();
  8925. // Events
  8926. window.removeEventListener("blur", this._onBlur);
  8927. window.removeEventListener("focus", this._onFocus);
  8928. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8929. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8930. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8931. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8932. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8933. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8934. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8935. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8936. };
  8937. // Loading screen
  8938. Engine.prototype.displayLoadingUI = function () {
  8939. this._loadingScreen.displayLoadingUI();
  8940. };
  8941. Engine.prototype.hideLoadingUI = function () {
  8942. this._loadingScreen.hideLoadingUI();
  8943. };
  8944. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8945. get: function () {
  8946. return this._loadingScreen;
  8947. },
  8948. set: function (loadingScreen) {
  8949. this._loadingScreen = loadingScreen;
  8950. },
  8951. enumerable: true,
  8952. configurable: true
  8953. });
  8954. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8955. set: function (text) {
  8956. this._loadingScreen.loadingUIText = text;
  8957. },
  8958. enumerable: true,
  8959. configurable: true
  8960. });
  8961. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8962. set: function (color) {
  8963. this._loadingScreen.loadingUIBackgroundColor = color;
  8964. },
  8965. enumerable: true,
  8966. configurable: true
  8967. });
  8968. Engine.prototype.attachContextLostEvent = function (callback) {
  8969. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8970. };
  8971. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8972. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8973. };
  8974. Engine.prototype.getVertexShaderSource = function (program) {
  8975. var shaders = this._gl.getAttachedShaders(program);
  8976. return this._gl.getShaderSource(shaders[0]);
  8977. };
  8978. Engine.prototype.getFragmentShaderSource = function (program) {
  8979. var shaders = this._gl.getAttachedShaders(program);
  8980. return this._gl.getShaderSource(shaders[1]);
  8981. };
  8982. // FPS
  8983. Engine.prototype.getFps = function () {
  8984. return this.fps;
  8985. };
  8986. Engine.prototype.getDeltaTime = function () {
  8987. return this.deltaTime;
  8988. };
  8989. Engine.prototype._measureFps = function () {
  8990. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8991. var length = this.previousFramesDuration.length;
  8992. if (length >= 2) {
  8993. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8994. }
  8995. if (length >= this.fpsRange) {
  8996. if (length > this.fpsRange) {
  8997. this.previousFramesDuration.splice(0, 1);
  8998. length = this.previousFramesDuration.length;
  8999. }
  9000. var sum = 0;
  9001. for (var id = 0; id < length - 1; id++) {
  9002. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9003. }
  9004. this.fps = 1000.0 / (sum / (length - 1));
  9005. }
  9006. };
  9007. Engine.prototype._canRenderToFloatTexture = function () {
  9008. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  9009. };
  9010. Engine.prototype._canRenderToHalfFloatTexture = function () {
  9011. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  9012. };
  9013. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9014. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  9015. var tempcanvas = document.createElement("canvas");
  9016. tempcanvas.height = 16;
  9017. tempcanvas.width = 16;
  9018. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  9019. // extension.
  9020. var ext = gl.getExtension(extension);
  9021. if (!ext) {
  9022. return false;
  9023. }
  9024. // setup GLSL program
  9025. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  9026. 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 }";
  9027. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  9028. gl.useProgram(program);
  9029. // look up where the vertex data needs to go.
  9030. var positionLocation = gl.getAttribLocation(program, "a_position");
  9031. var colorLoc = gl.getUniformLocation(program, "u_color");
  9032. // provide texture coordinates for the rectangle.
  9033. var positionBuffer = gl.createBuffer();
  9034. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  9035. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  9036. -1.0, -1.0,
  9037. 1.0, -1.0,
  9038. -1.0, 1.0,
  9039. -1.0, 1.0,
  9040. 1.0, -1.0,
  9041. 1.0, 1.0]), gl.STATIC_DRAW);
  9042. gl.enableVertexAttribArray(positionLocation);
  9043. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  9044. var whiteTex = gl.createTexture();
  9045. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9046. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  9047. var tex = gl.createTexture();
  9048. gl.bindTexture(gl.TEXTURE_2D, tex);
  9049. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  9050. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9051. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9052. var fb = gl.createFramebuffer();
  9053. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9054. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  9055. var cleanup = function () {
  9056. gl.deleteProgram(program);
  9057. gl.disableVertexAttribArray(positionLocation);
  9058. gl.deleteBuffer(positionBuffer);
  9059. gl.deleteFramebuffer(fb);
  9060. gl.deleteTexture(whiteTex);
  9061. gl.deleteTexture(tex);
  9062. };
  9063. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9064. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  9065. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  9066. cleanup();
  9067. return false;
  9068. }
  9069. // Draw the rectangle.
  9070. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9071. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  9072. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9073. gl.bindTexture(gl.TEXTURE_2D, tex);
  9074. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9075. gl.clearColor(1, 0, 0, 1);
  9076. gl.clear(gl.COLOR_BUFFER_BIT);
  9077. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  9078. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9079. var pixel = new Uint8Array(4);
  9080. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  9081. if (pixel[0] !== 0 ||
  9082. pixel[1] < 248 ||
  9083. pixel[2] < 248 ||
  9084. pixel[3] < 254) {
  9085. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  9086. cleanup();
  9087. return false;
  9088. }
  9089. // Succesfully rendered to "format" texture.
  9090. cleanup();
  9091. return true;
  9092. };
  9093. // Statics
  9094. Engine.isSupported = function () {
  9095. try {
  9096. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9097. if (navigator.isCocoonJS) {
  9098. return true;
  9099. }
  9100. var tempcanvas = document.createElement("canvas");
  9101. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9102. return gl != null && !!window.WebGLRenderingContext;
  9103. }
  9104. catch (e) {
  9105. return false;
  9106. }
  9107. };
  9108. // Const statics
  9109. Engine._ALPHA_DISABLE = 0;
  9110. Engine._ALPHA_ADD = 1;
  9111. Engine._ALPHA_COMBINE = 2;
  9112. Engine._ALPHA_SUBTRACT = 3;
  9113. Engine._ALPHA_MULTIPLY = 4;
  9114. Engine._ALPHA_MAXIMIZED = 5;
  9115. Engine._ALPHA_ONEONE = 6;
  9116. Engine._DELAYLOADSTATE_NONE = 0;
  9117. Engine._DELAYLOADSTATE_LOADED = 1;
  9118. Engine._DELAYLOADSTATE_LOADING = 2;
  9119. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9120. Engine._TEXTUREFORMAT_ALPHA = 0;
  9121. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9122. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9123. Engine._TEXTUREFORMAT_RGB = 4;
  9124. Engine._TEXTUREFORMAT_RGBA = 5;
  9125. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9126. Engine._TEXTURETYPE_FLOAT = 1;
  9127. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9128. // Depht or Stencil test Constants.
  9129. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9130. 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.
  9131. 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.
  9132. 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.
  9133. 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.
  9134. 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.
  9135. 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.
  9136. 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.
  9137. // Stencil Actions Constants.
  9138. Engine._KEEP = 0x1E00;
  9139. Engine._REPLACE = 0x1E01;
  9140. Engine._INCR = 0x1E02;
  9141. Engine._DECR = 0x1E03;
  9142. Engine._INVERT = 0x150A;
  9143. Engine._INCR_WRAP = 0x8507;
  9144. Engine._DECR_WRAP = 0x8508;
  9145. // Updatable statics so stick with vars here
  9146. Engine.CollisionsEpsilon = 0.001;
  9147. Engine.CodeRepository = "src/";
  9148. Engine.ShadersRepository = "src/Shaders/";
  9149. return Engine;
  9150. }());
  9151. BABYLON.Engine = Engine;
  9152. })(BABYLON || (BABYLON = {}));
  9153. //# sourceMappingURL=babylon.engine.js.map
  9154. var BABYLON;
  9155. (function (BABYLON) {
  9156. /**
  9157. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9158. */
  9159. var Node = (function () {
  9160. /**
  9161. * @constructor
  9162. * @param {string} name - the name and id to be given to this node
  9163. * @param {BABYLON.Scene} the scene this node will be added to
  9164. */
  9165. function Node(name, scene) {
  9166. this.state = "";
  9167. this.metadata = null;
  9168. this.doNotSerialize = false;
  9169. this.animations = new Array();
  9170. this._ranges = {};
  9171. this._childrenFlag = -1;
  9172. this._isEnabled = true;
  9173. this._isReady = true;
  9174. this._currentRenderId = -1;
  9175. this._parentRenderId = -1;
  9176. /**
  9177. * An event triggered when the mesh is disposed.
  9178. * @type {BABYLON.Observable}
  9179. */
  9180. this.onDisposeObservable = new BABYLON.Observable();
  9181. this.name = name;
  9182. this.id = name;
  9183. this._scene = scene;
  9184. this._initCache();
  9185. }
  9186. Object.defineProperty(Node.prototype, "parent", {
  9187. get: function () {
  9188. return this._parentNode;
  9189. },
  9190. set: function (parent) {
  9191. if (this._parentNode === parent) {
  9192. return;
  9193. }
  9194. if (this._parentNode) {
  9195. var index = this._parentNode._children.indexOf(this);
  9196. if (index !== -1) {
  9197. this._parentNode._children.splice(index, 1);
  9198. }
  9199. }
  9200. this._parentNode = parent;
  9201. if (this._parentNode) {
  9202. if (!this._parentNode._children) {
  9203. this._parentNode._children = new Array();
  9204. }
  9205. this._parentNode._children.push(this);
  9206. }
  9207. },
  9208. enumerable: true,
  9209. configurable: true
  9210. });
  9211. Node.prototype.getClassName = function () {
  9212. return "Node";
  9213. };
  9214. Object.defineProperty(Node.prototype, "onDispose", {
  9215. set: function (callback) {
  9216. if (this._onDisposeObserver) {
  9217. this.onDisposeObservable.remove(this._onDisposeObserver);
  9218. }
  9219. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9220. },
  9221. enumerable: true,
  9222. configurable: true
  9223. });
  9224. Node.prototype.getScene = function () {
  9225. return this._scene;
  9226. };
  9227. Node.prototype.getEngine = function () {
  9228. return this._scene.getEngine();
  9229. };
  9230. // override it in derived class
  9231. Node.prototype.getWorldMatrix = function () {
  9232. return BABYLON.Matrix.Identity();
  9233. };
  9234. // override it in derived class if you add new variables to the cache
  9235. // and call the parent class method
  9236. Node.prototype._initCache = function () {
  9237. this._cache = {};
  9238. this._cache.parent = undefined;
  9239. };
  9240. Node.prototype.updateCache = function (force) {
  9241. if (!force && this.isSynchronized())
  9242. return;
  9243. this._cache.parent = this.parent;
  9244. this._updateCache();
  9245. };
  9246. // override it in derived class if you add new variables to the cache
  9247. // and call the parent class method if !ignoreParentClass
  9248. Node.prototype._updateCache = function (ignoreParentClass) {
  9249. };
  9250. // override it in derived class if you add new variables to the cache
  9251. Node.prototype._isSynchronized = function () {
  9252. return true;
  9253. };
  9254. Node.prototype._markSyncedWithParent = function () {
  9255. this._parentRenderId = this.parent._currentRenderId;
  9256. };
  9257. Node.prototype.isSynchronizedWithParent = function () {
  9258. if (!this.parent) {
  9259. return true;
  9260. }
  9261. if (this._parentRenderId !== this.parent._currentRenderId) {
  9262. return false;
  9263. }
  9264. return this.parent.isSynchronized();
  9265. };
  9266. Node.prototype.isSynchronized = function (updateCache) {
  9267. var check = this.hasNewParent();
  9268. check = check || !this.isSynchronizedWithParent();
  9269. check = check || !this._isSynchronized();
  9270. if (updateCache)
  9271. this.updateCache(true);
  9272. return !check;
  9273. };
  9274. Node.prototype.hasNewParent = function (update) {
  9275. if (this._cache.parent === this.parent)
  9276. return false;
  9277. if (update)
  9278. this._cache.parent = this.parent;
  9279. return true;
  9280. };
  9281. /**
  9282. * Is this node ready to be used/rendered
  9283. * @return {boolean} is it ready
  9284. */
  9285. Node.prototype.isReady = function () {
  9286. return this._isReady;
  9287. };
  9288. /**
  9289. * Is this node enabled.
  9290. * If the node has a parent and is enabled, the parent will be inspected as well.
  9291. * @return {boolean} whether this node (and its parent) is enabled.
  9292. * @see setEnabled
  9293. */
  9294. Node.prototype.isEnabled = function () {
  9295. if (!this._isEnabled) {
  9296. return false;
  9297. }
  9298. if (this.parent) {
  9299. return this.parent.isEnabled();
  9300. }
  9301. return true;
  9302. };
  9303. /**
  9304. * Set the enabled state of this node.
  9305. * @param {boolean} value - the new enabled state
  9306. * @see isEnabled
  9307. */
  9308. Node.prototype.setEnabled = function (value) {
  9309. this._isEnabled = value;
  9310. };
  9311. /**
  9312. * Is this node a descendant of the given node.
  9313. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9314. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9315. * @see parent
  9316. */
  9317. Node.prototype.isDescendantOf = function (ancestor) {
  9318. if (this.parent) {
  9319. if (this.parent === ancestor) {
  9320. return true;
  9321. }
  9322. return this.parent.isDescendantOf(ancestor);
  9323. }
  9324. return false;
  9325. };
  9326. /**
  9327. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9328. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9329. * @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.
  9330. * @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.
  9331. */
  9332. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9333. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9334. if (!this._children) {
  9335. return;
  9336. }
  9337. for (var index = 0; index < this._children.length; index++) {
  9338. var item = this._children[index];
  9339. if (!predicate || predicate(item)) {
  9340. results.push(item);
  9341. }
  9342. if (!directDescendantsOnly) {
  9343. item._getDescendants(results, false, predicate);
  9344. }
  9345. }
  9346. };
  9347. /**
  9348. * Will return all nodes that have this node as ascendant.
  9349. * @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.
  9350. * @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.
  9351. * @return {BABYLON.Node[]} all children nodes of all types.
  9352. */
  9353. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9354. var results = [];
  9355. this._getDescendants(results, directDescendantsOnly, predicate);
  9356. return results;
  9357. };
  9358. /**
  9359. * @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.
  9360. * @Deprecated, legacy support.
  9361. * use getDecendants instead.
  9362. */
  9363. Node.prototype.getChildren = function (predicate) {
  9364. return this.getDescendants(true, predicate);
  9365. };
  9366. /**
  9367. * Get all child-meshes of this node.
  9368. */
  9369. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9370. var results = [];
  9371. this._getDescendants(results, directDecendantsOnly, function (node) {
  9372. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9373. });
  9374. return results;
  9375. };
  9376. Node.prototype._setReady = function (state) {
  9377. if (state === this._isReady) {
  9378. return;
  9379. }
  9380. if (!state) {
  9381. this._isReady = false;
  9382. return;
  9383. }
  9384. this._isReady = true;
  9385. if (this.onReady) {
  9386. this.onReady(this);
  9387. }
  9388. };
  9389. Node.prototype.getAnimationByName = function (name) {
  9390. for (var i = 0; i < this.animations.length; i++) {
  9391. var animation = this.animations[i];
  9392. if (animation.name === name) {
  9393. return animation;
  9394. }
  9395. }
  9396. return null;
  9397. };
  9398. Node.prototype.createAnimationRange = function (name, from, to) {
  9399. // check name not already in use
  9400. if (!this._ranges[name]) {
  9401. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9402. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9403. if (this.animations[i]) {
  9404. this.animations[i].createRange(name, from, to);
  9405. }
  9406. }
  9407. }
  9408. };
  9409. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9410. if (deleteFrames === void 0) { deleteFrames = true; }
  9411. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9412. if (this.animations[i]) {
  9413. this.animations[i].deleteRange(name, deleteFrames);
  9414. }
  9415. }
  9416. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9417. };
  9418. Node.prototype.getAnimationRange = function (name) {
  9419. return this._ranges[name];
  9420. };
  9421. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9422. var range = this.getAnimationRange(name);
  9423. if (!range) {
  9424. return null;
  9425. }
  9426. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9427. };
  9428. Node.prototype.serializeAnimationRanges = function () {
  9429. var serializationRanges = [];
  9430. for (var name in this._ranges) {
  9431. var range = {};
  9432. range.name = name;
  9433. range.from = this._ranges[name].from;
  9434. range.to = this._ranges[name].to;
  9435. serializationRanges.push(range);
  9436. }
  9437. return serializationRanges;
  9438. };
  9439. Node.prototype.dispose = function () {
  9440. this.parent = null;
  9441. // Callback
  9442. this.onDisposeObservable.notifyObservers(this);
  9443. this.onDisposeObservable.clear();
  9444. };
  9445. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9446. if (parsedNode.ranges) {
  9447. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9448. var data = parsedNode.ranges[index];
  9449. node.createAnimationRange(data.name, data.from, data.to);
  9450. }
  9451. }
  9452. };
  9453. __decorate([
  9454. BABYLON.serialize()
  9455. ], Node.prototype, "name", void 0);
  9456. __decorate([
  9457. BABYLON.serialize()
  9458. ], Node.prototype, "id", void 0);
  9459. __decorate([
  9460. BABYLON.serialize()
  9461. ], Node.prototype, "uniqueId", void 0);
  9462. __decorate([
  9463. BABYLON.serialize()
  9464. ], Node.prototype, "state", void 0);
  9465. __decorate([
  9466. BABYLON.serialize()
  9467. ], Node.prototype, "metadata", void 0);
  9468. return Node;
  9469. }());
  9470. BABYLON.Node = Node;
  9471. })(BABYLON || (BABYLON = {}));
  9472. //# sourceMappingURL=babylon.node.js.map
  9473. var BABYLON;
  9474. (function (BABYLON) {
  9475. var FilesInput = (function () {
  9476. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9477. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9478. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9479. this._engine = p_engine;
  9480. this._canvas = p_canvas;
  9481. this._currentScene = p_scene;
  9482. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9483. this._progressCallback = p_progressCallback;
  9484. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9485. this._textureLoadingCallback = p_textureLoadingCallback;
  9486. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9487. }
  9488. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9489. var _this = this;
  9490. if (p_elementToMonitor) {
  9491. this._elementToMonitor = p_elementToMonitor;
  9492. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9493. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9494. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9495. }
  9496. };
  9497. FilesInput.prototype.renderFunction = function () {
  9498. if (this._additionnalRenderLoopLogicCallback) {
  9499. this._additionnalRenderLoopLogicCallback();
  9500. }
  9501. if (this._currentScene) {
  9502. if (this._textureLoadingCallback) {
  9503. var remaining = this._currentScene.getWaitingItemsCount();
  9504. if (remaining > 0) {
  9505. this._textureLoadingCallback(remaining);
  9506. }
  9507. }
  9508. this._currentScene.render();
  9509. }
  9510. };
  9511. FilesInput.prototype.drag = function (e) {
  9512. e.stopPropagation();
  9513. e.preventDefault();
  9514. };
  9515. FilesInput.prototype.drop = function (eventDrop) {
  9516. eventDrop.stopPropagation();
  9517. eventDrop.preventDefault();
  9518. this.loadFiles(eventDrop);
  9519. };
  9520. FilesInput.prototype.loadFiles = function (event) {
  9521. if (this._startingProcessingFilesCallback)
  9522. this._startingProcessingFilesCallback();
  9523. // Handling data transfer via drag'n'drop
  9524. if (event && event.dataTransfer && event.dataTransfer.files) {
  9525. this._filesToLoad = event.dataTransfer.files;
  9526. }
  9527. // Handling files from input files
  9528. if (event && event.target && event.target.files) {
  9529. this._filesToLoad = event.target.files;
  9530. }
  9531. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9532. for (var i = 0; i < this._filesToLoad.length; i++) {
  9533. switch (this._filesToLoad[i].type) {
  9534. case "image/jpeg":
  9535. case "image/png":
  9536. case "image/bmp":
  9537. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9538. break;
  9539. case "image/targa":
  9540. case "image/vnd.ms-dds":
  9541. case "audio/wav":
  9542. case "audio/x-wav":
  9543. case "audio/mp3":
  9544. case "audio/mpeg":
  9545. case "audio/mpeg3":
  9546. case "audio/x-mpeg-3":
  9547. case "audio/ogg":
  9548. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9549. break;
  9550. default:
  9551. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9552. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9553. }
  9554. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9555. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9556. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9557. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9558. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9559. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9560. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9561. this._sceneFileToLoad = this._filesToLoad[i];
  9562. }
  9563. break;
  9564. }
  9565. }
  9566. this.reload();
  9567. }
  9568. };
  9569. FilesInput.prototype.reload = function () {
  9570. var _this = this;
  9571. var that = this;
  9572. // If a ".babylon" file has been provided
  9573. if (this._sceneFileToLoad) {
  9574. if (this._currentScene) {
  9575. if (BABYLON.Tools.errorsCount > 0) {
  9576. BABYLON.Tools.ClearLogCache();
  9577. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9578. }
  9579. this._engine.stopRenderLoop();
  9580. this._currentScene.dispose();
  9581. }
  9582. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9583. that._currentScene = newScene;
  9584. // Wait for textures and shaders to be ready
  9585. that._currentScene.executeWhenReady(function () {
  9586. // Attach camera to canvas inputs
  9587. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9588. that._currentScene.createDefaultCameraOrLight();
  9589. }
  9590. that._currentScene.activeCamera.attachControl(that._canvas);
  9591. if (that._sceneLoadedCallback) {
  9592. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9593. }
  9594. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9595. });
  9596. }, function (progress) {
  9597. if (_this._progressCallback) {
  9598. _this._progressCallback(progress);
  9599. }
  9600. });
  9601. }
  9602. else {
  9603. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9604. }
  9605. };
  9606. FilesInput.FilesTextures = new Array();
  9607. FilesInput.FilesToLoad = new Array();
  9608. return FilesInput;
  9609. }());
  9610. BABYLON.FilesInput = FilesInput;
  9611. })(BABYLON || (BABYLON = {}));
  9612. //# sourceMappingURL=babylon.filesInput.js.map
  9613. var BABYLON;
  9614. (function (BABYLON) {
  9615. var IntersectionInfo = (function () {
  9616. function IntersectionInfo(bu, bv, distance) {
  9617. this.bu = bu;
  9618. this.bv = bv;
  9619. this.distance = distance;
  9620. this.faceId = 0;
  9621. this.subMeshId = 0;
  9622. }
  9623. return IntersectionInfo;
  9624. }());
  9625. BABYLON.IntersectionInfo = IntersectionInfo;
  9626. var PickingInfo = (function () {
  9627. function PickingInfo() {
  9628. this.hit = false;
  9629. this.distance = 0;
  9630. this.pickedPoint = null;
  9631. this.pickedMesh = null;
  9632. this.bu = 0;
  9633. this.bv = 0;
  9634. this.faceId = -1;
  9635. this.subMeshId = 0;
  9636. this.pickedSprite = null;
  9637. }
  9638. // Methods
  9639. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9640. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9641. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9642. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9643. return null;
  9644. }
  9645. var indices = this.pickedMesh.getIndices();
  9646. var result;
  9647. if (useVerticesNormals) {
  9648. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9649. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9650. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9651. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9652. normal0 = normal0.scale(this.bu);
  9653. normal1 = normal1.scale(this.bv);
  9654. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9655. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9656. }
  9657. else {
  9658. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9659. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9660. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9661. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9662. var p1p2 = vertex1.subtract(vertex2);
  9663. var p3p2 = vertex3.subtract(vertex2);
  9664. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9665. }
  9666. if (useWorldCoordinates) {
  9667. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9668. }
  9669. return BABYLON.Vector3.Normalize(result);
  9670. };
  9671. PickingInfo.prototype.getTextureCoordinates = function () {
  9672. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9673. return null;
  9674. }
  9675. var indices = this.pickedMesh.getIndices();
  9676. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9677. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9678. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9679. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9680. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9681. uv1 = uv1.scale(this.bu);
  9682. uv2 = uv2.scale(this.bv);
  9683. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9684. };
  9685. return PickingInfo;
  9686. }());
  9687. BABYLON.PickingInfo = PickingInfo;
  9688. })(BABYLON || (BABYLON = {}));
  9689. //# sourceMappingURL=babylon.pickingInfo.js.map
  9690. var BABYLON;
  9691. (function (BABYLON) {
  9692. var BoundingSphere = (function () {
  9693. function BoundingSphere(minimum, maximum) {
  9694. this.minimum = minimum;
  9695. this.maximum = maximum;
  9696. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9697. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9698. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9699. this.radius = distance * 0.5;
  9700. this.centerWorld = BABYLON.Vector3.Zero();
  9701. this._update(BABYLON.Matrix.Identity());
  9702. }
  9703. // Methods
  9704. BoundingSphere.prototype._update = function (world) {
  9705. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9706. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9707. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9708. };
  9709. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9710. for (var i = 0; i < 6; i++) {
  9711. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9712. return false;
  9713. }
  9714. return true;
  9715. };
  9716. BoundingSphere.prototype.intersectsPoint = function (point) {
  9717. var x = this.centerWorld.x - point.x;
  9718. var y = this.centerWorld.y - point.y;
  9719. var z = this.centerWorld.z - point.z;
  9720. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9721. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9722. return false;
  9723. return true;
  9724. };
  9725. // Statics
  9726. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9727. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9728. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9729. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9730. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9731. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9732. return false;
  9733. return true;
  9734. };
  9735. return BoundingSphere;
  9736. }());
  9737. BABYLON.BoundingSphere = BoundingSphere;
  9738. })(BABYLON || (BABYLON = {}));
  9739. //# sourceMappingURL=babylon.boundingSphere.js.map
  9740. var BABYLON;
  9741. (function (BABYLON) {
  9742. var BoundingBox = (function () {
  9743. function BoundingBox(minimum, maximum) {
  9744. this.minimum = minimum;
  9745. this.maximum = maximum;
  9746. this.vectors = new Array();
  9747. this.vectorsWorld = new Array();
  9748. // Bounding vectors
  9749. this.vectors.push(this.minimum.clone());
  9750. this.vectors.push(this.maximum.clone());
  9751. this.vectors.push(this.minimum.clone());
  9752. this.vectors[2].x = this.maximum.x;
  9753. this.vectors.push(this.minimum.clone());
  9754. this.vectors[3].y = this.maximum.y;
  9755. this.vectors.push(this.minimum.clone());
  9756. this.vectors[4].z = this.maximum.z;
  9757. this.vectors.push(this.maximum.clone());
  9758. this.vectors[5].z = this.minimum.z;
  9759. this.vectors.push(this.maximum.clone());
  9760. this.vectors[6].x = this.minimum.x;
  9761. this.vectors.push(this.maximum.clone());
  9762. this.vectors[7].y = this.minimum.y;
  9763. // OBB
  9764. this.center = this.maximum.add(this.minimum).scale(0.5);
  9765. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9766. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9767. // World
  9768. for (var index = 0; index < this.vectors.length; index++) {
  9769. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9770. }
  9771. this.minimumWorld = BABYLON.Vector3.Zero();
  9772. this.maximumWorld = BABYLON.Vector3.Zero();
  9773. this._update(BABYLON.Matrix.Identity());
  9774. }
  9775. // Methods
  9776. BoundingBox.prototype.getWorldMatrix = function () {
  9777. return this._worldMatrix;
  9778. };
  9779. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9780. this._worldMatrix.copyFrom(matrix);
  9781. return this;
  9782. };
  9783. BoundingBox.prototype._update = function (world) {
  9784. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9785. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9786. for (var index = 0; index < this.vectors.length; index++) {
  9787. var v = this.vectorsWorld[index];
  9788. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9789. if (v.x < this.minimumWorld.x)
  9790. this.minimumWorld.x = v.x;
  9791. if (v.y < this.minimumWorld.y)
  9792. this.minimumWorld.y = v.y;
  9793. if (v.z < this.minimumWorld.z)
  9794. this.minimumWorld.z = v.z;
  9795. if (v.x > this.maximumWorld.x)
  9796. this.maximumWorld.x = v.x;
  9797. if (v.y > this.maximumWorld.y)
  9798. this.maximumWorld.y = v.y;
  9799. if (v.z > this.maximumWorld.z)
  9800. this.maximumWorld.z = v.z;
  9801. }
  9802. // OBB
  9803. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9804. this.center.scaleInPlace(0.5);
  9805. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9806. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9807. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9808. this._worldMatrix = world;
  9809. };
  9810. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9811. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9812. };
  9813. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9814. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9815. };
  9816. BoundingBox.prototype.intersectsPoint = function (point) {
  9817. var delta = -BABYLON.Epsilon;
  9818. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9819. return false;
  9820. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9821. return false;
  9822. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9823. return false;
  9824. return true;
  9825. };
  9826. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9827. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9828. };
  9829. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9830. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9831. return false;
  9832. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9833. return false;
  9834. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9835. return false;
  9836. return true;
  9837. };
  9838. // Statics
  9839. BoundingBox.Intersects = function (box0, box1) {
  9840. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9841. return false;
  9842. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9843. return false;
  9844. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9845. return false;
  9846. return true;
  9847. };
  9848. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9849. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9850. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9851. return (num <= (sphereRadius * sphereRadius));
  9852. };
  9853. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9854. for (var p = 0; p < 6; p++) {
  9855. for (var i = 0; i < 8; i++) {
  9856. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9857. return false;
  9858. }
  9859. }
  9860. }
  9861. return true;
  9862. };
  9863. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9864. for (var p = 0; p < 6; p++) {
  9865. var inCount = 8;
  9866. for (var i = 0; i < 8; i++) {
  9867. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9868. --inCount;
  9869. }
  9870. else {
  9871. break;
  9872. }
  9873. }
  9874. if (inCount === 0)
  9875. return false;
  9876. }
  9877. return true;
  9878. };
  9879. return BoundingBox;
  9880. }());
  9881. BABYLON.BoundingBox = BoundingBox;
  9882. })(BABYLON || (BABYLON = {}));
  9883. //# sourceMappingURL=babylon.boundingBox.js.map
  9884. var BABYLON;
  9885. (function (BABYLON) {
  9886. var computeBoxExtents = function (axis, box) {
  9887. var p = BABYLON.Vector3.Dot(box.center, axis);
  9888. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9889. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9890. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9891. var r = r0 + r1 + r2;
  9892. return {
  9893. min: p - r,
  9894. max: p + r
  9895. };
  9896. };
  9897. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9898. var axisOverlap = function (axis, box0, box1) {
  9899. var result0 = computeBoxExtents(axis, box0);
  9900. var result1 = computeBoxExtents(axis, box1);
  9901. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9902. };
  9903. var BoundingInfo = (function () {
  9904. function BoundingInfo(minimum, maximum) {
  9905. this.minimum = minimum;
  9906. this.maximum = maximum;
  9907. this._isLocked = false;
  9908. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9909. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9910. }
  9911. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9912. get: function () {
  9913. return this._isLocked;
  9914. },
  9915. set: function (value) {
  9916. this._isLocked = value;
  9917. },
  9918. enumerable: true,
  9919. configurable: true
  9920. });
  9921. // Methods
  9922. BoundingInfo.prototype.update = function (world) {
  9923. if (this._isLocked) {
  9924. return;
  9925. }
  9926. this.boundingBox._update(world);
  9927. this.boundingSphere._update(world);
  9928. };
  9929. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9930. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9931. return false;
  9932. return this.boundingBox.isInFrustum(frustumPlanes);
  9933. };
  9934. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9935. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9936. };
  9937. BoundingInfo.prototype._checkCollision = function (collider) {
  9938. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9939. };
  9940. BoundingInfo.prototype.intersectsPoint = function (point) {
  9941. if (!this.boundingSphere.centerWorld) {
  9942. return false;
  9943. }
  9944. if (!this.boundingSphere.intersectsPoint(point)) {
  9945. return false;
  9946. }
  9947. if (!this.boundingBox.intersectsPoint(point)) {
  9948. return false;
  9949. }
  9950. return true;
  9951. };
  9952. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9953. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9954. return false;
  9955. }
  9956. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9957. return false;
  9958. }
  9959. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9960. return false;
  9961. }
  9962. if (!precise) {
  9963. return true;
  9964. }
  9965. var box0 = this.boundingBox;
  9966. var box1 = boundingInfo.boundingBox;
  9967. if (!axisOverlap(box0.directions[0], box0, box1))
  9968. return false;
  9969. if (!axisOverlap(box0.directions[1], box0, box1))
  9970. return false;
  9971. if (!axisOverlap(box0.directions[2], box0, box1))
  9972. return false;
  9973. if (!axisOverlap(box1.directions[0], box0, box1))
  9974. return false;
  9975. if (!axisOverlap(box1.directions[1], box0, box1))
  9976. return false;
  9977. if (!axisOverlap(box1.directions[2], box0, box1))
  9978. return false;
  9979. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9980. return false;
  9981. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9982. return false;
  9983. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9984. return false;
  9985. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9986. return false;
  9987. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9988. return false;
  9989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9990. return false;
  9991. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9992. return false;
  9993. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9994. return false;
  9995. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9996. return false;
  9997. return true;
  9998. };
  9999. return BoundingInfo;
  10000. }());
  10001. BABYLON.BoundingInfo = BoundingInfo;
  10002. })(BABYLON || (BABYLON = {}));
  10003. //# sourceMappingURL=babylon.boundingInfo.js.map
  10004. var BABYLON;
  10005. (function (BABYLON) {
  10006. var Ray = (function () {
  10007. function Ray(origin, direction, length) {
  10008. if (length === void 0) { length = Number.MAX_VALUE; }
  10009. this.origin = origin;
  10010. this.direction = direction;
  10011. this.length = length;
  10012. this._show = false;
  10013. }
  10014. // Methods
  10015. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10016. var d = 0.0;
  10017. var maxValue = Number.MAX_VALUE;
  10018. var inv;
  10019. var min;
  10020. var max;
  10021. var temp;
  10022. if (Math.abs(this.direction.x) < 0.0000001) {
  10023. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10024. return false;
  10025. }
  10026. }
  10027. else {
  10028. inv = 1.0 / this.direction.x;
  10029. min = (minimum.x - this.origin.x) * inv;
  10030. max = (maximum.x - this.origin.x) * inv;
  10031. if (max === -Infinity) {
  10032. max = Infinity;
  10033. }
  10034. if (min > max) {
  10035. temp = min;
  10036. min = max;
  10037. max = temp;
  10038. }
  10039. d = Math.max(min, d);
  10040. maxValue = Math.min(max, maxValue);
  10041. if (d > maxValue) {
  10042. return false;
  10043. }
  10044. }
  10045. if (Math.abs(this.direction.y) < 0.0000001) {
  10046. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10047. return false;
  10048. }
  10049. }
  10050. else {
  10051. inv = 1.0 / this.direction.y;
  10052. min = (minimum.y - this.origin.y) * inv;
  10053. max = (maximum.y - this.origin.y) * inv;
  10054. if (max === -Infinity) {
  10055. max = Infinity;
  10056. }
  10057. if (min > max) {
  10058. temp = min;
  10059. min = max;
  10060. max = temp;
  10061. }
  10062. d = Math.max(min, d);
  10063. maxValue = Math.min(max, maxValue);
  10064. if (d > maxValue) {
  10065. return false;
  10066. }
  10067. }
  10068. if (Math.abs(this.direction.z) < 0.0000001) {
  10069. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10070. return false;
  10071. }
  10072. }
  10073. else {
  10074. inv = 1.0 / this.direction.z;
  10075. min = (minimum.z - this.origin.z) * inv;
  10076. max = (maximum.z - this.origin.z) * inv;
  10077. if (max === -Infinity) {
  10078. max = Infinity;
  10079. }
  10080. if (min > max) {
  10081. temp = min;
  10082. min = max;
  10083. max = temp;
  10084. }
  10085. d = Math.max(min, d);
  10086. maxValue = Math.min(max, maxValue);
  10087. if (d > maxValue) {
  10088. return false;
  10089. }
  10090. }
  10091. return true;
  10092. };
  10093. Ray.prototype.intersectsBox = function (box) {
  10094. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10095. };
  10096. Ray.prototype.intersectsSphere = function (sphere) {
  10097. var x = sphere.center.x - this.origin.x;
  10098. var y = sphere.center.y - this.origin.y;
  10099. var z = sphere.center.z - this.origin.z;
  10100. var pyth = (x * x) + (y * y) + (z * z);
  10101. var rr = sphere.radius * sphere.radius;
  10102. if (pyth <= rr) {
  10103. return true;
  10104. }
  10105. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10106. if (dot < 0.0) {
  10107. return false;
  10108. }
  10109. var temp = pyth - (dot * dot);
  10110. return temp <= rr;
  10111. };
  10112. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10113. if (!this._edge1) {
  10114. this._edge1 = BABYLON.Vector3.Zero();
  10115. this._edge2 = BABYLON.Vector3.Zero();
  10116. this._pvec = BABYLON.Vector3.Zero();
  10117. this._tvec = BABYLON.Vector3.Zero();
  10118. this._qvec = BABYLON.Vector3.Zero();
  10119. }
  10120. vertex1.subtractToRef(vertex0, this._edge1);
  10121. vertex2.subtractToRef(vertex0, this._edge2);
  10122. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10123. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10124. if (det === 0) {
  10125. return null;
  10126. }
  10127. var invdet = 1 / det;
  10128. this.origin.subtractToRef(vertex0, this._tvec);
  10129. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10130. if (bu < 0 || bu > 1.0) {
  10131. return null;
  10132. }
  10133. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10134. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10135. if (bv < 0 || bu + bv > 1.0) {
  10136. return null;
  10137. }
  10138. //check if the distance is longer than the predefined length.
  10139. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10140. if (distance > this.length) {
  10141. return null;
  10142. }
  10143. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10144. };
  10145. Ray.prototype.intersectsPlane = function (plane) {
  10146. var distance;
  10147. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10148. if (Math.abs(result1) < 9.99999997475243E-07) {
  10149. return null;
  10150. }
  10151. else {
  10152. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10153. distance = (-plane.d - result2) / result1;
  10154. if (distance < 0.0) {
  10155. if (distance < -9.99999997475243E-07) {
  10156. return null;
  10157. }
  10158. else {
  10159. return 0;
  10160. }
  10161. }
  10162. return distance;
  10163. }
  10164. };
  10165. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10166. var tm = BABYLON.Tmp.Matrix[0];
  10167. mesh.getWorldMatrix().invertToRef(tm);
  10168. if (this._tmpRay) {
  10169. Ray.TransformToRef(this, tm, this._tmpRay);
  10170. }
  10171. else {
  10172. this._tmpRay = Ray.Transform(this, tm);
  10173. }
  10174. return mesh.intersects(this._tmpRay, fastCheck);
  10175. };
  10176. Ray.prototype.show = function (scene, color) {
  10177. if (!this._show) {
  10178. this._renderFunction = this._render.bind(this);
  10179. this._show = true;
  10180. this._scene = scene;
  10181. this._renderPoints = [this.origin, this.origin.add(this.direction.scale(this.length))];
  10182. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10183. this._scene.registerBeforeRender(this._renderFunction);
  10184. }
  10185. if (color) {
  10186. this._renderLine.color.copyFrom(color);
  10187. }
  10188. };
  10189. Ray.prototype.hide = function () {
  10190. if (this._show) {
  10191. this._show = false;
  10192. this._scene.unregisterBeforeRender(this._renderFunction);
  10193. }
  10194. if (this._renderLine) {
  10195. this._renderLine.dispose();
  10196. this._renderLine = null;
  10197. this._renderPoints = null;
  10198. }
  10199. };
  10200. Ray.prototype._render = function () {
  10201. var point = this._renderPoints[1];
  10202. point.copyFrom(this.direction);
  10203. point.scaleInPlace(this.length);
  10204. point.addInPlace(this.origin);
  10205. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10206. };
  10207. /**
  10208. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10209. * @param sega the first point of the segment to test the intersection against
  10210. * @param segb the second point of the segment to test the intersection against
  10211. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10212. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10213. */
  10214. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10215. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10216. var u = segb.subtract(sega);
  10217. var v = rsegb.subtract(this.origin);
  10218. var w = sega.subtract(this.origin);
  10219. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10220. var b = BABYLON.Vector3.Dot(u, v);
  10221. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10222. var d = BABYLON.Vector3.Dot(u, w);
  10223. var e = BABYLON.Vector3.Dot(v, w);
  10224. var D = a * c - b * b; // always >= 0
  10225. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10226. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10227. // compute the line parameters of the two closest points
  10228. if (D < Ray.smallnum) {
  10229. sN = 0.0; // force using point P0 on segment S1
  10230. sD = 1.0; // to prevent possible division by 0.0 later
  10231. tN = e;
  10232. tD = c;
  10233. }
  10234. else {
  10235. sN = (b * e - c * d);
  10236. tN = (a * e - b * d);
  10237. if (sN < 0.0) {
  10238. sN = 0.0;
  10239. tN = e;
  10240. tD = c;
  10241. }
  10242. else if (sN > sD) {
  10243. sN = sD;
  10244. tN = e + b;
  10245. tD = c;
  10246. }
  10247. }
  10248. if (tN < 0.0) {
  10249. tN = 0.0;
  10250. // recompute sc for this edge
  10251. if (-d < 0.0) {
  10252. sN = 0.0;
  10253. }
  10254. else if (-d > a)
  10255. sN = sD;
  10256. else {
  10257. sN = -d;
  10258. sD = a;
  10259. }
  10260. }
  10261. else if (tN > tD) {
  10262. tN = tD;
  10263. // recompute sc for this edge
  10264. if ((-d + b) < 0.0) {
  10265. sN = 0;
  10266. }
  10267. else if ((-d + b) > a) {
  10268. sN = sD;
  10269. }
  10270. else {
  10271. sN = (-d + b);
  10272. sD = a;
  10273. }
  10274. }
  10275. // finally do the division to get sc and tc
  10276. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10277. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10278. // get the difference of the two closest points
  10279. var qtc = v.multiplyByFloats(tc, tc, tc);
  10280. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10281. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10282. if (isIntersected) {
  10283. return qtc.length();
  10284. }
  10285. return -1;
  10286. };
  10287. // Statics
  10288. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10289. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10290. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10291. var direction = end.subtract(start);
  10292. direction.normalize();
  10293. return new Ray(start, direction);
  10294. };
  10295. /**
  10296. * 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
  10297. * transformed to the given world matrix.
  10298. * @param origin The origin point
  10299. * @param end The end point
  10300. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10301. */
  10302. Ray.CreateNewFromTo = function (origin, end, world) {
  10303. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10304. var direction = end.subtract(origin);
  10305. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10306. direction.normalize();
  10307. return Ray.Transform(new Ray(origin, direction, length), world);
  10308. };
  10309. Ray.Transform = function (ray, matrix) {
  10310. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10311. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10312. newDirection.normalize();
  10313. return new Ray(newOrigin, newDirection, ray.length);
  10314. };
  10315. Ray.TransformToRef = function (ray, matrix, result) {
  10316. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10317. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10318. ray.direction.normalize();
  10319. };
  10320. Ray.smallnum = 0.00000001;
  10321. Ray.rayl = 10e8;
  10322. return Ray;
  10323. }());
  10324. BABYLON.Ray = Ray;
  10325. })(BABYLON || (BABYLON = {}));
  10326. //# sourceMappingURL=babylon.ray.js.map
  10327. var BABYLON;
  10328. (function (BABYLON) {
  10329. var AbstractMesh = (function (_super) {
  10330. __extends(AbstractMesh, _super);
  10331. // Constructor
  10332. function AbstractMesh(name, scene) {
  10333. var _this = this;
  10334. _super.call(this, name, scene);
  10335. // Events
  10336. /**
  10337. * An event triggered when this mesh collides with another one
  10338. * @type {BABYLON.Observable}
  10339. */
  10340. this.onCollideObservable = new BABYLON.Observable();
  10341. /**
  10342. * An event triggered when the collision's position changes
  10343. * @type {BABYLON.Observable}
  10344. */
  10345. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10346. /**
  10347. * An event triggered after the world matrix is updated
  10348. * @type {BABYLON.Observable}
  10349. */
  10350. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10351. // Properties
  10352. this.definedFacingForward = true; // orientation for POV movement & rotation
  10353. this.position = new BABYLON.Vector3(0, 0, 0);
  10354. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10355. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10356. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10357. this.visibility = 1.0;
  10358. this.alphaIndex = Number.MAX_VALUE;
  10359. this.infiniteDistance = false;
  10360. this.isVisible = true;
  10361. this.isPickable = true;
  10362. this.showBoundingBox = false;
  10363. this.showSubMeshesBoundingBox = false;
  10364. this.isBlocker = false;
  10365. this.renderingGroupId = 0;
  10366. this.receiveShadows = false;
  10367. this.renderOutline = false;
  10368. this.outlineColor = BABYLON.Color3.Red();
  10369. this.outlineWidth = 0.02;
  10370. this.renderOverlay = false;
  10371. this.overlayColor = BABYLON.Color3.Red();
  10372. this.overlayAlpha = 0.5;
  10373. this.hasVertexAlpha = false;
  10374. this.useVertexColors = true;
  10375. this.applyFog = true;
  10376. this.computeBonesUsingShaders = true;
  10377. this.scalingDeterminant = 1;
  10378. this.numBoneInfluencers = 4;
  10379. this.useOctreeForRenderingSelection = true;
  10380. this.useOctreeForPicking = true;
  10381. this.useOctreeForCollisions = true;
  10382. this.layerMask = 0x0FFFFFFF;
  10383. this.alwaysSelectAsActiveMesh = false;
  10384. // Collisions
  10385. this._checkCollisions = false;
  10386. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10387. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10388. this._collider = new BABYLON.Collider();
  10389. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10390. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10391. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10392. // Edges
  10393. this.edgesWidth = 1;
  10394. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10395. // Cache
  10396. this._localWorld = BABYLON.Matrix.Zero();
  10397. this._worldMatrix = BABYLON.Matrix.Zero();
  10398. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10399. this._absolutePosition = BABYLON.Vector3.Zero();
  10400. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10401. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10402. this._isDirty = false;
  10403. this._pivotMatrix = BABYLON.Matrix.Identity();
  10404. this._isDisposed = false;
  10405. this._renderId = 0;
  10406. this._intersectionsInProgress = new Array();
  10407. this._isWorldMatrixFrozen = false;
  10408. this._unIndexed = false;
  10409. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10410. if (collidedMesh === void 0) { collidedMesh = null; }
  10411. //TODO move this to the collision coordinator!
  10412. if (_this.getScene().workerCollisions)
  10413. newPosition.multiplyInPlace(_this._collider.radius);
  10414. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10415. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10416. _this.position.addInPlace(_this._diffPositionForCollisions);
  10417. }
  10418. if (collidedMesh) {
  10419. _this.onCollideObservable.notifyObservers(collidedMesh);
  10420. }
  10421. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10422. };
  10423. scene.addMesh(this);
  10424. }
  10425. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10426. get: function () {
  10427. return AbstractMesh._BILLBOARDMODE_NONE;
  10428. },
  10429. enumerable: true,
  10430. configurable: true
  10431. });
  10432. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10433. get: function () {
  10434. return AbstractMesh._BILLBOARDMODE_X;
  10435. },
  10436. enumerable: true,
  10437. configurable: true
  10438. });
  10439. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10440. get: function () {
  10441. return AbstractMesh._BILLBOARDMODE_Y;
  10442. },
  10443. enumerable: true,
  10444. configurable: true
  10445. });
  10446. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10447. get: function () {
  10448. return AbstractMesh._BILLBOARDMODE_Z;
  10449. },
  10450. enumerable: true,
  10451. configurable: true
  10452. });
  10453. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10454. get: function () {
  10455. return AbstractMesh._BILLBOARDMODE_ALL;
  10456. },
  10457. enumerable: true,
  10458. configurable: true
  10459. });
  10460. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10461. set: function (callback) {
  10462. if (this._onCollideObserver) {
  10463. this.onCollideObservable.remove(this._onCollideObserver);
  10464. }
  10465. this._onCollideObserver = this.onCollideObservable.add(callback);
  10466. },
  10467. enumerable: true,
  10468. configurable: true
  10469. });
  10470. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10471. set: function (callback) {
  10472. if (this._onCollisionPositionChangeObserver) {
  10473. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10474. }
  10475. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10476. },
  10477. enumerable: true,
  10478. configurable: true
  10479. });
  10480. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10481. get: function () {
  10482. return this._skeleton;
  10483. },
  10484. set: function (value) {
  10485. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10486. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10487. }
  10488. if (value && value.needInitialSkinMatrix) {
  10489. value._registerMeshWithPoseMatrix(this);
  10490. }
  10491. this._skeleton = value;
  10492. if (!this._skeleton) {
  10493. this._bonesTransformMatrices = null;
  10494. }
  10495. },
  10496. enumerable: true,
  10497. configurable: true
  10498. });
  10499. AbstractMesh.prototype.getClassName = function () {
  10500. return "AbstractMesh";
  10501. };
  10502. /**
  10503. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10504. */
  10505. AbstractMesh.prototype.toString = function (fullDetails) {
  10506. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10507. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10508. if (this._skeleton) {
  10509. ret += ", skeleton: " + this._skeleton.name;
  10510. }
  10511. if (fullDetails) {
  10512. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10513. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10514. }
  10515. return ret;
  10516. };
  10517. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10518. /**
  10519. * Getting the rotation object.
  10520. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10521. */
  10522. get: function () {
  10523. return this._rotation;
  10524. },
  10525. set: function (newRotation) {
  10526. this._rotation = newRotation;
  10527. },
  10528. enumerable: true,
  10529. configurable: true
  10530. });
  10531. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10532. get: function () {
  10533. return this._scaling;
  10534. },
  10535. set: function (newScaling) {
  10536. this._scaling = newScaling;
  10537. if (this.physicsImpostor) {
  10538. this.physicsImpostor.forceUpdate();
  10539. }
  10540. },
  10541. enumerable: true,
  10542. configurable: true
  10543. });
  10544. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10545. get: function () {
  10546. return this._rotationQuaternion;
  10547. },
  10548. set: function (quaternion) {
  10549. this._rotationQuaternion = quaternion;
  10550. //reset the rotation vector.
  10551. if (quaternion && this.rotation.length()) {
  10552. this.rotation.copyFromFloats(0, 0, 0);
  10553. }
  10554. },
  10555. enumerable: true,
  10556. configurable: true
  10557. });
  10558. // Methods
  10559. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10560. this._poseMatrix.copyFrom(matrix);
  10561. };
  10562. AbstractMesh.prototype.getPoseMatrix = function () {
  10563. return this._poseMatrix;
  10564. };
  10565. AbstractMesh.prototype.disableEdgesRendering = function () {
  10566. if (this._edgesRenderer !== undefined) {
  10567. this._edgesRenderer.dispose();
  10568. this._edgesRenderer = undefined;
  10569. }
  10570. };
  10571. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10572. if (epsilon === void 0) { epsilon = 0.95; }
  10573. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10574. this.disableEdgesRendering();
  10575. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10576. };
  10577. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10578. get: function () {
  10579. return false;
  10580. },
  10581. enumerable: true,
  10582. configurable: true
  10583. });
  10584. AbstractMesh.prototype.getLOD = function (camera) {
  10585. return this;
  10586. };
  10587. AbstractMesh.prototype.getTotalVertices = function () {
  10588. return 0;
  10589. };
  10590. AbstractMesh.prototype.getIndices = function () {
  10591. return null;
  10592. };
  10593. AbstractMesh.prototype.getVerticesData = function (kind) {
  10594. return null;
  10595. };
  10596. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10597. return false;
  10598. };
  10599. AbstractMesh.prototype.getBoundingInfo = function () {
  10600. if (this._masterMesh) {
  10601. return this._masterMesh.getBoundingInfo();
  10602. }
  10603. if (!this._boundingInfo) {
  10604. this._updateBoundingInfo();
  10605. }
  10606. return this._boundingInfo;
  10607. };
  10608. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10609. this._boundingInfo = boundingInfo;
  10610. };
  10611. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10612. get: function () {
  10613. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10614. },
  10615. enumerable: true,
  10616. configurable: true
  10617. });
  10618. AbstractMesh.prototype._preActivate = function () {
  10619. };
  10620. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10621. };
  10622. AbstractMesh.prototype._activate = function (renderId) {
  10623. this._renderId = renderId;
  10624. };
  10625. AbstractMesh.prototype.getWorldMatrix = function () {
  10626. if (this._masterMesh) {
  10627. return this._masterMesh.getWorldMatrix();
  10628. }
  10629. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10630. this.computeWorldMatrix();
  10631. }
  10632. return this._worldMatrix;
  10633. };
  10634. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10635. get: function () {
  10636. return this._worldMatrix;
  10637. },
  10638. enumerable: true,
  10639. configurable: true
  10640. });
  10641. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10642. get: function () {
  10643. return this._absolutePosition;
  10644. },
  10645. enumerable: true,
  10646. configurable: true
  10647. });
  10648. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10649. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10650. this.computeWorldMatrix(true);
  10651. this._isWorldMatrixFrozen = true;
  10652. };
  10653. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10654. this._isWorldMatrixFrozen = false;
  10655. this.computeWorldMatrix(true);
  10656. };
  10657. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10658. get: function () {
  10659. return this._isWorldMatrixFrozen;
  10660. },
  10661. enumerable: true,
  10662. configurable: true
  10663. });
  10664. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10665. axis.normalize();
  10666. if (!this.rotationQuaternion) {
  10667. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10668. this.rotation = BABYLON.Vector3.Zero();
  10669. }
  10670. var rotationQuaternion;
  10671. if (!space || space === BABYLON.Space.LOCAL) {
  10672. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10673. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10674. }
  10675. else {
  10676. if (this.parent) {
  10677. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10678. invertParentWorldMatrix.invert();
  10679. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10680. }
  10681. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10682. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10683. }
  10684. };
  10685. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10686. var displacementVector = axis.scale(distance);
  10687. if (!space || space === BABYLON.Space.LOCAL) {
  10688. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10689. this.setPositionWithLocalVector(tempV3);
  10690. }
  10691. else {
  10692. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10693. }
  10694. };
  10695. AbstractMesh.prototype.getAbsolutePosition = function () {
  10696. this.computeWorldMatrix();
  10697. return this._absolutePosition;
  10698. };
  10699. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10700. if (!absolutePosition) {
  10701. return;
  10702. }
  10703. var absolutePositionX;
  10704. var absolutePositionY;
  10705. var absolutePositionZ;
  10706. if (absolutePosition.x === undefined) {
  10707. if (arguments.length < 3) {
  10708. return;
  10709. }
  10710. absolutePositionX = arguments[0];
  10711. absolutePositionY = arguments[1];
  10712. absolutePositionZ = arguments[2];
  10713. }
  10714. else {
  10715. absolutePositionX = absolutePosition.x;
  10716. absolutePositionY = absolutePosition.y;
  10717. absolutePositionZ = absolutePosition.z;
  10718. }
  10719. if (this.parent) {
  10720. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10721. invertParentWorldMatrix.invert();
  10722. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10723. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10724. }
  10725. else {
  10726. this.position.x = absolutePositionX;
  10727. this.position.y = absolutePositionY;
  10728. this.position.z = absolutePositionZ;
  10729. }
  10730. };
  10731. // ================================== Point of View Movement =================================
  10732. /**
  10733. * Perform relative position change from the point of view of behind the front of the mesh.
  10734. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10735. * Supports definition of mesh facing forward or backward.
  10736. * @param {number} amountRight
  10737. * @param {number} amountUp
  10738. * @param {number} amountForward
  10739. */
  10740. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10741. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10742. };
  10743. /**
  10744. * Calculate relative position change from the point of view of behind the front of the mesh.
  10745. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10746. * Supports definition of mesh facing forward or backward.
  10747. * @param {number} amountRight
  10748. * @param {number} amountUp
  10749. * @param {number} amountForward
  10750. */
  10751. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10752. var rotMatrix = new BABYLON.Matrix();
  10753. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10754. rotQuaternion.toRotationMatrix(rotMatrix);
  10755. var translationDelta = BABYLON.Vector3.Zero();
  10756. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10757. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10758. return translationDelta;
  10759. };
  10760. // ================================== Point of View Rotation =================================
  10761. /**
  10762. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10763. * Supports definition of mesh facing forward or backward.
  10764. * @param {number} flipBack
  10765. * @param {number} twirlClockwise
  10766. * @param {number} tiltRight
  10767. */
  10768. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10769. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10770. };
  10771. /**
  10772. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10773. * Supports definition of mesh facing forward or backward.
  10774. * @param {number} flipBack
  10775. * @param {number} twirlClockwise
  10776. * @param {number} tiltRight
  10777. */
  10778. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10779. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10780. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10781. };
  10782. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10783. this._pivotMatrix = matrix;
  10784. this._cache.pivotMatrixUpdated = true;
  10785. };
  10786. AbstractMesh.prototype.getPivotMatrix = function () {
  10787. return this._pivotMatrix;
  10788. };
  10789. AbstractMesh.prototype._isSynchronized = function () {
  10790. if (this._isDirty) {
  10791. return false;
  10792. }
  10793. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10794. return false;
  10795. if (this._cache.pivotMatrixUpdated) {
  10796. return false;
  10797. }
  10798. if (this.infiniteDistance) {
  10799. return false;
  10800. }
  10801. if (!this._cache.position.equals(this.position))
  10802. return false;
  10803. if (this.rotationQuaternion) {
  10804. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10805. return false;
  10806. }
  10807. if (!this._cache.rotation.equals(this.rotation))
  10808. return false;
  10809. if (!this._cache.scaling.equals(this.scaling))
  10810. return false;
  10811. return true;
  10812. };
  10813. AbstractMesh.prototype._initCache = function () {
  10814. _super.prototype._initCache.call(this);
  10815. this._cache.localMatrixUpdated = false;
  10816. this._cache.position = BABYLON.Vector3.Zero();
  10817. this._cache.scaling = BABYLON.Vector3.Zero();
  10818. this._cache.rotation = BABYLON.Vector3.Zero();
  10819. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10820. this._cache.billboardMode = -1;
  10821. };
  10822. AbstractMesh.prototype.markAsDirty = function (property) {
  10823. if (property === "rotation") {
  10824. this.rotationQuaternion = null;
  10825. }
  10826. this._currentRenderId = Number.MAX_VALUE;
  10827. this._isDirty = true;
  10828. };
  10829. AbstractMesh.prototype._updateBoundingInfo = function () {
  10830. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10831. this._boundingInfo.update(this.worldMatrixFromCache);
  10832. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10833. };
  10834. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10835. if (!this.subMeshes) {
  10836. return;
  10837. }
  10838. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10839. var subMesh = this.subMeshes[subIndex];
  10840. if (!subMesh.IsGlobal) {
  10841. subMesh.updateBoundingInfo(matrix);
  10842. }
  10843. }
  10844. };
  10845. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10846. if (this._isWorldMatrixFrozen) {
  10847. return this._worldMatrix;
  10848. }
  10849. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10850. this._currentRenderId = this.getScene().getRenderId();
  10851. return this._worldMatrix;
  10852. }
  10853. this._cache.position.copyFrom(this.position);
  10854. this._cache.scaling.copyFrom(this.scaling);
  10855. this._cache.pivotMatrixUpdated = false;
  10856. this._cache.billboardMode = this.billboardMode;
  10857. this._currentRenderId = this.getScene().getRenderId();
  10858. this._isDirty = false;
  10859. // Scaling
  10860. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10861. // Rotation
  10862. //rotate, if quaternion is set and rotation was used
  10863. if (this.rotationQuaternion) {
  10864. var len = this.rotation.length();
  10865. if (len) {
  10866. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10867. this.rotation.copyFromFloats(0, 0, 0);
  10868. }
  10869. }
  10870. if (this.rotationQuaternion) {
  10871. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10872. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10873. }
  10874. else {
  10875. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10876. this._cache.rotation.copyFrom(this.rotation);
  10877. }
  10878. // Translation
  10879. if (this.infiniteDistance && !this.parent) {
  10880. var camera = this.getScene().activeCamera;
  10881. if (camera) {
  10882. var cameraWorldMatrix = camera.getWorldMatrix();
  10883. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10884. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10885. }
  10886. }
  10887. else {
  10888. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10889. }
  10890. // Composing transformations
  10891. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10892. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10893. // Billboarding
  10894. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10895. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10896. var localPosition = BABYLON.Tmp.Vector3[0];
  10897. if (this.parent && this.parent.getWorldMatrix) {
  10898. this._markSyncedWithParent();
  10899. var parentMatrix;
  10900. if (this._meshToBoneReferal) {
  10901. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10902. parentMatrix = BABYLON.Tmp.Matrix[6];
  10903. }
  10904. else {
  10905. parentMatrix = this.parent.getWorldMatrix();
  10906. }
  10907. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10908. localPosition = BABYLON.Tmp.Vector3[1];
  10909. }
  10910. var zero = this.getScene().activeCamera.globalPosition.clone();
  10911. if (this.parent && this.parent.position) {
  10912. localPosition.addInPlace(this.parent.position);
  10913. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10914. }
  10915. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10916. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10917. zero.x = localPosition.x + BABYLON.Epsilon;
  10918. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10919. zero.y = localPosition.y + BABYLON.Epsilon;
  10920. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10921. zero.z = localPosition.z + BABYLON.Epsilon;
  10922. }
  10923. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10924. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10925. BABYLON.Tmp.Matrix[3].invert();
  10926. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10927. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10928. }
  10929. // Local world
  10930. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10931. // Parent
  10932. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10933. this._markSyncedWithParent();
  10934. if (this._meshToBoneReferal) {
  10935. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10936. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10937. }
  10938. else {
  10939. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10940. }
  10941. }
  10942. else {
  10943. this._worldMatrix.copyFrom(this._localWorld);
  10944. }
  10945. // Bounding info
  10946. this._updateBoundingInfo();
  10947. // Absolute position
  10948. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10949. // Callbacks
  10950. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10951. if (!this._poseMatrix) {
  10952. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10953. }
  10954. return this._worldMatrix;
  10955. };
  10956. /**
  10957. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10958. * @param func: callback function to add
  10959. */
  10960. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10961. this.onAfterWorldMatrixUpdateObservable.add(func);
  10962. };
  10963. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10964. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10965. };
  10966. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10967. this.computeWorldMatrix();
  10968. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10969. };
  10970. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10971. this.computeWorldMatrix();
  10972. var invLocalWorldMatrix = this._localWorld.clone();
  10973. invLocalWorldMatrix.invert();
  10974. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10975. };
  10976. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10977. this.computeWorldMatrix(true);
  10978. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10979. };
  10980. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10981. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10982. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10983. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10984. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10985. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10986. /// <returns>Mesh oriented towards targetMesh</returns>
  10987. if (yawCor === void 0) { yawCor = 0; }
  10988. if (pitchCor === void 0) { pitchCor = 0; }
  10989. if (rollCor === void 0) { rollCor = 0; }
  10990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10991. var dv = AbstractMesh._lookAtVectorCache;
  10992. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10993. targetPoint.subtractToRef(pos, dv);
  10994. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10995. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10996. var pitch = Math.atan2(dv.y, len);
  10997. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10998. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10999. };
  11000. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11001. this._meshToBoneReferal = affectedMesh;
  11002. this.parent = bone;
  11003. if (bone.getWorldMatrix().determinant() < 0) {
  11004. this.scalingDeterminant *= -1;
  11005. }
  11006. };
  11007. AbstractMesh.prototype.detachFromBone = function () {
  11008. if (this.parent.getWorldMatrix().determinant() < 0) {
  11009. this.scalingDeterminant *= -1;
  11010. }
  11011. this._meshToBoneReferal = null;
  11012. this.parent = null;
  11013. };
  11014. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11015. return this._boundingInfo.isInFrustum(frustumPlanes);
  11016. };
  11017. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11018. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11019. ;
  11020. };
  11021. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11022. if (!this._boundingInfo || !mesh._boundingInfo) {
  11023. return false;
  11024. }
  11025. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11026. };
  11027. AbstractMesh.prototype.intersectsPoint = function (point) {
  11028. if (!this._boundingInfo) {
  11029. return false;
  11030. }
  11031. return this._boundingInfo.intersectsPoint(point);
  11032. };
  11033. // Physics
  11034. /**
  11035. * @Deprecated. Use new PhysicsImpostor instead.
  11036. * */
  11037. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11038. //legacy support
  11039. if (impostor.impostor) {
  11040. options = impostor;
  11041. impostor = impostor.impostor;
  11042. }
  11043. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11044. return this.physicsImpostor.physicsBody;
  11045. };
  11046. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11047. return this.physicsImpostor;
  11048. };
  11049. /**
  11050. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11051. */
  11052. AbstractMesh.prototype.getPhysicsMass = function () {
  11053. return this.physicsImpostor.getParam("mass");
  11054. };
  11055. /**
  11056. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11057. */
  11058. AbstractMesh.prototype.getPhysicsFriction = function () {
  11059. return this.physicsImpostor.getParam("friction");
  11060. };
  11061. /**
  11062. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11063. */
  11064. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11065. return this.physicsImpostor.getParam("restitution");
  11066. };
  11067. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11068. if (!camera) {
  11069. camera = this.getScene().activeCamera;
  11070. }
  11071. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11072. };
  11073. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11074. if (!camera) {
  11075. camera = this.getScene().activeCamera;
  11076. }
  11077. return this.absolutePosition.subtract(camera.position).length();
  11078. };
  11079. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11080. if (!this.physicsImpostor) {
  11081. return;
  11082. }
  11083. this.physicsImpostor.applyImpulse(force, contactPoint);
  11084. };
  11085. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11086. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11087. return;
  11088. }
  11089. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11090. mainPivot: pivot1,
  11091. connectedPivot: pivot2,
  11092. nativeParams: options
  11093. });
  11094. };
  11095. /**
  11096. * @Deprecated
  11097. */
  11098. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11099. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11100. this.updatePhysicsBody();
  11101. };
  11102. /**
  11103. * @Deprecated
  11104. * Calling this function is not needed anymore.
  11105. * The physics engine takes care of transofmration automatically.
  11106. */
  11107. AbstractMesh.prototype.updatePhysicsBody = function () {
  11108. //Unneeded
  11109. };
  11110. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11111. // Collisions
  11112. get: function () {
  11113. return this._checkCollisions;
  11114. },
  11115. set: function (collisionEnabled) {
  11116. this._checkCollisions = collisionEnabled;
  11117. if (this.getScene().workerCollisions) {
  11118. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11119. }
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11125. var globalPosition = this.getAbsolutePosition();
  11126. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11127. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11128. this._collider.radius = this.ellipsoid;
  11129. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11130. };
  11131. // Submeshes octree
  11132. /**
  11133. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11134. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11135. */
  11136. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11137. if (maxCapacity === void 0) { maxCapacity = 64; }
  11138. if (maxDepth === void 0) { maxDepth = 2; }
  11139. if (!this._submeshesOctree) {
  11140. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11141. }
  11142. this.computeWorldMatrix(true);
  11143. // Update octree
  11144. var bbox = this.getBoundingInfo().boundingBox;
  11145. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11146. return this._submeshesOctree;
  11147. };
  11148. // Collisions
  11149. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11150. this._generatePointsArray();
  11151. // Transformation
  11152. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11153. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11154. subMesh._lastColliderWorldVertices = [];
  11155. subMesh._trianglePlanes = [];
  11156. var start = subMesh.verticesStart;
  11157. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11158. for (var i = start; i < end; i++) {
  11159. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11160. }
  11161. }
  11162. // Collide
  11163. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11164. if (collider.collisionFound) {
  11165. collider.collidedMesh = this;
  11166. }
  11167. };
  11168. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11169. var subMeshes;
  11170. var len;
  11171. // Octrees
  11172. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11173. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11174. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11175. len = intersections.length;
  11176. subMeshes = intersections.data;
  11177. }
  11178. else {
  11179. subMeshes = this.subMeshes;
  11180. len = subMeshes.length;
  11181. }
  11182. for (var index = 0; index < len; index++) {
  11183. var subMesh = subMeshes[index];
  11184. // Bounding test
  11185. if (len > 1 && !subMesh._checkCollision(collider))
  11186. continue;
  11187. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11188. }
  11189. };
  11190. AbstractMesh.prototype._checkCollision = function (collider) {
  11191. // Bounding box test
  11192. if (!this._boundingInfo._checkCollision(collider))
  11193. return;
  11194. // Transformation matrix
  11195. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11196. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11197. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11198. };
  11199. // Picking
  11200. AbstractMesh.prototype._generatePointsArray = function () {
  11201. return false;
  11202. };
  11203. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11204. var pickingInfo = new BABYLON.PickingInfo();
  11205. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11206. return pickingInfo;
  11207. }
  11208. if (!this._generatePointsArray()) {
  11209. return pickingInfo;
  11210. }
  11211. var intersectInfo = null;
  11212. // Octrees
  11213. var subMeshes;
  11214. var len;
  11215. if (this._submeshesOctree && this.useOctreeForPicking) {
  11216. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11217. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11218. len = intersections.length;
  11219. subMeshes = intersections.data;
  11220. }
  11221. else {
  11222. subMeshes = this.subMeshes;
  11223. len = subMeshes.length;
  11224. }
  11225. for (var index = 0; index < len; index++) {
  11226. var subMesh = subMeshes[index];
  11227. // Bounding test
  11228. if (len > 1 && !subMesh.canIntersects(ray))
  11229. continue;
  11230. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11231. if (currentIntersectInfo) {
  11232. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11233. intersectInfo = currentIntersectInfo;
  11234. intersectInfo.subMeshId = index;
  11235. if (fastCheck) {
  11236. break;
  11237. }
  11238. }
  11239. }
  11240. }
  11241. if (intersectInfo) {
  11242. // Get picked point
  11243. var world = this.getWorldMatrix();
  11244. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11245. var direction = ray.direction.clone();
  11246. direction = direction.scale(intersectInfo.distance);
  11247. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11248. var pickedPoint = worldOrigin.add(worldDirection);
  11249. // Return result
  11250. pickingInfo.hit = true;
  11251. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11252. pickingInfo.pickedPoint = pickedPoint;
  11253. pickingInfo.pickedMesh = this;
  11254. pickingInfo.bu = intersectInfo.bu;
  11255. pickingInfo.bv = intersectInfo.bv;
  11256. pickingInfo.faceId = intersectInfo.faceId;
  11257. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11258. return pickingInfo;
  11259. }
  11260. return pickingInfo;
  11261. };
  11262. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11263. return null;
  11264. };
  11265. AbstractMesh.prototype.releaseSubMeshes = function () {
  11266. if (this.subMeshes) {
  11267. while (this.subMeshes.length) {
  11268. this.subMeshes[0].dispose();
  11269. }
  11270. }
  11271. else {
  11272. this.subMeshes = new Array();
  11273. }
  11274. };
  11275. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11276. var _this = this;
  11277. var index;
  11278. // Action manager
  11279. if (this.actionManager) {
  11280. this.actionManager.dispose();
  11281. this.actionManager = null;
  11282. }
  11283. // Skeleton
  11284. this.skeleton = null;
  11285. // Animations
  11286. this.getScene().stopAnimation(this);
  11287. // Physics
  11288. if (this.physicsImpostor) {
  11289. this.physicsImpostor.dispose();
  11290. }
  11291. // Intersections in progress
  11292. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11293. var other = this._intersectionsInProgress[index];
  11294. var pos = other._intersectionsInProgress.indexOf(this);
  11295. other._intersectionsInProgress.splice(pos, 1);
  11296. }
  11297. this._intersectionsInProgress = [];
  11298. // Lights
  11299. var lights = this.getScene().lights;
  11300. lights.forEach(function (light) {
  11301. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11302. if (meshIndex !== -1) {
  11303. light.includedOnlyMeshes.splice(meshIndex, 1);
  11304. }
  11305. meshIndex = light.excludedMeshes.indexOf(_this);
  11306. if (meshIndex !== -1) {
  11307. light.excludedMeshes.splice(meshIndex, 1);
  11308. }
  11309. // Shadow generators
  11310. var generator = light.getShadowGenerator();
  11311. if (generator) {
  11312. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11313. if (meshIndex !== -1) {
  11314. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11315. }
  11316. }
  11317. });
  11318. // Edges
  11319. if (this._edgesRenderer) {
  11320. this._edgesRenderer.dispose();
  11321. this._edgesRenderer = null;
  11322. }
  11323. // SubMeshes
  11324. this.releaseSubMeshes();
  11325. // Engine
  11326. this.getScene().getEngine().unbindAllAttributes();
  11327. // Remove from scene
  11328. this.getScene().removeMesh(this);
  11329. if (!doNotRecurse) {
  11330. // Particles
  11331. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11332. if (this.getScene().particleSystems[index].emitter === this) {
  11333. this.getScene().particleSystems[index].dispose();
  11334. index--;
  11335. }
  11336. }
  11337. // Children
  11338. var objects = this.getDescendants(true);
  11339. for (index = 0; index < objects.length; index++) {
  11340. objects[index].dispose();
  11341. }
  11342. }
  11343. else {
  11344. var childMeshes = this.getChildMeshes(true);
  11345. for (index = 0; index < childMeshes.length; index++) {
  11346. var child = childMeshes[index];
  11347. child.parent = null;
  11348. child.computeWorldMatrix(true);
  11349. }
  11350. }
  11351. this.onAfterWorldMatrixUpdateObservable.clear();
  11352. this.onCollideObservable.clear();
  11353. this.onCollisionPositionChangeObservable.clear();
  11354. this._isDisposed = true;
  11355. _super.prototype.dispose.call(this);
  11356. };
  11357. AbstractMesh.prototype.getDirection = function (localAxis) {
  11358. var result = BABYLON.Vector3.Zero();
  11359. this.getDirectionToRef(localAxis, result);
  11360. return result;
  11361. };
  11362. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11363. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11364. };
  11365. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11366. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11367. if (this.getScene().getRenderId() == 0) {
  11368. this.computeWorldMatrix(true);
  11369. }
  11370. var wm = this.getWorldMatrix();
  11371. if (space == BABYLON.Space.WORLD) {
  11372. var tmat = BABYLON.Tmp.Matrix[0];
  11373. wm.invertToRef(tmat);
  11374. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11375. }
  11376. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11377. this._pivotMatrix.m[12] = -point.x;
  11378. this._pivotMatrix.m[13] = -point.y;
  11379. this._pivotMatrix.m[14] = -point.z;
  11380. this._cache.pivotMatrixUpdated = true;
  11381. };
  11382. AbstractMesh.prototype.getPivotPoint = function () {
  11383. var point = BABYLON.Vector3.Zero();
  11384. this.getPivotPointToRef(point);
  11385. return point;
  11386. };
  11387. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11388. result.x = -this._pivotMatrix.m[12];
  11389. result.y = -this._pivotMatrix.m[13];
  11390. result.z = -this._pivotMatrix.m[14];
  11391. };
  11392. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11393. var point = BABYLON.Vector3.Zero();
  11394. this.getAbsolutePivotPointToRef(point);
  11395. return point;
  11396. };
  11397. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11398. result.x = this._pivotMatrix.m[12];
  11399. result.y = this._pivotMatrix.m[13];
  11400. result.z = this._pivotMatrix.m[14];
  11401. this.getPivotPointToRef(result);
  11402. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11403. };
  11404. // Statics
  11405. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11406. AbstractMesh._BILLBOARDMODE_X = 1;
  11407. AbstractMesh._BILLBOARDMODE_Y = 2;
  11408. AbstractMesh._BILLBOARDMODE_Z = 4;
  11409. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11410. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11411. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11412. return AbstractMesh;
  11413. }(BABYLON.Node));
  11414. BABYLON.AbstractMesh = AbstractMesh;
  11415. })(BABYLON || (BABYLON = {}));
  11416. //# sourceMappingURL=babylon.abstractMesh.js.map
  11417. var BABYLON;
  11418. (function (BABYLON) {
  11419. var Light = (function (_super) {
  11420. __extends(Light, _super);
  11421. function Light(name, scene) {
  11422. _super.call(this, name, scene);
  11423. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11424. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11425. this.intensity = 1.0;
  11426. this.range = Number.MAX_VALUE;
  11427. this.includeOnlyWithLayerMask = 0;
  11428. this.includedOnlyMeshes = new Array();
  11429. this.excludedMeshes = new Array();
  11430. this.excludeWithLayerMask = 0;
  11431. this.lightmapMode = 0;
  11432. // PBR Properties.
  11433. this.radius = 0.00001;
  11434. this._excludedMeshesIds = new Array();
  11435. this._includedOnlyMeshesIds = new Array();
  11436. scene.addLight(this);
  11437. }
  11438. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11439. /**
  11440. * If every light affecting the material is in this lightmapMode,
  11441. * material.lightmapTexture adds or multiplies
  11442. * (depends on material.useLightmapAsShadowmap)
  11443. * after every other light calculations.
  11444. */
  11445. get: function () {
  11446. return Light._LIGHTMAP_DEFAULT;
  11447. },
  11448. enumerable: true,
  11449. configurable: true
  11450. });
  11451. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11452. /**
  11453. * material.lightmapTexture as only diffuse lighting from this light
  11454. * adds pnly specular lighting from this light
  11455. * adds dynamic shadows
  11456. */
  11457. get: function () {
  11458. return Light._LIGHTMAP_SPECULAR;
  11459. },
  11460. enumerable: true,
  11461. configurable: true
  11462. });
  11463. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11464. /**
  11465. * material.lightmapTexture as only lighting
  11466. * no light calculation from this light
  11467. * only adds dynamic shadows from this light
  11468. */
  11469. get: function () {
  11470. return Light._LIGHTMAP_SHADOWSONLY;
  11471. },
  11472. enumerable: true,
  11473. configurable: true
  11474. });
  11475. Light.prototype.getClassName = function () {
  11476. return "Light";
  11477. };
  11478. /**
  11479. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11480. */
  11481. Light.prototype.toString = function (fullDetails) {
  11482. var ret = "Name: " + this.name;
  11483. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11484. if (this.animations) {
  11485. for (var i = 0; i < this.animations.length; i++) {
  11486. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11487. }
  11488. }
  11489. if (fullDetails) {
  11490. }
  11491. return ret;
  11492. };
  11493. Light.prototype.getShadowGenerator = function () {
  11494. return this._shadowGenerator;
  11495. };
  11496. Light.prototype.getAbsolutePosition = function () {
  11497. return BABYLON.Vector3.Zero();
  11498. };
  11499. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11500. };
  11501. Light.prototype._getWorldMatrix = function () {
  11502. return BABYLON.Matrix.Identity();
  11503. };
  11504. Light.prototype.canAffectMesh = function (mesh) {
  11505. if (!mesh) {
  11506. return true;
  11507. }
  11508. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11509. return false;
  11510. }
  11511. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11512. return false;
  11513. }
  11514. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11515. return false;
  11516. }
  11517. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11518. return false;
  11519. }
  11520. return true;
  11521. };
  11522. Light.prototype.getWorldMatrix = function () {
  11523. this._currentRenderId = this.getScene().getRenderId();
  11524. var worldMatrix = this._getWorldMatrix();
  11525. if (this.parent && this.parent.getWorldMatrix) {
  11526. if (!this._parentedWorldMatrix) {
  11527. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11528. }
  11529. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11530. this._markSyncedWithParent();
  11531. return this._parentedWorldMatrix;
  11532. }
  11533. return worldMatrix;
  11534. };
  11535. Light.prototype.dispose = function () {
  11536. if (this._shadowGenerator) {
  11537. this._shadowGenerator.dispose();
  11538. this._shadowGenerator = null;
  11539. }
  11540. // Animations
  11541. this.getScene().stopAnimation(this);
  11542. // Remove from scene
  11543. this.getScene().removeLight(this);
  11544. _super.prototype.dispose.call(this);
  11545. };
  11546. Light.prototype.getTypeID = function () {
  11547. return 0;
  11548. };
  11549. Light.prototype.clone = function (name) {
  11550. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11551. };
  11552. Light.prototype.serialize = function () {
  11553. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11554. // Type
  11555. serializationObject.type = this.getTypeID();
  11556. // Parent
  11557. if (this.parent) {
  11558. serializationObject.parentId = this.parent.id;
  11559. }
  11560. // Inclusion / exclusions
  11561. if (this.excludedMeshes.length > 0) {
  11562. serializationObject.excludedMeshesIds = [];
  11563. this.excludedMeshes.forEach(function (mesh) {
  11564. serializationObject.excludedMeshesIds.push(mesh.id);
  11565. });
  11566. }
  11567. if (this.includedOnlyMeshes.length > 0) {
  11568. serializationObject.includedOnlyMeshesIds = [];
  11569. this.includedOnlyMeshes.forEach(function (mesh) {
  11570. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11571. });
  11572. }
  11573. // Animations
  11574. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11575. serializationObject.ranges = this.serializeAnimationRanges();
  11576. return serializationObject;
  11577. };
  11578. Light.GetConstructorFromName = function (type, name, scene) {
  11579. switch (type) {
  11580. case 0:
  11581. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11582. case 1:
  11583. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11584. case 2:
  11585. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11586. case 3:
  11587. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11588. }
  11589. };
  11590. Light.Parse = function (parsedLight, scene) {
  11591. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11592. // Inclusion / exclusions
  11593. if (parsedLight.excludedMeshesIds) {
  11594. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11595. }
  11596. if (parsedLight.includedOnlyMeshesIds) {
  11597. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11598. }
  11599. // Parent
  11600. if (parsedLight.parentId) {
  11601. light._waitingParentId = parsedLight.parentId;
  11602. }
  11603. // Animations
  11604. if (parsedLight.animations) {
  11605. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11606. var parsedAnimation = parsedLight.animations[animationIndex];
  11607. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11608. }
  11609. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11610. }
  11611. if (parsedLight.autoAnimate) {
  11612. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11613. }
  11614. return light;
  11615. };
  11616. //lightmapMode Consts
  11617. Light._LIGHTMAP_DEFAULT = 0;
  11618. Light._LIGHTMAP_SPECULAR = 1;
  11619. Light._LIGHTMAP_SHADOWSONLY = 2;
  11620. __decorate([
  11621. BABYLON.serializeAsColor3()
  11622. ], Light.prototype, "diffuse", void 0);
  11623. __decorate([
  11624. BABYLON.serializeAsColor3()
  11625. ], Light.prototype, "specular", void 0);
  11626. __decorate([
  11627. BABYLON.serialize()
  11628. ], Light.prototype, "intensity", void 0);
  11629. __decorate([
  11630. BABYLON.serialize()
  11631. ], Light.prototype, "range", void 0);
  11632. __decorate([
  11633. BABYLON.serialize()
  11634. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11635. __decorate([
  11636. BABYLON.serialize()
  11637. ], Light.prototype, "excludeWithLayerMask", void 0);
  11638. __decorate([
  11639. BABYLON.serialize()
  11640. ], Light.prototype, "lightmapMode", void 0);
  11641. __decorate([
  11642. BABYLON.serialize()
  11643. ], Light.prototype, "radius", void 0);
  11644. return Light;
  11645. }(BABYLON.Node));
  11646. BABYLON.Light = Light;
  11647. })(BABYLON || (BABYLON = {}));
  11648. //# sourceMappingURL=babylon.light.js.map
  11649. var BABYLON;
  11650. (function (BABYLON) {
  11651. var PointLight = (function (_super) {
  11652. __extends(PointLight, _super);
  11653. function PointLight(name, position, scene) {
  11654. _super.call(this, name, scene);
  11655. this.position = position;
  11656. }
  11657. PointLight.prototype.getClassName = function () {
  11658. return "PointLight";
  11659. };
  11660. PointLight.prototype.getAbsolutePosition = function () {
  11661. return this.transformedPosition ? this.transformedPosition : this.position;
  11662. };
  11663. PointLight.prototype.computeTransformedPosition = function () {
  11664. if (this.parent && this.parent.getWorldMatrix) {
  11665. if (!this.transformedPosition) {
  11666. this.transformedPosition = BABYLON.Vector3.Zero();
  11667. }
  11668. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11669. return true;
  11670. }
  11671. return false;
  11672. };
  11673. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11674. if (this.parent && this.parent.getWorldMatrix) {
  11675. this.computeTransformedPosition();
  11676. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11677. return;
  11678. }
  11679. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11680. };
  11681. PointLight.prototype.needCube = function () {
  11682. return true;
  11683. };
  11684. PointLight.prototype.supportsVSM = function () {
  11685. return false;
  11686. };
  11687. PointLight.prototype.needRefreshPerFrame = function () {
  11688. return false;
  11689. };
  11690. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11691. switch (faceIndex) {
  11692. case 0:
  11693. return new BABYLON.Vector3(1, 0, 0);
  11694. case 1:
  11695. return new BABYLON.Vector3(-1, 0, 0);
  11696. case 2:
  11697. return new BABYLON.Vector3(0, -1, 0);
  11698. case 3:
  11699. return new BABYLON.Vector3(0, 1, 0);
  11700. case 4:
  11701. return new BABYLON.Vector3(0, 0, 1);
  11702. case 5:
  11703. return new BABYLON.Vector3(0, 0, -1);
  11704. }
  11705. return BABYLON.Vector3.Zero();
  11706. };
  11707. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11708. var activeCamera = this.getScene().activeCamera;
  11709. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11710. };
  11711. PointLight.prototype._getWorldMatrix = function () {
  11712. if (!this._worldMatrix) {
  11713. this._worldMatrix = BABYLON.Matrix.Identity();
  11714. }
  11715. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11716. return this._worldMatrix;
  11717. };
  11718. PointLight.prototype.getTypeID = function () {
  11719. return 0;
  11720. };
  11721. __decorate([
  11722. BABYLON.serializeAsVector3()
  11723. ], PointLight.prototype, "position", void 0);
  11724. return PointLight;
  11725. }(BABYLON.Light));
  11726. BABYLON.PointLight = PointLight;
  11727. })(BABYLON || (BABYLON = {}));
  11728. //# sourceMappingURL=babylon.pointLight.js.map
  11729. var BABYLON;
  11730. (function (BABYLON) {
  11731. var SpotLight = (function (_super) {
  11732. __extends(SpotLight, _super);
  11733. function SpotLight(name, position, direction, angle, exponent, scene) {
  11734. _super.call(this, name, scene);
  11735. this.position = position;
  11736. this.direction = direction;
  11737. this.angle = angle;
  11738. this.exponent = exponent;
  11739. }
  11740. SpotLight.prototype.getClassName = function () {
  11741. return "SpotLight";
  11742. };
  11743. SpotLight.prototype.getAbsolutePosition = function () {
  11744. return this.transformedPosition ? this.transformedPosition : this.position;
  11745. };
  11746. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11747. var activeCamera = this.getScene().activeCamera;
  11748. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11749. };
  11750. SpotLight.prototype.needCube = function () {
  11751. return false;
  11752. };
  11753. SpotLight.prototype.supportsVSM = function () {
  11754. return true;
  11755. };
  11756. SpotLight.prototype.needRefreshPerFrame = function () {
  11757. return false;
  11758. };
  11759. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11760. return this.direction;
  11761. };
  11762. SpotLight.prototype.setDirectionToTarget = function (target) {
  11763. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11764. return this.direction;
  11765. };
  11766. SpotLight.prototype.computeTransformedPosition = function () {
  11767. if (this.parent && this.parent.getWorldMatrix) {
  11768. if (!this.transformedPosition) {
  11769. this.transformedPosition = BABYLON.Vector3.Zero();
  11770. }
  11771. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11772. return true;
  11773. }
  11774. return false;
  11775. };
  11776. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11777. var normalizeDirection;
  11778. if (this.parent && this.parent.getWorldMatrix) {
  11779. if (!this._transformedDirection) {
  11780. this._transformedDirection = BABYLON.Vector3.Zero();
  11781. }
  11782. this.computeTransformedPosition();
  11783. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11784. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11785. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11786. }
  11787. else {
  11788. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11789. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11790. }
  11791. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11792. };
  11793. SpotLight.prototype._getWorldMatrix = function () {
  11794. if (!this._worldMatrix) {
  11795. this._worldMatrix = BABYLON.Matrix.Identity();
  11796. }
  11797. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11798. return this._worldMatrix;
  11799. };
  11800. SpotLight.prototype.getTypeID = function () {
  11801. return 2;
  11802. };
  11803. SpotLight.prototype.getRotation = function () {
  11804. this.direction.normalize();
  11805. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  11806. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  11807. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  11808. };
  11809. __decorate([
  11810. BABYLON.serializeAsVector3()
  11811. ], SpotLight.prototype, "position", void 0);
  11812. __decorate([
  11813. BABYLON.serializeAsVector3()
  11814. ], SpotLight.prototype, "direction", void 0);
  11815. __decorate([
  11816. BABYLON.serialize()
  11817. ], SpotLight.prototype, "angle", void 0);
  11818. __decorate([
  11819. BABYLON.serialize()
  11820. ], SpotLight.prototype, "exponent", void 0);
  11821. return SpotLight;
  11822. }(BABYLON.Light));
  11823. BABYLON.SpotLight = SpotLight;
  11824. })(BABYLON || (BABYLON = {}));
  11825. //# sourceMappingURL=babylon.spotLight.js.map
  11826. var BABYLON;
  11827. (function (BABYLON) {
  11828. var HemisphericLight = (function (_super) {
  11829. __extends(HemisphericLight, _super);
  11830. function HemisphericLight(name, direction, scene) {
  11831. _super.call(this, name, scene);
  11832. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11833. this.direction = direction;
  11834. }
  11835. HemisphericLight.prototype.getClassName = function () {
  11836. return "HemisphericLight";
  11837. };
  11838. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11839. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11840. return this.direction;
  11841. };
  11842. HemisphericLight.prototype.getShadowGenerator = function () {
  11843. return null;
  11844. };
  11845. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11846. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11847. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11848. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11849. };
  11850. HemisphericLight.prototype._getWorldMatrix = function () {
  11851. if (!this._worldMatrix) {
  11852. this._worldMatrix = BABYLON.Matrix.Identity();
  11853. }
  11854. return this._worldMatrix;
  11855. };
  11856. HemisphericLight.prototype.getTypeID = function () {
  11857. return 3;
  11858. };
  11859. __decorate([
  11860. BABYLON.serializeAsColor3()
  11861. ], HemisphericLight.prototype, "groundColor", void 0);
  11862. __decorate([
  11863. BABYLON.serializeAsVector3()
  11864. ], HemisphericLight.prototype, "direction", void 0);
  11865. return HemisphericLight;
  11866. }(BABYLON.Light));
  11867. BABYLON.HemisphericLight = HemisphericLight;
  11868. })(BABYLON || (BABYLON = {}));
  11869. //# sourceMappingURL=babylon.hemisphericLight.js.map
  11870. var BABYLON;
  11871. (function (BABYLON) {
  11872. var DirectionalLight = (function (_super) {
  11873. __extends(DirectionalLight, _super);
  11874. function DirectionalLight(name, direction, scene) {
  11875. _super.call(this, name, scene);
  11876. this.shadowOrthoScale = 0.5;
  11877. this.autoUpdateExtends = true;
  11878. // Cache
  11879. this._orthoLeft = Number.MAX_VALUE;
  11880. this._orthoRight = Number.MIN_VALUE;
  11881. this._orthoTop = Number.MIN_VALUE;
  11882. this._orthoBottom = Number.MAX_VALUE;
  11883. this.position = direction.scale(-1);
  11884. this.direction = direction;
  11885. }
  11886. DirectionalLight.prototype.getClassName = function () {
  11887. return "DirectionalLight";
  11888. };
  11889. DirectionalLight.prototype.getAbsolutePosition = function () {
  11890. return this.transformedPosition ? this.transformedPosition : this.position;
  11891. };
  11892. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11893. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11894. return this.direction;
  11895. };
  11896. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11897. var activeCamera = this.getScene().activeCamera;
  11898. // Check extends
  11899. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11900. var tempVector3 = BABYLON.Vector3.Zero();
  11901. this._orthoLeft = Number.MAX_VALUE;
  11902. this._orthoRight = Number.MIN_VALUE;
  11903. this._orthoTop = Number.MIN_VALUE;
  11904. this._orthoBottom = Number.MAX_VALUE;
  11905. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11906. var mesh = renderList[meshIndex];
  11907. if (!mesh) {
  11908. continue;
  11909. }
  11910. var boundingInfo = mesh.getBoundingInfo();
  11911. if (!boundingInfo) {
  11912. continue;
  11913. }
  11914. var boundingBox = boundingInfo.boundingBox;
  11915. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11916. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11917. if (tempVector3.x < this._orthoLeft)
  11918. this._orthoLeft = tempVector3.x;
  11919. if (tempVector3.y < this._orthoBottom)
  11920. this._orthoBottom = tempVector3.y;
  11921. if (tempVector3.x > this._orthoRight)
  11922. this._orthoRight = tempVector3.x;
  11923. if (tempVector3.y > this._orthoTop)
  11924. this._orthoTop = tempVector3.y;
  11925. }
  11926. }
  11927. }
  11928. var xOffset = this._orthoRight - this._orthoLeft;
  11929. var yOffset = this._orthoTop - this._orthoBottom;
  11930. 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);
  11931. };
  11932. DirectionalLight.prototype.supportsVSM = function () {
  11933. return true;
  11934. };
  11935. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11936. return true;
  11937. };
  11938. DirectionalLight.prototype.needCube = function () {
  11939. return false;
  11940. };
  11941. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11942. return this.direction;
  11943. };
  11944. DirectionalLight.prototype.computeTransformedPosition = function () {
  11945. if (this.parent && this.parent.getWorldMatrix) {
  11946. if (!this.transformedPosition) {
  11947. this.transformedPosition = BABYLON.Vector3.Zero();
  11948. }
  11949. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11950. return true;
  11951. }
  11952. return false;
  11953. };
  11954. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11955. if (this.parent && this.parent.getWorldMatrix) {
  11956. if (!this._transformedDirection) {
  11957. this._transformedDirection = BABYLON.Vector3.Zero();
  11958. }
  11959. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11960. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11961. return;
  11962. }
  11963. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11964. };
  11965. DirectionalLight.prototype._getWorldMatrix = function () {
  11966. if (!this._worldMatrix) {
  11967. this._worldMatrix = BABYLON.Matrix.Identity();
  11968. }
  11969. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11970. return this._worldMatrix;
  11971. };
  11972. DirectionalLight.prototype.getTypeID = function () {
  11973. return 1;
  11974. };
  11975. __decorate([
  11976. BABYLON.serializeAsVector3()
  11977. ], DirectionalLight.prototype, "position", void 0);
  11978. __decorate([
  11979. BABYLON.serializeAsVector3()
  11980. ], DirectionalLight.prototype, "direction", void 0);
  11981. __decorate([
  11982. BABYLON.serialize()
  11983. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11984. __decorate([
  11985. BABYLON.serialize()
  11986. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11987. return DirectionalLight;
  11988. }(BABYLON.Light));
  11989. BABYLON.DirectionalLight = DirectionalLight;
  11990. })(BABYLON || (BABYLON = {}));
  11991. //# sourceMappingURL=babylon.directionalLight.js.map
  11992. var BABYLON;
  11993. (function (BABYLON) {
  11994. var ShadowGenerator = (function () {
  11995. function ShadowGenerator(mapSize, light) {
  11996. var _this = this;
  11997. // Members
  11998. this._filter = ShadowGenerator.FILTER_NONE;
  11999. this.blurScale = 2;
  12000. this._blurBoxOffset = 0;
  12001. this._bias = 0.00005;
  12002. this._lightDirection = BABYLON.Vector3.Zero();
  12003. this.forceBackFacesOnly = false;
  12004. this._darkness = 0;
  12005. this._transparencyShadow = false;
  12006. this._viewMatrix = BABYLON.Matrix.Zero();
  12007. this._projectionMatrix = BABYLON.Matrix.Zero();
  12008. this._transformMatrix = BABYLON.Matrix.Zero();
  12009. this._worldViewProjection = BABYLON.Matrix.Zero();
  12010. this._currentFaceIndex = 0;
  12011. this._currentFaceIndexCache = 0;
  12012. this._useFullFloat = true;
  12013. this._light = light;
  12014. this._scene = light.getScene();
  12015. this._mapSize = mapSize;
  12016. light._shadowGenerator = this;
  12017. // Texture type fallback from float to int if not supported.
  12018. var textureType;
  12019. var caps = this._scene.getEngine().getCaps();
  12020. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12021. this._useFullFloat = true;
  12022. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12023. }
  12024. else {
  12025. this._useFullFloat = false;
  12026. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12027. }
  12028. // Render target
  12029. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12030. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12031. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12032. this._shadowMap.anisotropicFilteringLevel = 1;
  12033. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12034. this._shadowMap.renderParticles = false;
  12035. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12036. _this._currentFaceIndex = faceIndex;
  12037. });
  12038. this._shadowMap.onAfterUnbindObservable.add(function () {
  12039. if (!_this.useBlurVarianceShadowMap) {
  12040. return;
  12041. }
  12042. if (!_this._shadowMap2) {
  12043. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12044. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12045. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12046. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12047. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12048. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12049. effect.setTexture("textureSampler", _this._shadowMap);
  12050. });
  12051. _this.blurBoxOffset = 1;
  12052. }
  12053. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12054. });
  12055. // Custom render function
  12056. var renderSubMesh = function (subMesh) {
  12057. var mesh = subMesh.getRenderingMesh();
  12058. var scene = _this._scene;
  12059. var engine = scene.getEngine();
  12060. // Culling
  12061. engine.setState(subMesh.getMaterial().backFaceCulling);
  12062. // Managing instances
  12063. var batch = mesh._getInstancesRenderList(subMesh._id);
  12064. if (batch.mustReturn) {
  12065. return;
  12066. }
  12067. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12068. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12069. engine.enableEffect(_this._effect);
  12070. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12071. var material = subMesh.getMaterial();
  12072. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12073. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12074. if (_this.getLight().needCube()) {
  12075. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12076. }
  12077. // Alpha test
  12078. if (material && material.needAlphaTesting()) {
  12079. var alphaTexture = material.getAlphaTestTexture();
  12080. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12081. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12082. }
  12083. // Bones
  12084. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12085. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12086. }
  12087. if (_this.forceBackFacesOnly) {
  12088. engine.setState(true, 0, false, true);
  12089. }
  12090. // Draw
  12091. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12092. if (_this.forceBackFacesOnly) {
  12093. engine.setState(true, 0, false, false);
  12094. }
  12095. }
  12096. else {
  12097. // Need to reset refresh rate of the shadowMap
  12098. _this._shadowMap.resetRefreshCounter();
  12099. }
  12100. };
  12101. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12102. var index;
  12103. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12104. renderSubMesh(opaqueSubMeshes.data[index]);
  12105. }
  12106. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12107. renderSubMesh(alphaTestSubMeshes.data[index]);
  12108. }
  12109. if (_this._transparencyShadow) {
  12110. for (index = 0; index < transparentSubMeshes.length; index++) {
  12111. renderSubMesh(transparentSubMeshes.data[index]);
  12112. }
  12113. }
  12114. };
  12115. this._shadowMap.onClearObservable.add(function (engine) {
  12116. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12117. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12118. }
  12119. else {
  12120. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12121. }
  12122. });
  12123. }
  12124. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12125. // Static
  12126. get: function () {
  12127. return ShadowGenerator._FILTER_NONE;
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12133. get: function () {
  12134. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12135. },
  12136. enumerable: true,
  12137. configurable: true
  12138. });
  12139. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12140. get: function () {
  12141. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12147. get: function () {
  12148. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12149. },
  12150. enumerable: true,
  12151. configurable: true
  12152. });
  12153. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12154. get: function () {
  12155. return this._bias;
  12156. },
  12157. set: function (bias) {
  12158. this._bias = bias;
  12159. },
  12160. enumerable: true,
  12161. configurable: true
  12162. });
  12163. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12164. get: function () {
  12165. return this._blurBoxOffset;
  12166. },
  12167. set: function (value) {
  12168. var _this = this;
  12169. if (this._blurBoxOffset === value) {
  12170. return;
  12171. }
  12172. this._blurBoxOffset = value;
  12173. if (this._boxBlurPostprocess) {
  12174. this._boxBlurPostprocess.dispose();
  12175. }
  12176. 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);
  12177. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12178. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12179. });
  12180. },
  12181. enumerable: true,
  12182. configurable: true
  12183. });
  12184. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12185. get: function () {
  12186. return this._filter;
  12187. },
  12188. set: function (value) {
  12189. if (this._filter === value) {
  12190. return;
  12191. }
  12192. this._filter = value;
  12193. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12194. this._shadowMap.anisotropicFilteringLevel = 16;
  12195. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12196. }
  12197. else {
  12198. this._shadowMap.anisotropicFilteringLevel = 1;
  12199. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12200. }
  12201. },
  12202. enumerable: true,
  12203. configurable: true
  12204. });
  12205. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12206. get: function () {
  12207. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12208. },
  12209. set: function (value) {
  12210. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12211. },
  12212. enumerable: true,
  12213. configurable: true
  12214. });
  12215. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12216. get: function () {
  12217. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12218. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12219. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12220. },
  12221. set: function (value) {
  12222. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12223. },
  12224. enumerable: true,
  12225. configurable: true
  12226. });
  12227. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12228. get: function () {
  12229. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12230. },
  12231. set: function (value) {
  12232. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12233. },
  12234. enumerable: true,
  12235. configurable: true
  12236. });
  12237. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12238. var defines = [];
  12239. if (this._useFullFloat) {
  12240. defines.push("#define FULLFLOAT");
  12241. }
  12242. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12243. defines.push("#define VSM");
  12244. }
  12245. if (this.getLight().needCube()) {
  12246. defines.push("#define CUBEMAP");
  12247. }
  12248. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12249. var mesh = subMesh.getMesh();
  12250. var material = subMesh.getMaterial();
  12251. // Alpha test
  12252. if (material && material.needAlphaTesting()) {
  12253. defines.push("#define ALPHATEST");
  12254. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12255. attribs.push(BABYLON.VertexBuffer.UVKind);
  12256. defines.push("#define UV1");
  12257. }
  12258. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12259. var alphaTexture = material.getAlphaTestTexture();
  12260. if (alphaTexture.coordinatesIndex === 1) {
  12261. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12262. defines.push("#define UV2");
  12263. }
  12264. }
  12265. }
  12266. // Bones
  12267. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12268. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12269. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12270. if (mesh.numBoneInfluencers > 4) {
  12271. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12272. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12273. }
  12274. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12275. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12276. }
  12277. else {
  12278. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12279. }
  12280. // Instances
  12281. if (useInstances) {
  12282. defines.push("#define INSTANCES");
  12283. attribs.push("world0");
  12284. attribs.push("world1");
  12285. attribs.push("world2");
  12286. attribs.push("world3");
  12287. }
  12288. // Get correct effect
  12289. var join = defines.join("\n");
  12290. if (this._cachedDefines !== join) {
  12291. this._cachedDefines = join;
  12292. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12293. }
  12294. return this._effect.isReady();
  12295. };
  12296. ShadowGenerator.prototype.getShadowMap = function () {
  12297. return this._shadowMap;
  12298. };
  12299. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12300. if (this._shadowMap2) {
  12301. return this._shadowMap2;
  12302. }
  12303. return this._shadowMap;
  12304. };
  12305. ShadowGenerator.prototype.getLight = function () {
  12306. return this._light;
  12307. };
  12308. // Methods
  12309. ShadowGenerator.prototype.getTransformMatrix = function () {
  12310. var scene = this._scene;
  12311. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12312. return this._transformMatrix;
  12313. }
  12314. this._currentRenderID = scene.getRenderId();
  12315. this._currentFaceIndexCache = this._currentFaceIndex;
  12316. var lightPosition = this._light.position;
  12317. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12318. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12319. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12320. }
  12321. if (this._light.computeTransformedPosition()) {
  12322. lightPosition = this._light.transformedPosition;
  12323. }
  12324. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12325. this._cachedPosition = lightPosition.clone();
  12326. this._cachedDirection = this._lightDirection.clone();
  12327. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12328. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12329. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12330. }
  12331. return this._transformMatrix;
  12332. };
  12333. ShadowGenerator.prototype.getDarkness = function () {
  12334. return this._darkness;
  12335. };
  12336. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12337. if (darkness >= 1.0)
  12338. this._darkness = 1.0;
  12339. else if (darkness <= 0.0)
  12340. this._darkness = 0.0;
  12341. else
  12342. this._darkness = darkness;
  12343. };
  12344. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12345. this._transparencyShadow = hasShadow;
  12346. };
  12347. ShadowGenerator.prototype._packHalf = function (depth) {
  12348. var scale = depth * 255.0;
  12349. var fract = scale - Math.floor(scale);
  12350. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12351. };
  12352. ShadowGenerator.prototype.dispose = function () {
  12353. this._shadowMap.dispose();
  12354. if (this._shadowMap2) {
  12355. this._shadowMap2.dispose();
  12356. }
  12357. if (this._downSamplePostprocess) {
  12358. this._downSamplePostprocess.dispose();
  12359. }
  12360. if (this._boxBlurPostprocess) {
  12361. this._boxBlurPostprocess.dispose();
  12362. }
  12363. };
  12364. ShadowGenerator.prototype.serialize = function () {
  12365. var serializationObject = {};
  12366. serializationObject.lightId = this._light.id;
  12367. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12368. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12369. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12370. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12371. serializationObject.renderList = [];
  12372. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12373. var mesh = this.getShadowMap().renderList[meshIndex];
  12374. serializationObject.renderList.push(mesh.id);
  12375. }
  12376. return serializationObject;
  12377. };
  12378. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12379. //casting to point light, as light is missing the position attr and typescript complains.
  12380. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12381. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12382. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12383. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12384. meshes.forEach(function (mesh) {
  12385. shadowGenerator.getShadowMap().renderList.push(mesh);
  12386. });
  12387. }
  12388. if (parsedShadowGenerator.usePoissonSampling) {
  12389. shadowGenerator.usePoissonSampling = true;
  12390. }
  12391. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12392. shadowGenerator.useVarianceShadowMap = true;
  12393. }
  12394. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12395. shadowGenerator.useBlurVarianceShadowMap = true;
  12396. if (parsedShadowGenerator.blurScale) {
  12397. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12398. }
  12399. if (parsedShadowGenerator.blurBoxOffset) {
  12400. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12401. }
  12402. }
  12403. if (parsedShadowGenerator.bias !== undefined) {
  12404. shadowGenerator.bias = parsedShadowGenerator.bias;
  12405. }
  12406. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12407. return shadowGenerator;
  12408. };
  12409. ShadowGenerator._FILTER_NONE = 0;
  12410. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12411. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12412. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12413. return ShadowGenerator;
  12414. }());
  12415. BABYLON.ShadowGenerator = ShadowGenerator;
  12416. })(BABYLON || (BABYLON = {}));
  12417. //# sourceMappingURL=babylon.shadowGenerator.js.map
  12418. var BABYLON;
  12419. (function (BABYLON) {
  12420. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12421. if (boxMin.x > sphereCenter.x + sphereRadius)
  12422. return false;
  12423. if (sphereCenter.x - sphereRadius > boxMax.x)
  12424. return false;
  12425. if (boxMin.y > sphereCenter.y + sphereRadius)
  12426. return false;
  12427. if (sphereCenter.y - sphereRadius > boxMax.y)
  12428. return false;
  12429. if (boxMin.z > sphereCenter.z + sphereRadius)
  12430. return false;
  12431. if (sphereCenter.z - sphereRadius > boxMax.z)
  12432. return false;
  12433. return true;
  12434. };
  12435. var getLowestRoot = (function () {
  12436. var result = { root: 0, found: false };
  12437. return function (a, b, c, maxR) {
  12438. result.root = 0;
  12439. result.found = false;
  12440. var determinant = b * b - 4.0 * a * c;
  12441. if (determinant < 0)
  12442. return result;
  12443. var sqrtD = Math.sqrt(determinant);
  12444. var r1 = (-b - sqrtD) / (2.0 * a);
  12445. var r2 = (-b + sqrtD) / (2.0 * a);
  12446. if (r1 > r2) {
  12447. var temp = r2;
  12448. r2 = r1;
  12449. r1 = temp;
  12450. }
  12451. if (r1 > 0 && r1 < maxR) {
  12452. result.root = r1;
  12453. result.found = true;
  12454. return result;
  12455. }
  12456. if (r2 > 0 && r2 < maxR) {
  12457. result.root = r2;
  12458. result.found = true;
  12459. return result;
  12460. }
  12461. return result;
  12462. };
  12463. })();
  12464. var Collider = (function () {
  12465. function Collider() {
  12466. this.radius = new BABYLON.Vector3(1, 1, 1);
  12467. this.retry = 0;
  12468. this.basePointWorld = BABYLON.Vector3.Zero();
  12469. this.velocityWorld = BABYLON.Vector3.Zero();
  12470. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12471. this._collisionPoint = BABYLON.Vector3.Zero();
  12472. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12473. this._tempVector = BABYLON.Vector3.Zero();
  12474. this._tempVector2 = BABYLON.Vector3.Zero();
  12475. this._tempVector3 = BABYLON.Vector3.Zero();
  12476. this._tempVector4 = BABYLON.Vector3.Zero();
  12477. this._edge = BABYLON.Vector3.Zero();
  12478. this._baseToVertex = BABYLON.Vector3.Zero();
  12479. this._destinationPoint = BABYLON.Vector3.Zero();
  12480. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12481. this._displacementVector = BABYLON.Vector3.Zero();
  12482. }
  12483. // Methods
  12484. Collider.prototype._initialize = function (source, dir, e) {
  12485. this.velocity = dir;
  12486. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12487. this.basePoint = source;
  12488. source.multiplyToRef(this.radius, this.basePointWorld);
  12489. dir.multiplyToRef(this.radius, this.velocityWorld);
  12490. this.velocityWorldLength = this.velocityWorld.length();
  12491. this.epsilon = e;
  12492. this.collisionFound = false;
  12493. };
  12494. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12495. pa.subtractToRef(point, this._tempVector);
  12496. pb.subtractToRef(point, this._tempVector2);
  12497. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12498. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12499. if (d < 0)
  12500. return false;
  12501. pc.subtractToRef(point, this._tempVector3);
  12502. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12503. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12504. if (d < 0)
  12505. return false;
  12506. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12507. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12508. return d >= 0;
  12509. };
  12510. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12511. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12512. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12513. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12514. return false;
  12515. }
  12516. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12517. return false;
  12518. return true;
  12519. };
  12520. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12521. var t0;
  12522. var embeddedInPlane = false;
  12523. //defensive programming, actually not needed.
  12524. if (!trianglePlaneArray) {
  12525. trianglePlaneArray = [];
  12526. }
  12527. if (!trianglePlaneArray[faceIndex]) {
  12528. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12529. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12530. }
  12531. var trianglePlane = trianglePlaneArray[faceIndex];
  12532. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12533. return;
  12534. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12535. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12536. if (normalDotVelocity == 0) {
  12537. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12538. return;
  12539. embeddedInPlane = true;
  12540. t0 = 0;
  12541. }
  12542. else {
  12543. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12544. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12545. if (t0 > t1) {
  12546. var temp = t1;
  12547. t1 = t0;
  12548. t0 = temp;
  12549. }
  12550. if (t0 > 1.0 || t1 < 0.0)
  12551. return;
  12552. if (t0 < 0)
  12553. t0 = 0;
  12554. if (t0 > 1.0)
  12555. t0 = 1.0;
  12556. }
  12557. this._collisionPoint.copyFromFloats(0, 0, 0);
  12558. var found = false;
  12559. var t = 1.0;
  12560. if (!embeddedInPlane) {
  12561. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12562. this.velocity.scaleToRef(t0, this._tempVector);
  12563. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12564. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12565. found = true;
  12566. t = t0;
  12567. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12568. }
  12569. }
  12570. if (!found) {
  12571. var velocitySquaredLength = this.velocity.lengthSquared();
  12572. var a = velocitySquaredLength;
  12573. this.basePoint.subtractToRef(p1, this._tempVector);
  12574. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12575. var c = this._tempVector.lengthSquared() - 1.0;
  12576. var lowestRoot = getLowestRoot(a, b, c, t);
  12577. if (lowestRoot.found) {
  12578. t = lowestRoot.root;
  12579. found = true;
  12580. this._collisionPoint.copyFrom(p1);
  12581. }
  12582. this.basePoint.subtractToRef(p2, this._tempVector);
  12583. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12584. c = this._tempVector.lengthSquared() - 1.0;
  12585. lowestRoot = getLowestRoot(a, b, c, t);
  12586. if (lowestRoot.found) {
  12587. t = lowestRoot.root;
  12588. found = true;
  12589. this._collisionPoint.copyFrom(p2);
  12590. }
  12591. this.basePoint.subtractToRef(p3, this._tempVector);
  12592. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12593. c = this._tempVector.lengthSquared() - 1.0;
  12594. lowestRoot = getLowestRoot(a, b, c, t);
  12595. if (lowestRoot.found) {
  12596. t = lowestRoot.root;
  12597. found = true;
  12598. this._collisionPoint.copyFrom(p3);
  12599. }
  12600. p2.subtractToRef(p1, this._edge);
  12601. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12602. var edgeSquaredLength = this._edge.lengthSquared();
  12603. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12604. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12605. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12606. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12607. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12608. lowestRoot = getLowestRoot(a, b, c, t);
  12609. if (lowestRoot.found) {
  12610. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12611. if (f >= 0.0 && f <= 1.0) {
  12612. t = lowestRoot.root;
  12613. found = true;
  12614. this._edge.scaleInPlace(f);
  12615. p1.addToRef(this._edge, this._collisionPoint);
  12616. }
  12617. }
  12618. p3.subtractToRef(p2, this._edge);
  12619. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12620. edgeSquaredLength = this._edge.lengthSquared();
  12621. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12622. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12623. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12624. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12625. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12626. lowestRoot = getLowestRoot(a, b, c, t);
  12627. if (lowestRoot.found) {
  12628. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12629. if (f >= 0.0 && f <= 1.0) {
  12630. t = lowestRoot.root;
  12631. found = true;
  12632. this._edge.scaleInPlace(f);
  12633. p2.addToRef(this._edge, this._collisionPoint);
  12634. }
  12635. }
  12636. p1.subtractToRef(p3, this._edge);
  12637. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12638. edgeSquaredLength = this._edge.lengthSquared();
  12639. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12640. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12641. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12642. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12643. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12644. lowestRoot = getLowestRoot(a, b, c, t);
  12645. if (lowestRoot.found) {
  12646. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12647. if (f >= 0.0 && f <= 1.0) {
  12648. t = lowestRoot.root;
  12649. found = true;
  12650. this._edge.scaleInPlace(f);
  12651. p3.addToRef(this._edge, this._collisionPoint);
  12652. }
  12653. }
  12654. }
  12655. if (found) {
  12656. var distToCollision = t * this.velocity.length();
  12657. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12658. if (!this.intersectionPoint) {
  12659. this.intersectionPoint = this._collisionPoint.clone();
  12660. }
  12661. else {
  12662. this.intersectionPoint.copyFrom(this._collisionPoint);
  12663. }
  12664. this.nearestDistance = distToCollision;
  12665. this.collisionFound = true;
  12666. }
  12667. }
  12668. };
  12669. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12670. for (var i = indexStart; i < indexEnd; i += 3) {
  12671. var p1 = pts[indices[i] - decal];
  12672. var p2 = pts[indices[i + 1] - decal];
  12673. var p3 = pts[indices[i + 2] - decal];
  12674. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12675. }
  12676. };
  12677. Collider.prototype._getResponse = function (pos, vel) {
  12678. pos.addToRef(vel, this._destinationPoint);
  12679. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12680. this.basePoint.addToRef(vel, pos);
  12681. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12682. this._slidePlaneNormal.normalize();
  12683. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12684. pos.addInPlace(this._displacementVector);
  12685. this.intersectionPoint.addInPlace(this._displacementVector);
  12686. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12687. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12688. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12689. };
  12690. return Collider;
  12691. }());
  12692. BABYLON.Collider = Collider;
  12693. })(BABYLON || (BABYLON = {}));
  12694. //# sourceMappingURL=babylon.collider.js.map
  12695. var BABYLON;
  12696. (function (BABYLON) {
  12697. //WebWorker code will be inserted to this variable.
  12698. BABYLON.CollisionWorker = "";
  12699. (function (WorkerTaskType) {
  12700. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12701. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12702. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12703. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12704. var WorkerTaskType = BABYLON.WorkerTaskType;
  12705. (function (WorkerReplyType) {
  12706. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12707. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12708. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12709. var WorkerReplyType = BABYLON.WorkerReplyType;
  12710. var CollisionCoordinatorWorker = (function () {
  12711. function CollisionCoordinatorWorker() {
  12712. var _this = this;
  12713. this._scaledPosition = BABYLON.Vector3.Zero();
  12714. this._scaledVelocity = BABYLON.Vector3.Zero();
  12715. this.onMeshUpdated = function (mesh) {
  12716. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12717. };
  12718. this.onGeometryUpdated = function (geometry) {
  12719. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12720. };
  12721. this._afterRender = function () {
  12722. if (!_this._init)
  12723. return;
  12724. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12725. return;
  12726. }
  12727. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12728. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12729. if (_this._runningUpdated > 4) {
  12730. return;
  12731. }
  12732. ++_this._runningUpdated;
  12733. var payload = {
  12734. updatedMeshes: _this._addUpdateMeshesList,
  12735. updatedGeometries: _this._addUpdateGeometriesList,
  12736. removedGeometries: _this._toRemoveGeometryArray,
  12737. removedMeshes: _this._toRemoveMeshesArray
  12738. };
  12739. var message = {
  12740. payload: payload,
  12741. taskType: WorkerTaskType.UPDATE
  12742. };
  12743. var serializable = [];
  12744. for (var id in payload.updatedGeometries) {
  12745. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12746. //prepare transferables
  12747. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12748. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12749. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12750. }
  12751. }
  12752. _this._worker.postMessage(message, serializable);
  12753. _this._addUpdateMeshesList = {};
  12754. _this._addUpdateGeometriesList = {};
  12755. _this._toRemoveGeometryArray = [];
  12756. _this._toRemoveMeshesArray = [];
  12757. };
  12758. this._onMessageFromWorker = function (e) {
  12759. var returnData = e.data;
  12760. if (returnData.error != WorkerReplyType.SUCCESS) {
  12761. //TODO what errors can be returned from the worker?
  12762. BABYLON.Tools.Warn("error returned from worker!");
  12763. return;
  12764. }
  12765. switch (returnData.taskType) {
  12766. case WorkerTaskType.INIT:
  12767. _this._init = true;
  12768. //Update the worked with ALL of the scene's current state
  12769. _this._scene.meshes.forEach(function (mesh) {
  12770. _this.onMeshAdded(mesh);
  12771. });
  12772. _this._scene.getGeometries().forEach(function (geometry) {
  12773. _this.onGeometryAdded(geometry);
  12774. });
  12775. break;
  12776. case WorkerTaskType.UPDATE:
  12777. _this._runningUpdated--;
  12778. break;
  12779. case WorkerTaskType.COLLIDE:
  12780. _this._runningCollisionTask = false;
  12781. var returnPayload = returnData.payload;
  12782. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12783. return;
  12784. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12785. //cleanup
  12786. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12787. break;
  12788. }
  12789. };
  12790. this._collisionsCallbackArray = [];
  12791. this._init = false;
  12792. this._runningUpdated = 0;
  12793. this._runningCollisionTask = false;
  12794. this._addUpdateMeshesList = {};
  12795. this._addUpdateGeometriesList = {};
  12796. this._toRemoveGeometryArray = [];
  12797. this._toRemoveMeshesArray = [];
  12798. }
  12799. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12800. if (!this._init)
  12801. return;
  12802. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12803. return;
  12804. position.divideToRef(collider.radius, this._scaledPosition);
  12805. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12806. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12807. var payload = {
  12808. collider: {
  12809. position: this._scaledPosition.asArray(),
  12810. velocity: this._scaledVelocity.asArray(),
  12811. radius: collider.radius.asArray()
  12812. },
  12813. collisionId: collisionIndex,
  12814. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12815. maximumRetry: maximumRetry
  12816. };
  12817. var message = {
  12818. payload: payload,
  12819. taskType: WorkerTaskType.COLLIDE
  12820. };
  12821. this._worker.postMessage(message);
  12822. };
  12823. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12824. this._scene = scene;
  12825. this._scene.registerAfterRender(this._afterRender);
  12826. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12827. this._worker = new Worker(workerUrl);
  12828. this._worker.onmessage = this._onMessageFromWorker;
  12829. var message = {
  12830. payload: {},
  12831. taskType: WorkerTaskType.INIT
  12832. };
  12833. this._worker.postMessage(message);
  12834. };
  12835. CollisionCoordinatorWorker.prototype.destroy = function () {
  12836. this._scene.unregisterAfterRender(this._afterRender);
  12837. this._worker.terminate();
  12838. };
  12839. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12840. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12841. this.onMeshUpdated(mesh);
  12842. };
  12843. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12844. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12845. };
  12846. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12847. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12848. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12849. this.onGeometryUpdated(geometry);
  12850. };
  12851. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12852. this._toRemoveGeometryArray.push(geometry.id);
  12853. };
  12854. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12855. var submeshes = [];
  12856. if (mesh.subMeshes) {
  12857. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12858. return {
  12859. position: idx,
  12860. verticesStart: sm.verticesStart,
  12861. verticesCount: sm.verticesCount,
  12862. indexStart: sm.indexStart,
  12863. indexCount: sm.indexCount,
  12864. hasMaterial: !!sm.getMaterial(),
  12865. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12866. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12867. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12868. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12869. };
  12870. });
  12871. }
  12872. var geometryId = null;
  12873. if (mesh instanceof BABYLON.Mesh) {
  12874. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12875. }
  12876. else if (mesh instanceof BABYLON.InstancedMesh) {
  12877. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12878. }
  12879. return {
  12880. uniqueId: mesh.uniqueId,
  12881. id: mesh.id,
  12882. name: mesh.name,
  12883. geometryId: geometryId,
  12884. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12885. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12886. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12887. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12888. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12889. subMeshes: submeshes,
  12890. checkCollisions: mesh.checkCollisions
  12891. };
  12892. };
  12893. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12894. return {
  12895. id: geometry.id,
  12896. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12897. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12898. indices: new Int32Array(geometry.getIndices() || []),
  12899. };
  12900. };
  12901. return CollisionCoordinatorWorker;
  12902. }());
  12903. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12904. var CollisionCoordinatorLegacy = (function () {
  12905. function CollisionCoordinatorLegacy() {
  12906. this._scaledPosition = BABYLON.Vector3.Zero();
  12907. this._scaledVelocity = BABYLON.Vector3.Zero();
  12908. this._finalPosition = BABYLON.Vector3.Zero();
  12909. }
  12910. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12911. position.divideToRef(collider.radius, this._scaledPosition);
  12912. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12913. collider.collidedMesh = null;
  12914. collider.retry = 0;
  12915. collider.initialVelocity = this._scaledVelocity;
  12916. collider.initialPosition = this._scaledPosition;
  12917. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12918. this._finalPosition.multiplyInPlace(collider.radius);
  12919. //run the callback
  12920. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12921. };
  12922. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12923. this._scene = scene;
  12924. };
  12925. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12926. //Legacy need no destruction method.
  12927. };
  12928. //No update in legacy mode
  12929. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12930. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12931. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12932. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12933. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12934. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12935. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12936. if (excludedMesh === void 0) { excludedMesh = null; }
  12937. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12938. if (collider.retry >= maximumRetry) {
  12939. finalPosition.copyFrom(position);
  12940. return;
  12941. }
  12942. collider._initialize(position, velocity, closeDistance);
  12943. // Check all meshes
  12944. for (var index = 0; index < this._scene.meshes.length; index++) {
  12945. var mesh = this._scene.meshes[index];
  12946. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12947. mesh._checkCollision(collider);
  12948. }
  12949. }
  12950. if (!collider.collisionFound) {
  12951. position.addToRef(velocity, finalPosition);
  12952. return;
  12953. }
  12954. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12955. collider._getResponse(position, velocity);
  12956. }
  12957. if (velocity.length() <= closeDistance) {
  12958. finalPosition.copyFrom(position);
  12959. return;
  12960. }
  12961. collider.retry++;
  12962. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12963. };
  12964. return CollisionCoordinatorLegacy;
  12965. }());
  12966. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12967. })(BABYLON || (BABYLON = {}));
  12968. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  12969. var BABYLON;
  12970. (function (BABYLON) {
  12971. var Camera = (function (_super) {
  12972. __extends(Camera, _super);
  12973. function Camera(name, position, scene) {
  12974. _super.call(this, name, scene);
  12975. this.upVector = BABYLON.Vector3.Up();
  12976. this.orthoLeft = null;
  12977. this.orthoRight = null;
  12978. this.orthoBottom = null;
  12979. this.orthoTop = null;
  12980. this.fov = 0.8;
  12981. this.minZ = 1.0;
  12982. this.maxZ = 10000.0;
  12983. this.inertia = 0.9;
  12984. this.mode = Camera.PERSPECTIVE_CAMERA;
  12985. this.isIntermediate = false;
  12986. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12987. this.layerMask = 0x0FFFFFFF;
  12988. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12989. // Camera rig members
  12990. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12991. this._rigCameras = new Array();
  12992. // Cache
  12993. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12994. this._projectionMatrix = new BABYLON.Matrix();
  12995. this._doNotComputeProjectionMatrix = false;
  12996. this._postProcesses = new Array();
  12997. this._transformMatrix = BABYLON.Matrix.Zero();
  12998. this._webvrViewMatrix = BABYLON.Matrix.Identity();
  12999. this._activeMeshes = new BABYLON.SmartArray(256);
  13000. this._globalPosition = BABYLON.Vector3.Zero();
  13001. this._refreshFrustumPlanes = true;
  13002. scene.addCamera(this);
  13003. if (!scene.activeCamera) {
  13004. scene.activeCamera = this;
  13005. }
  13006. this.position = position;
  13007. }
  13008. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13009. get: function () {
  13010. return Camera._PERSPECTIVE_CAMERA;
  13011. },
  13012. enumerable: true,
  13013. configurable: true
  13014. });
  13015. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13016. get: function () {
  13017. return Camera._ORTHOGRAPHIC_CAMERA;
  13018. },
  13019. enumerable: true,
  13020. configurable: true
  13021. });
  13022. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13023. get: function () {
  13024. return Camera._FOVMODE_VERTICAL_FIXED;
  13025. },
  13026. enumerable: true,
  13027. configurable: true
  13028. });
  13029. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13030. get: function () {
  13031. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13032. },
  13033. enumerable: true,
  13034. configurable: true
  13035. });
  13036. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13037. get: function () {
  13038. return Camera._RIG_MODE_NONE;
  13039. },
  13040. enumerable: true,
  13041. configurable: true
  13042. });
  13043. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13044. get: function () {
  13045. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13046. },
  13047. enumerable: true,
  13048. configurable: true
  13049. });
  13050. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13051. get: function () {
  13052. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13053. },
  13054. enumerable: true,
  13055. configurable: true
  13056. });
  13057. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13058. get: function () {
  13059. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13060. },
  13061. enumerable: true,
  13062. configurable: true
  13063. });
  13064. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13065. get: function () {
  13066. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13067. },
  13068. enumerable: true,
  13069. configurable: true
  13070. });
  13071. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13072. get: function () {
  13073. return Camera._RIG_MODE_VR;
  13074. },
  13075. enumerable: true,
  13076. configurable: true
  13077. });
  13078. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13079. get: function () {
  13080. return Camera._RIG_MODE_WEBVR;
  13081. },
  13082. enumerable: true,
  13083. configurable: true
  13084. });
  13085. Camera.prototype.getClassName = function () {
  13086. return "Camera";
  13087. };
  13088. /**
  13089. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13090. */
  13091. Camera.prototype.toString = function (fullDetails) {
  13092. var ret = "Name: " + this.name;
  13093. ret += ", type: " + this.getClassName();
  13094. if (this.animations) {
  13095. for (var i = 0; i < this.animations.length; i++) {
  13096. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13097. }
  13098. }
  13099. if (fullDetails) {
  13100. }
  13101. return ret;
  13102. };
  13103. Object.defineProperty(Camera.prototype, "globalPosition", {
  13104. get: function () {
  13105. return this._globalPosition;
  13106. },
  13107. enumerable: true,
  13108. configurable: true
  13109. });
  13110. Camera.prototype.getActiveMeshes = function () {
  13111. return this._activeMeshes;
  13112. };
  13113. Camera.prototype.isActiveMesh = function (mesh) {
  13114. return (this._activeMeshes.indexOf(mesh) !== -1);
  13115. };
  13116. //Cache
  13117. Camera.prototype._initCache = function () {
  13118. _super.prototype._initCache.call(this);
  13119. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13120. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13121. this._cache.mode = undefined;
  13122. this._cache.minZ = undefined;
  13123. this._cache.maxZ = undefined;
  13124. this._cache.fov = undefined;
  13125. this._cache.fovMode = undefined;
  13126. this._cache.aspectRatio = undefined;
  13127. this._cache.orthoLeft = undefined;
  13128. this._cache.orthoRight = undefined;
  13129. this._cache.orthoBottom = undefined;
  13130. this._cache.orthoTop = undefined;
  13131. this._cache.renderWidth = undefined;
  13132. this._cache.renderHeight = undefined;
  13133. };
  13134. Camera.prototype._updateCache = function (ignoreParentClass) {
  13135. if (!ignoreParentClass) {
  13136. _super.prototype._updateCache.call(this);
  13137. }
  13138. var engine = this.getEngine();
  13139. this._cache.position.copyFrom(this.position);
  13140. this._cache.upVector.copyFrom(this.upVector);
  13141. this._cache.mode = this.mode;
  13142. this._cache.minZ = this.minZ;
  13143. this._cache.maxZ = this.maxZ;
  13144. this._cache.fov = this.fov;
  13145. this._cache.fovMode = this.fovMode;
  13146. this._cache.aspectRatio = engine.getAspectRatio(this);
  13147. this._cache.orthoLeft = this.orthoLeft;
  13148. this._cache.orthoRight = this.orthoRight;
  13149. this._cache.orthoBottom = this.orthoBottom;
  13150. this._cache.orthoTop = this.orthoTop;
  13151. this._cache.renderWidth = engine.getRenderWidth();
  13152. this._cache.renderHeight = engine.getRenderHeight();
  13153. };
  13154. Camera.prototype._updateFromScene = function () {
  13155. this.updateCache();
  13156. this.update();
  13157. };
  13158. // Synchronized
  13159. Camera.prototype._isSynchronized = function () {
  13160. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13161. };
  13162. Camera.prototype._isSynchronizedViewMatrix = function () {
  13163. if (!_super.prototype._isSynchronized.call(this))
  13164. return false;
  13165. return this._cache.position.equals(this.position)
  13166. && this._cache.upVector.equals(this.upVector)
  13167. && this.isSynchronizedWithParent();
  13168. };
  13169. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13170. var check = this._cache.mode === this.mode
  13171. && this._cache.minZ === this.minZ
  13172. && this._cache.maxZ === this.maxZ;
  13173. if (!check) {
  13174. return false;
  13175. }
  13176. var engine = this.getEngine();
  13177. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13178. check = this._cache.fov === this.fov
  13179. && this._cache.fovMode === this.fovMode
  13180. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13181. }
  13182. else {
  13183. check = this._cache.orthoLeft === this.orthoLeft
  13184. && this._cache.orthoRight === this.orthoRight
  13185. && this._cache.orthoBottom === this.orthoBottom
  13186. && this._cache.orthoTop === this.orthoTop
  13187. && this._cache.renderWidth === engine.getRenderWidth()
  13188. && this._cache.renderHeight === engine.getRenderHeight();
  13189. }
  13190. return check;
  13191. };
  13192. // Controls
  13193. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13194. };
  13195. Camera.prototype.detachControl = function (element) {
  13196. };
  13197. Camera.prototype.update = function () {
  13198. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13199. this._updateRigCameras();
  13200. }
  13201. this._checkInputs();
  13202. };
  13203. Camera.prototype._checkInputs = function () {
  13204. };
  13205. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13206. // invalidate framebuffer
  13207. if (this._postProcesses.length > 0) {
  13208. this._postProcesses[0].markTextureDirty();
  13209. }
  13210. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13211. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13212. var cam = this._rigCameras[i];
  13213. var rigPostProcess = cam._rigPostProcess;
  13214. // for VR rig, there does not have to be a post process
  13215. if (rigPostProcess) {
  13216. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13217. if (isPass) {
  13218. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13219. cam.isIntermediate = this._postProcesses.length === 0;
  13220. }
  13221. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13222. rigPostProcess.markTextureDirty();
  13223. }
  13224. else {
  13225. cam._postProcesses = this._postProcesses.slice(0);
  13226. }
  13227. }
  13228. };
  13229. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13230. if (insertAt === void 0) { insertAt = null; }
  13231. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13232. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13233. return 0;
  13234. }
  13235. if (insertAt == null || insertAt < 0) {
  13236. this._postProcesses.push(postProcess);
  13237. }
  13238. else {
  13239. this._postProcesses.splice(insertAt, 0, postProcess);
  13240. }
  13241. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13242. return this._postProcesses.indexOf(postProcess);
  13243. };
  13244. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13245. if (atIndices === void 0) { atIndices = null; }
  13246. var result = [];
  13247. var i;
  13248. var index;
  13249. if (!atIndices) {
  13250. var idx = this._postProcesses.indexOf(postProcess);
  13251. if (idx !== -1) {
  13252. this._postProcesses.splice(idx, 1);
  13253. }
  13254. }
  13255. else {
  13256. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13257. // iterate descending, so can just splice as we go
  13258. for (i = atIndices.length - 1; i >= 0; i--) {
  13259. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13260. result.push(i);
  13261. continue;
  13262. }
  13263. this._postProcesses.splice(index, 1);
  13264. }
  13265. }
  13266. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13267. return result;
  13268. };
  13269. Camera.prototype.getWorldMatrix = function () {
  13270. if (!this._worldMatrix) {
  13271. this._worldMatrix = BABYLON.Matrix.Identity();
  13272. }
  13273. var viewMatrix = this.getViewMatrix();
  13274. viewMatrix.invertToRef(this._worldMatrix);
  13275. return this._worldMatrix;
  13276. };
  13277. Camera.prototype._getViewMatrix = function () {
  13278. return BABYLON.Matrix.Identity();
  13279. };
  13280. Camera.prototype.getViewMatrix = function (force) {
  13281. this._computedViewMatrix = this._computeViewMatrix(force);
  13282. if (!force && this._isSynchronizedViewMatrix()) {
  13283. return this._computedViewMatrix;
  13284. }
  13285. this._refreshFrustumPlanes = true;
  13286. if (!this.parent || !this.parent.getWorldMatrix) {
  13287. this._globalPosition.copyFrom(this.position);
  13288. }
  13289. else {
  13290. if (!this._worldMatrix) {
  13291. this._worldMatrix = BABYLON.Matrix.Identity();
  13292. }
  13293. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13294. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13295. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13296. this._computedViewMatrix.invert();
  13297. this._markSyncedWithParent();
  13298. }
  13299. this._currentRenderId = this.getScene().getRenderId();
  13300. return this._computedViewMatrix;
  13301. };
  13302. Camera.prototype._computeViewMatrix = function (force) {
  13303. if (!force && this._isSynchronizedViewMatrix()) {
  13304. return this._computedViewMatrix;
  13305. }
  13306. this._computedViewMatrix = this._getViewMatrix();
  13307. this._currentRenderId = this.getScene().getRenderId();
  13308. return this._computedViewMatrix;
  13309. };
  13310. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13311. this._doNotComputeProjectionMatrix = true;
  13312. if (projection !== undefined) {
  13313. this._projectionMatrix = projection;
  13314. }
  13315. };
  13316. ;
  13317. Camera.prototype.unfreezeProjectionMatrix = function () {
  13318. this._doNotComputeProjectionMatrix = false;
  13319. };
  13320. ;
  13321. Camera.prototype.getProjectionMatrix = function (force) {
  13322. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13323. return this._projectionMatrix;
  13324. }
  13325. this._refreshFrustumPlanes = true;
  13326. var engine = this.getEngine();
  13327. var scene = this.getScene();
  13328. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13329. if (this.minZ <= 0) {
  13330. this.minZ = 0.1;
  13331. }
  13332. if (scene.useRightHandedSystem) {
  13333. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13334. }
  13335. else {
  13336. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13337. }
  13338. return this._projectionMatrix;
  13339. }
  13340. var halfWidth = engine.getRenderWidth() / 2.0;
  13341. var halfHeight = engine.getRenderHeight() / 2.0;
  13342. if (scene.useRightHandedSystem) {
  13343. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13344. }
  13345. else {
  13346. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13347. }
  13348. return this._projectionMatrix;
  13349. };
  13350. Camera.prototype.getTranformationMatrix = function () {
  13351. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13352. return this._transformMatrix;
  13353. };
  13354. Camera.prototype.updateFrustumPlanes = function () {
  13355. if (!this._refreshFrustumPlanes) {
  13356. return;
  13357. }
  13358. this.getTranformationMatrix();
  13359. if (!this._frustumPlanes) {
  13360. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13361. }
  13362. else {
  13363. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13364. }
  13365. this._refreshFrustumPlanes = false;
  13366. };
  13367. Camera.prototype.isInFrustum = function (target) {
  13368. this.updateFrustumPlanes();
  13369. return target.isInFrustum(this._frustumPlanes);
  13370. };
  13371. Camera.prototype.isCompletelyInFrustum = function (target) {
  13372. this.updateFrustumPlanes();
  13373. return target.isCompletelyInFrustum(this._frustumPlanes);
  13374. };
  13375. Camera.prototype.dispose = function () {
  13376. // Animations
  13377. this.getScene().stopAnimation(this);
  13378. // Remove from scene
  13379. this.getScene().removeCamera(this);
  13380. while (this._rigCameras.length > 0) {
  13381. this._rigCameras.pop().dispose();
  13382. }
  13383. // Postprocesses
  13384. for (var i = 0; i < this._postProcesses.length; ++i) {
  13385. this._postProcesses[i].dispose(this);
  13386. }
  13387. _super.prototype.dispose.call(this);
  13388. };
  13389. // ---- Camera rigs section ----
  13390. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13391. while (this._rigCameras.length > 0) {
  13392. this._rigCameras.pop().dispose();
  13393. }
  13394. this.cameraRigMode = mode;
  13395. this._cameraRigParams = {};
  13396. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13397. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13398. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13399. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13400. // create the rig cameras, unless none
  13401. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13402. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13403. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13404. }
  13405. switch (this.cameraRigMode) {
  13406. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13407. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13408. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13409. break;
  13410. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13411. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13412. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13413. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13414. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13415. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13416. break;
  13417. case Camera.RIG_MODE_VR:
  13418. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13419. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13420. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13421. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13422. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13423. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13424. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13425. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13426. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13427. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13428. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13429. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13430. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13431. if (metrics.compensateDistortion) {
  13432. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13433. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13434. }
  13435. break;
  13436. case Camera.RIG_MODE_WEBVR:
  13437. if (rigParams.vrDisplay) {
  13438. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13439. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13440. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13441. this._rigCameras[0].setCameraRigParameter("left", true);
  13442. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13443. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13444. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13445. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13446. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13447. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13448. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13449. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13450. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13451. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13452. }
  13453. break;
  13454. }
  13455. this._cascadePostProcessesToRigCams();
  13456. this.
  13457. update();
  13458. };
  13459. Camera.prototype._getVRProjectionMatrix = function () {
  13460. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13461. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13462. return this._projectionMatrix;
  13463. };
  13464. Camera.prototype._getWebVRProjectionMatrix = function () {
  13465. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13466. //babylon compatible matrix
  13467. [8, 9, 10, 11].forEach(function (num) {
  13468. projectionArray[num] *= -1;
  13469. });
  13470. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13471. return this._projectionMatrix;
  13472. };
  13473. //Can be used, but we'll use the free camera's view matrix calculation
  13474. Camera.prototype._getWebVRViewMatrix = function () {
  13475. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13476. //babylon compatible matrix
  13477. [8, 9, 10, 11].forEach(function (num) {
  13478. projectionArray[num] *= -1;
  13479. });
  13480. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13481. return this._webvrViewMatrix;
  13482. };
  13483. Camera.prototype.setCameraRigParameter = function (name, value) {
  13484. if (!this._cameraRigParams) {
  13485. this._cameraRigParams = {};
  13486. }
  13487. this._cameraRigParams[name] = value;
  13488. //provisionnally:
  13489. if (name === "interaxialDistance") {
  13490. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13491. }
  13492. };
  13493. /**
  13494. * needs to be overridden by children so sub has required properties to be copied
  13495. */
  13496. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13497. return null;
  13498. };
  13499. /**
  13500. * May need to be overridden by children
  13501. */
  13502. Camera.prototype._updateRigCameras = function () {
  13503. for (var i = 0; i < this._rigCameras.length; i++) {
  13504. this._rigCameras[i].minZ = this.minZ;
  13505. this._rigCameras[i].maxZ = this.maxZ;
  13506. this._rigCameras[i].fov = this.fov;
  13507. }
  13508. // only update viewport when ANAGLYPH
  13509. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13510. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13511. }
  13512. };
  13513. Camera.prototype._setupInputs = function () {
  13514. };
  13515. Camera.prototype.serialize = function () {
  13516. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13517. // Type
  13518. serializationObject.type = this.getClassName();
  13519. // Parent
  13520. if (this.parent) {
  13521. serializationObject.parentId = this.parent.id;
  13522. }
  13523. if (this.inputs) {
  13524. this.inputs.serialize(serializationObject);
  13525. }
  13526. // Animations
  13527. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13528. serializationObject.ranges = this.serializeAnimationRanges();
  13529. return serializationObject;
  13530. };
  13531. Camera.prototype.clone = function (name) {
  13532. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13533. };
  13534. Camera.prototype.getDirection = function (localAxis) {
  13535. var result = BABYLON.Vector3.Zero();
  13536. this.getDirectionToRef(localAxis, result);
  13537. return result;
  13538. };
  13539. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13540. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13541. };
  13542. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13543. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13544. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13545. switch (type) {
  13546. case "ArcRotateCamera":
  13547. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13548. case "DeviceOrientationCamera":
  13549. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13550. case "FollowCamera":
  13551. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13552. case "ArcFollowCamera":
  13553. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13554. case "GamepadCamera":
  13555. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13556. case "TouchCamera":
  13557. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13558. case "VirtualJoysticksCamera":
  13559. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13560. case "WebVRFreeCamera":
  13561. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13562. case "VRDeviceOrientationFreeCamera":
  13563. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13564. case "AnaglyphArcRotateCamera":
  13565. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13566. case "AnaglyphFreeCamera":
  13567. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13568. case "AnaglyphGamepadCamera":
  13569. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13570. case "AnaglyphUniversalCamera":
  13571. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13572. case "StereoscopicArcRotateCamera":
  13573. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13574. case "StereoscopicFreeCamera":
  13575. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13576. case "StereoscopicGamepadCamera":
  13577. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13578. case "StereoscopicUniversalCamera":
  13579. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13580. case "FreeCamera":
  13581. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13582. default:
  13583. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13584. }
  13585. };
  13586. Camera.Parse = function (parsedCamera, scene) {
  13587. var type = parsedCamera.type;
  13588. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13589. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13590. // Parent
  13591. if (parsedCamera.parentId) {
  13592. camera._waitingParentId = parsedCamera.parentId;
  13593. }
  13594. //If camera has an input manager, let it parse inputs settings
  13595. if (camera.inputs) {
  13596. camera.inputs.parse(parsedCamera);
  13597. camera._setupInputs();
  13598. }
  13599. // Target
  13600. if (parsedCamera.target) {
  13601. if (camera.setTarget) {
  13602. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13603. }
  13604. }
  13605. // Apply 3d rig, when found
  13606. if (parsedCamera.cameraRigMode) {
  13607. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13608. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13609. }
  13610. // Animations
  13611. if (parsedCamera.animations) {
  13612. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13613. var parsedAnimation = parsedCamera.animations[animationIndex];
  13614. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13615. }
  13616. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13617. }
  13618. if (parsedCamera.autoAnimate) {
  13619. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13620. }
  13621. return camera;
  13622. };
  13623. // Statics
  13624. Camera._PERSPECTIVE_CAMERA = 0;
  13625. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13626. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13627. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13628. Camera._RIG_MODE_NONE = 0;
  13629. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13630. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13631. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13632. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13633. Camera._RIG_MODE_VR = 20;
  13634. Camera._RIG_MODE_WEBVR = 21;
  13635. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13636. __decorate([
  13637. BABYLON.serializeAsVector3()
  13638. ], Camera.prototype, "position", void 0);
  13639. __decorate([
  13640. BABYLON.serializeAsVector3()
  13641. ], Camera.prototype, "upVector", void 0);
  13642. __decorate([
  13643. BABYLON.serialize()
  13644. ], Camera.prototype, "orthoLeft", void 0);
  13645. __decorate([
  13646. BABYLON.serialize()
  13647. ], Camera.prototype, "orthoRight", void 0);
  13648. __decorate([
  13649. BABYLON.serialize()
  13650. ], Camera.prototype, "orthoBottom", void 0);
  13651. __decorate([
  13652. BABYLON.serialize()
  13653. ], Camera.prototype, "orthoTop", void 0);
  13654. __decorate([
  13655. BABYLON.serialize()
  13656. ], Camera.prototype, "fov", void 0);
  13657. __decorate([
  13658. BABYLON.serialize()
  13659. ], Camera.prototype, "minZ", void 0);
  13660. __decorate([
  13661. BABYLON.serialize()
  13662. ], Camera.prototype, "maxZ", void 0);
  13663. __decorate([
  13664. BABYLON.serialize()
  13665. ], Camera.prototype, "inertia", void 0);
  13666. __decorate([
  13667. BABYLON.serialize()
  13668. ], Camera.prototype, "mode", void 0);
  13669. __decorate([
  13670. BABYLON.serialize()
  13671. ], Camera.prototype, "layerMask", void 0);
  13672. __decorate([
  13673. BABYLON.serialize()
  13674. ], Camera.prototype, "fovMode", void 0);
  13675. __decorate([
  13676. BABYLON.serialize()
  13677. ], Camera.prototype, "cameraRigMode", void 0);
  13678. __decorate([
  13679. BABYLON.serialize()
  13680. ], Camera.prototype, "interaxialDistance", void 0);
  13681. __decorate([
  13682. BABYLON.serialize()
  13683. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13684. return Camera;
  13685. }(BABYLON.Node));
  13686. BABYLON.Camera = Camera;
  13687. })(BABYLON || (BABYLON = {}));
  13688. //# sourceMappingURL=babylon.camera.js.map
  13689. var BABYLON;
  13690. (function (BABYLON) {
  13691. BABYLON.CameraInputTypes = {};
  13692. var CameraInputsManager = (function () {
  13693. function CameraInputsManager(camera) {
  13694. this.attached = {};
  13695. this.camera = camera;
  13696. this.checkInputs = function () { };
  13697. }
  13698. CameraInputsManager.prototype.add = function (input) {
  13699. var type = input.getSimpleName();
  13700. if (this.attached[type]) {
  13701. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13702. return;
  13703. }
  13704. this.attached[type] = input;
  13705. input.camera = this.camera;
  13706. //for checkInputs, we are dynamically creating a function
  13707. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13708. if (input.checkInputs) {
  13709. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13710. }
  13711. if (this.attachedElement) {
  13712. input.attachControl(this.attachedElement);
  13713. }
  13714. };
  13715. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13716. for (var cam in this.attached) {
  13717. var input = this.attached[cam];
  13718. if (input === inputToRemove) {
  13719. input.detachControl(this.attachedElement);
  13720. delete this.attached[cam];
  13721. this.rebuildInputCheck();
  13722. }
  13723. }
  13724. };
  13725. CameraInputsManager.prototype.removeByType = function (inputType) {
  13726. for (var cam in this.attached) {
  13727. var input = this.attached[cam];
  13728. if (input.getTypeName() === inputType) {
  13729. input.detachControl(this.attachedElement);
  13730. delete this.attached[cam];
  13731. this.rebuildInputCheck();
  13732. }
  13733. }
  13734. };
  13735. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13736. var current = this.checkInputs;
  13737. return function () {
  13738. current();
  13739. fn();
  13740. };
  13741. };
  13742. CameraInputsManager.prototype.attachInput = function (input) {
  13743. input.attachControl(this.attachedElement, this.noPreventDefault);
  13744. };
  13745. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13746. if (this.attachedElement) {
  13747. return;
  13748. }
  13749. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13750. this.attachedElement = element;
  13751. this.noPreventDefault = noPreventDefault;
  13752. for (var cam in this.attached) {
  13753. var input = this.attached[cam];
  13754. this.attached[cam].attachControl(element, noPreventDefault);
  13755. }
  13756. };
  13757. CameraInputsManager.prototype.detachElement = function (element) {
  13758. if (this.attachedElement !== element) {
  13759. return;
  13760. }
  13761. for (var cam in this.attached) {
  13762. var input = this.attached[cam];
  13763. this.attached[cam].detachControl(element);
  13764. }
  13765. this.attachedElement = null;
  13766. };
  13767. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13768. this.checkInputs = function () { };
  13769. for (var cam in this.attached) {
  13770. var input = this.attached[cam];
  13771. if (input.checkInputs) {
  13772. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13773. }
  13774. }
  13775. };
  13776. CameraInputsManager.prototype.clear = function () {
  13777. if (this.attachedElement) {
  13778. this.detachElement(this.attachedElement);
  13779. }
  13780. this.attached = {};
  13781. this.attachedElement = null;
  13782. this.checkInputs = function () { };
  13783. };
  13784. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13785. var inputs = {};
  13786. for (var cam in this.attached) {
  13787. var input = this.attached[cam];
  13788. var res = BABYLON.SerializationHelper.Serialize(input);
  13789. inputs[input.getTypeName()] = res;
  13790. }
  13791. serializedCamera.inputsmgr = inputs;
  13792. };
  13793. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13794. var parsedInputs = parsedCamera.inputsmgr;
  13795. if (parsedInputs) {
  13796. this.clear();
  13797. for (var n in parsedInputs) {
  13798. var construct = BABYLON.CameraInputTypes[n];
  13799. if (construct) {
  13800. var parsedinput = parsedInputs[n];
  13801. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13802. this.add(input);
  13803. }
  13804. }
  13805. }
  13806. else {
  13807. //2016-03-08 this part is for managing backward compatibility
  13808. for (var n in this.attached) {
  13809. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13810. if (construct) {
  13811. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13812. this.remove(this.attached[n]);
  13813. this.add(input);
  13814. }
  13815. }
  13816. }
  13817. };
  13818. return CameraInputsManager;
  13819. }());
  13820. BABYLON.CameraInputsManager = CameraInputsManager;
  13821. })(BABYLON || (BABYLON = {}));
  13822. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  13823. var BABYLON;
  13824. (function (BABYLON) {
  13825. var FreeCameraMouseInput = (function () {
  13826. function FreeCameraMouseInput(touchEnabled) {
  13827. if (touchEnabled === void 0) { touchEnabled = true; }
  13828. this.touchEnabled = touchEnabled;
  13829. this.buttons = [0, 1, 2];
  13830. this.angularSensibility = 2000.0;
  13831. }
  13832. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13833. var _this = this;
  13834. var engine = this.camera.getEngine();
  13835. if (!this._pointerInput) {
  13836. this._pointerInput = function (p, s) {
  13837. var evt = p.event;
  13838. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13839. return;
  13840. }
  13841. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  13842. return;
  13843. }
  13844. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13845. try {
  13846. evt.srcElement.setPointerCapture(evt.pointerId);
  13847. }
  13848. catch (e) {
  13849. }
  13850. _this.previousPosition = {
  13851. x: evt.clientX,
  13852. y: evt.clientY
  13853. };
  13854. if (!noPreventDefault) {
  13855. evt.preventDefault();
  13856. element.focus();
  13857. }
  13858. }
  13859. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13860. try {
  13861. evt.srcElement.releasePointerCapture(evt.pointerId);
  13862. }
  13863. catch (e) {
  13864. }
  13865. _this.previousPosition = null;
  13866. if (!noPreventDefault) {
  13867. evt.preventDefault();
  13868. }
  13869. }
  13870. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13871. if (!_this.previousPosition || engine.isPointerLock) {
  13872. return;
  13873. }
  13874. var offsetX = evt.clientX - _this.previousPosition.x;
  13875. var offsetY = evt.clientY - _this.previousPosition.y;
  13876. if (_this.camera.getScene().useRightHandedSystem) {
  13877. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13878. }
  13879. else {
  13880. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13881. }
  13882. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13883. _this.previousPosition = {
  13884. x: evt.clientX,
  13885. y: evt.clientY
  13886. };
  13887. if (!noPreventDefault) {
  13888. evt.preventDefault();
  13889. }
  13890. }
  13891. };
  13892. }
  13893. this._onMouseMove = function (evt) {
  13894. if (!engine.isPointerLock) {
  13895. return;
  13896. }
  13897. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13898. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13899. if (_this.camera.getScene().useRightHandedSystem) {
  13900. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13901. }
  13902. else {
  13903. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13904. }
  13905. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13906. _this.previousPosition = null;
  13907. if (!noPreventDefault) {
  13908. evt.preventDefault();
  13909. }
  13910. };
  13911. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13912. element.addEventListener("mousemove", this._onMouseMove, false);
  13913. };
  13914. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13915. if (this._observer && element) {
  13916. this.camera.getScene().onPointerObservable.remove(this._observer);
  13917. element.removeEventListener("mousemove", this._onMouseMove);
  13918. this._observer = null;
  13919. this._onMouseMove = null;
  13920. this.previousPosition = null;
  13921. }
  13922. };
  13923. FreeCameraMouseInput.prototype.getTypeName = function () {
  13924. return "FreeCameraMouseInput";
  13925. };
  13926. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13927. return "mouse";
  13928. };
  13929. __decorate([
  13930. BABYLON.serialize()
  13931. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  13932. __decorate([
  13933. BABYLON.serialize()
  13934. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13935. return FreeCameraMouseInput;
  13936. }());
  13937. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13938. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13939. })(BABYLON || (BABYLON = {}));
  13940. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  13941. var BABYLON;
  13942. (function (BABYLON) {
  13943. var FreeCameraKeyboardMoveInput = (function () {
  13944. function FreeCameraKeyboardMoveInput() {
  13945. this._keys = [];
  13946. this.keysUp = [38];
  13947. this.keysDown = [40];
  13948. this.keysLeft = [37];
  13949. this.keysRight = [39];
  13950. }
  13951. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13952. var _this = this;
  13953. if (!this._onKeyDown) {
  13954. element.tabIndex = 1;
  13955. this._onKeyDown = function (evt) {
  13956. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13957. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13958. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13959. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13960. var index = _this._keys.indexOf(evt.keyCode);
  13961. if (index === -1) {
  13962. _this._keys.push(evt.keyCode);
  13963. }
  13964. if (!noPreventDefault) {
  13965. evt.preventDefault();
  13966. }
  13967. }
  13968. };
  13969. this._onKeyUp = function (evt) {
  13970. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13971. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13972. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13973. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13974. var index = _this._keys.indexOf(evt.keyCode);
  13975. if (index >= 0) {
  13976. _this._keys.splice(index, 1);
  13977. }
  13978. if (!noPreventDefault) {
  13979. evt.preventDefault();
  13980. }
  13981. }
  13982. };
  13983. element.addEventListener("keydown", this._onKeyDown, false);
  13984. element.addEventListener("keyup", this._onKeyUp, false);
  13985. BABYLON.Tools.RegisterTopRootEvents([
  13986. { name: "blur", handler: this._onLostFocus }
  13987. ]);
  13988. }
  13989. };
  13990. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13991. if (this._onKeyDown) {
  13992. element.removeEventListener("keydown", this._onKeyDown);
  13993. element.removeEventListener("keyup", this._onKeyUp);
  13994. BABYLON.Tools.UnregisterTopRootEvents([
  13995. { name: "blur", handler: this._onLostFocus }
  13996. ]);
  13997. this._keys = [];
  13998. this._onKeyDown = null;
  13999. this._onKeyUp = null;
  14000. }
  14001. };
  14002. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14003. if (this._onKeyDown) {
  14004. var camera = this.camera;
  14005. // Keyboard
  14006. for (var index = 0; index < this._keys.length; index++) {
  14007. var keyCode = this._keys[index];
  14008. var speed = camera._computeLocalCameraSpeed();
  14009. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14010. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14011. }
  14012. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14013. camera._localDirection.copyFromFloats(0, 0, speed);
  14014. }
  14015. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14016. camera._localDirection.copyFromFloats(speed, 0, 0);
  14017. }
  14018. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14019. camera._localDirection.copyFromFloats(0, 0, -speed);
  14020. }
  14021. if (camera.getScene().useRightHandedSystem) {
  14022. camera._localDirection.z *= -1;
  14023. }
  14024. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14025. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14026. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14027. }
  14028. }
  14029. };
  14030. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14031. return "FreeCameraKeyboardMoveInput";
  14032. };
  14033. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14034. this._keys = [];
  14035. };
  14036. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14037. return "keyboard";
  14038. };
  14039. __decorate([
  14040. BABYLON.serialize()
  14041. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14042. __decorate([
  14043. BABYLON.serialize()
  14044. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14045. __decorate([
  14046. BABYLON.serialize()
  14047. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14048. __decorate([
  14049. BABYLON.serialize()
  14050. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14051. return FreeCameraKeyboardMoveInput;
  14052. }());
  14053. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14054. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14055. })(BABYLON || (BABYLON = {}));
  14056. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14057. var BABYLON;
  14058. (function (BABYLON) {
  14059. var FreeCameraTouchInput = (function () {
  14060. function FreeCameraTouchInput() {
  14061. this._offsetX = null;
  14062. this._offsetY = null;
  14063. this._pointerCount = 0;
  14064. this._pointerPressed = [];
  14065. this.touchAngularSensibility = 200000.0;
  14066. this.touchMoveSensibility = 250.0;
  14067. }
  14068. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14069. var _this = this;
  14070. var previousPosition;
  14071. if (this._pointerInput === undefined) {
  14072. this._onLostFocus = function (evt) {
  14073. _this._offsetX = null;
  14074. _this._offsetY = null;
  14075. };
  14076. this._pointerInput = function (p, s) {
  14077. var evt = p.event;
  14078. if (evt.pointerType === "mouse") {
  14079. return;
  14080. }
  14081. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14082. if (!noPreventDefault) {
  14083. evt.preventDefault();
  14084. }
  14085. _this._pointerPressed.push(evt.pointerId);
  14086. if (_this._pointerPressed.length !== 1) {
  14087. return;
  14088. }
  14089. previousPosition = {
  14090. x: evt.clientX,
  14091. y: evt.clientY
  14092. };
  14093. }
  14094. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14095. if (!noPreventDefault) {
  14096. evt.preventDefault();
  14097. }
  14098. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14099. if (index === -1) {
  14100. return;
  14101. }
  14102. _this._pointerPressed.splice(index, 1);
  14103. if (index != 0) {
  14104. return;
  14105. }
  14106. previousPosition = null;
  14107. _this._offsetX = null;
  14108. _this._offsetY = null;
  14109. }
  14110. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14111. if (!noPreventDefault) {
  14112. evt.preventDefault();
  14113. }
  14114. if (!previousPosition) {
  14115. return;
  14116. }
  14117. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14118. if (index != 0) {
  14119. return;
  14120. }
  14121. _this._offsetX = evt.clientX - previousPosition.x;
  14122. _this._offsetY = -(evt.clientY - previousPosition.y);
  14123. }
  14124. };
  14125. }
  14126. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14127. element.addEventListener("blur", this._onLostFocus);
  14128. };
  14129. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14130. if (this._pointerInput && element) {
  14131. this.camera.getScene().onPointerObservable.remove(this._observer);
  14132. this._observer = null;
  14133. element.removeEventListener("blur", this._onLostFocus);
  14134. this._onLostFocus = null;
  14135. this._pointerPressed = [];
  14136. this._offsetX = null;
  14137. this._offsetY = null;
  14138. this._pointerCount = 0;
  14139. }
  14140. };
  14141. FreeCameraTouchInput.prototype.checkInputs = function () {
  14142. if (this._offsetX) {
  14143. var camera = this.camera;
  14144. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14145. if (this._pointerPressed.length > 1) {
  14146. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14147. }
  14148. else {
  14149. var speed = camera._computeLocalCameraSpeed();
  14150. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14151. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14152. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14153. }
  14154. }
  14155. };
  14156. FreeCameraTouchInput.prototype.getTypeName = function () {
  14157. return "FreeCameraTouchInput";
  14158. };
  14159. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14160. return "touch";
  14161. };
  14162. __decorate([
  14163. BABYLON.serialize()
  14164. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14165. __decorate([
  14166. BABYLON.serialize()
  14167. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14168. return FreeCameraTouchInput;
  14169. }());
  14170. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14171. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14172. })(BABYLON || (BABYLON = {}));
  14173. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14174. var BABYLON;
  14175. (function (BABYLON) {
  14176. var FreeCameraDeviceOrientationInput = (function () {
  14177. function FreeCameraDeviceOrientationInput() {
  14178. var _this = this;
  14179. this._screenOrientationAngle = 0;
  14180. this._screenQuaternion = new BABYLON.Quaternion();
  14181. this._alpha = 0;
  14182. this._beta = 0;
  14183. this._gamma = 0;
  14184. this._orientationChanged = function () {
  14185. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14186. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14187. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14188. };
  14189. this._deviceOrientation = function (evt) {
  14190. _this._alpha = evt.alpha;
  14191. _this._beta = evt.beta;
  14192. _this._gamma = evt.gamma;
  14193. };
  14194. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14195. this._orientationChanged();
  14196. }
  14197. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14198. get: function () {
  14199. return this._camera;
  14200. },
  14201. set: function (camera) {
  14202. this._camera = camera;
  14203. if (!this._camera.rotationQuaternion)
  14204. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14205. },
  14206. enumerable: true,
  14207. configurable: true
  14208. });
  14209. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14210. window.addEventListener("orientationchange", this._orientationChanged);
  14211. window.addEventListener("deviceorientation", this._deviceOrientation);
  14212. //In certain cases, the attach control is called AFTER orientation was changed,
  14213. //So this is needed.
  14214. this._orientationChanged();
  14215. };
  14216. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14217. window.removeEventListener("orientationchange", this._orientationChanged);
  14218. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14219. };
  14220. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14221. //if no device orientation provided, don't update the rotation.
  14222. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14223. if (!this._alpha)
  14224. return;
  14225. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14226. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14227. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14228. //Mirror on XY Plane
  14229. this._camera.rotationQuaternion.z *= -1;
  14230. this._camera.rotationQuaternion.w *= -1;
  14231. };
  14232. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14233. return "FreeCameraDeviceOrientationInput";
  14234. };
  14235. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14236. return "deviceOrientation";
  14237. };
  14238. return FreeCameraDeviceOrientationInput;
  14239. }());
  14240. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14241. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14242. })(BABYLON || (BABYLON = {}));
  14243. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14244. var BABYLON;
  14245. (function (BABYLON) {
  14246. var FreeCameraGamepadInput = (function () {
  14247. function FreeCameraGamepadInput() {
  14248. this.gamepadAngularSensibility = 200;
  14249. this.gamepadMoveSensibility = 40;
  14250. }
  14251. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14252. var _this = this;
  14253. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14254. };
  14255. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14256. if (this._gamepads) {
  14257. this._gamepads.dispose();
  14258. }
  14259. this.gamepad = null;
  14260. };
  14261. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14262. if (this.gamepad) {
  14263. var camera = this.camera;
  14264. var LSValues = this.gamepad.leftStick;
  14265. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14266. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14267. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14268. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14269. var RSValues = this.gamepad.rightStick;
  14270. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14271. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14272. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14273. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14274. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14275. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14276. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14277. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14278. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14279. }
  14280. };
  14281. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14282. // Only the first gamepad can control the camera
  14283. if (gamepad.index === 0) {
  14284. this.gamepad = gamepad;
  14285. }
  14286. };
  14287. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14288. return "FreeCameraGamepadInput";
  14289. };
  14290. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14291. return "gamepad";
  14292. };
  14293. __decorate([
  14294. BABYLON.serialize()
  14295. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14296. __decorate([
  14297. BABYLON.serialize()
  14298. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14299. return FreeCameraGamepadInput;
  14300. }());
  14301. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14302. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14303. })(BABYLON || (BABYLON = {}));
  14304. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  14305. var BABYLON;
  14306. (function (BABYLON) {
  14307. var ArcRotateCameraKeyboardMoveInput = (function () {
  14308. function ArcRotateCameraKeyboardMoveInput() {
  14309. this._keys = [];
  14310. this.keysUp = [38];
  14311. this.keysDown = [40];
  14312. this.keysLeft = [37];
  14313. this.keysRight = [39];
  14314. }
  14315. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14316. var _this = this;
  14317. element.tabIndex = 1;
  14318. this._onKeyDown = function (evt) {
  14319. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14320. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14321. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14322. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14323. var index = _this._keys.indexOf(evt.keyCode);
  14324. if (index === -1) {
  14325. _this._keys.push(evt.keyCode);
  14326. }
  14327. if (evt.preventDefault) {
  14328. if (!noPreventDefault) {
  14329. evt.preventDefault();
  14330. }
  14331. }
  14332. }
  14333. };
  14334. this._onKeyUp = function (evt) {
  14335. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14336. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14337. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14338. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14339. var index = _this._keys.indexOf(evt.keyCode);
  14340. if (index >= 0) {
  14341. _this._keys.splice(index, 1);
  14342. }
  14343. if (evt.preventDefault) {
  14344. if (!noPreventDefault) {
  14345. evt.preventDefault();
  14346. }
  14347. }
  14348. }
  14349. };
  14350. this._onLostFocus = function () {
  14351. _this._keys = [];
  14352. };
  14353. element.addEventListener("keydown", this._onKeyDown, false);
  14354. element.addEventListener("keyup", this._onKeyUp, false);
  14355. BABYLON.Tools.RegisterTopRootEvents([
  14356. { name: "blur", handler: this._onLostFocus }
  14357. ]);
  14358. };
  14359. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14360. if (element) {
  14361. element.removeEventListener("keydown", this._onKeyDown);
  14362. element.removeEventListener("keyup", this._onKeyUp);
  14363. }
  14364. BABYLON.Tools.UnregisterTopRootEvents([
  14365. { name: "blur", handler: this._onLostFocus }
  14366. ]);
  14367. this._keys = [];
  14368. this._onKeyDown = null;
  14369. this._onKeyUp = null;
  14370. this._onLostFocus = null;
  14371. };
  14372. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14373. if (this._onKeyDown) {
  14374. var camera = this.camera;
  14375. for (var index = 0; index < this._keys.length; index++) {
  14376. var keyCode = this._keys[index];
  14377. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14378. camera.inertialAlphaOffset -= 0.01;
  14379. }
  14380. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14381. camera.inertialBetaOffset -= 0.01;
  14382. }
  14383. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14384. camera.inertialAlphaOffset += 0.01;
  14385. }
  14386. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14387. camera.inertialBetaOffset += 0.01;
  14388. }
  14389. }
  14390. }
  14391. };
  14392. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14393. return "ArcRotateCameraKeyboardMoveInput";
  14394. };
  14395. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14396. return "keyboard";
  14397. };
  14398. __decorate([
  14399. BABYLON.serialize()
  14400. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14401. __decorate([
  14402. BABYLON.serialize()
  14403. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14404. __decorate([
  14405. BABYLON.serialize()
  14406. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14407. __decorate([
  14408. BABYLON.serialize()
  14409. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14410. return ArcRotateCameraKeyboardMoveInput;
  14411. }());
  14412. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14413. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14414. })(BABYLON || (BABYLON = {}));
  14415. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  14416. var BABYLON;
  14417. (function (BABYLON) {
  14418. var ArcRotateCameraMouseWheelInput = (function () {
  14419. function ArcRotateCameraMouseWheelInput() {
  14420. this.wheelPrecision = 3.0;
  14421. }
  14422. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14423. var _this = this;
  14424. this._wheel = function (p, s) {
  14425. //sanity check - this should be a PointerWheel event.
  14426. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14427. return;
  14428. var event = p.event;
  14429. var delta = 0;
  14430. if (event.wheelDelta) {
  14431. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14432. }
  14433. else if (event.detail) {
  14434. delta = -event.detail / _this.wheelPrecision;
  14435. }
  14436. if (delta)
  14437. _this.camera.inertialRadiusOffset += delta;
  14438. if (event.preventDefault) {
  14439. if (!noPreventDefault) {
  14440. event.preventDefault();
  14441. }
  14442. }
  14443. };
  14444. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14445. };
  14446. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14447. if (this._observer && element) {
  14448. this.camera.getScene().onPointerObservable.remove(this._observer);
  14449. this._observer = null;
  14450. this._wheel = null;
  14451. }
  14452. };
  14453. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14454. return "ArcRotateCameraMouseWheelInput";
  14455. };
  14456. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14457. return "mousewheel";
  14458. };
  14459. __decorate([
  14460. BABYLON.serialize()
  14461. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14462. return ArcRotateCameraMouseWheelInput;
  14463. }());
  14464. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14465. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14466. })(BABYLON || (BABYLON = {}));
  14467. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  14468. var BABYLON;
  14469. (function (BABYLON) {
  14470. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14471. var ArcRotateCameraPointersInput = (function () {
  14472. function ArcRotateCameraPointersInput() {
  14473. this.buttons = [0, 1, 2];
  14474. this.angularSensibilityX = 1000.0;
  14475. this.angularSensibilityY = 1000.0;
  14476. this.pinchPrecision = 6.0;
  14477. this.panningSensibility = 50.0;
  14478. this._isPanClick = false;
  14479. this.pinchInwards = true;
  14480. }
  14481. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14482. var _this = this;
  14483. var engine = this.camera.getEngine();
  14484. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14485. var pointA, pointB;
  14486. var previousPinchDistance = 0;
  14487. this._pointerInput = function (p, s) {
  14488. var evt = p.event;
  14489. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14490. return;
  14491. }
  14492. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14493. try {
  14494. evt.srcElement.setPointerCapture(evt.pointerId);
  14495. }
  14496. catch (e) {
  14497. }
  14498. // Manage panning with pan button click
  14499. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14500. // manage pointers
  14501. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14502. if (pointA === undefined) {
  14503. pointA = cacheSoloPointer;
  14504. }
  14505. else if (pointB === undefined) {
  14506. pointB = cacheSoloPointer;
  14507. }
  14508. if (!noPreventDefault) {
  14509. evt.preventDefault();
  14510. element.focus();
  14511. }
  14512. }
  14513. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14514. try {
  14515. evt.srcElement.releasePointerCapture(evt.pointerId);
  14516. }
  14517. catch (e) {
  14518. }
  14519. cacheSoloPointer = null;
  14520. previousPinchDistance = 0;
  14521. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14522. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14523. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14524. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14525. pointA = pointB = undefined;
  14526. if (!noPreventDefault) {
  14527. evt.preventDefault();
  14528. }
  14529. }
  14530. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14531. if (!noPreventDefault) {
  14532. evt.preventDefault();
  14533. }
  14534. // One button down
  14535. if (pointA && pointB === undefined) {
  14536. if (_this.panningSensibility !== 0 &&
  14537. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14538. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14539. _this.camera
  14540. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14541. _this.camera
  14542. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14543. }
  14544. else {
  14545. var offsetX = evt.clientX - cacheSoloPointer.x;
  14546. var offsetY = evt.clientY - cacheSoloPointer.y;
  14547. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14548. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14549. }
  14550. cacheSoloPointer.x = evt.clientX;
  14551. cacheSoloPointer.y = evt.clientY;
  14552. }
  14553. else if (pointA && pointB) {
  14554. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14555. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14556. ed.x = evt.clientX;
  14557. ed.y = evt.clientY;
  14558. var direction = _this.pinchInwards ? 1 : -1;
  14559. var distX = pointA.x - pointB.x;
  14560. var distY = pointA.y - pointB.y;
  14561. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14562. if (previousPinchDistance === 0) {
  14563. previousPinchDistance = pinchSquaredDistance;
  14564. return;
  14565. }
  14566. if (pinchSquaredDistance !== previousPinchDistance) {
  14567. _this.camera
  14568. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14569. (_this.pinchPrecision *
  14570. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14571. direction);
  14572. previousPinchDistance = pinchSquaredDistance;
  14573. }
  14574. }
  14575. }
  14576. };
  14577. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14578. this._onContextMenu = function (evt) {
  14579. evt.preventDefault();
  14580. };
  14581. if (!this.camera._useCtrlForPanning) {
  14582. element.addEventListener("contextmenu", this._onContextMenu, false);
  14583. }
  14584. this._onLostFocus = function () {
  14585. //this._keys = [];
  14586. pointA = pointB = undefined;
  14587. previousPinchDistance = 0;
  14588. cacheSoloPointer = null;
  14589. };
  14590. this._onMouseMove = function (evt) {
  14591. if (!engine.isPointerLock) {
  14592. return;
  14593. }
  14594. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14595. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14596. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14597. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14598. if (!noPreventDefault) {
  14599. evt.preventDefault();
  14600. }
  14601. };
  14602. this._onGestureStart = function (e) {
  14603. if (window.MSGesture === undefined) {
  14604. return;
  14605. }
  14606. if (!_this._MSGestureHandler) {
  14607. _this._MSGestureHandler = new MSGesture();
  14608. _this._MSGestureHandler.target = element;
  14609. }
  14610. _this._MSGestureHandler.addPointer(e.pointerId);
  14611. };
  14612. this._onGesture = function (e) {
  14613. _this.camera.radius *= e.scale;
  14614. if (e.preventDefault) {
  14615. if (!noPreventDefault) {
  14616. e.stopPropagation();
  14617. e.preventDefault();
  14618. }
  14619. }
  14620. };
  14621. element.addEventListener("mousemove", this._onMouseMove, false);
  14622. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14623. element.addEventListener("MSGestureChange", this._onGesture, false);
  14624. element.addEventListener("keydown", this._onKeyDown, false);
  14625. element.addEventListener("keyup", this._onKeyUp, false);
  14626. BABYLON.Tools.RegisterTopRootEvents([
  14627. { name: "blur", handler: this._onLostFocus }
  14628. ]);
  14629. };
  14630. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14631. if (element && this._observer) {
  14632. this.camera.getScene().onPointerObservable.remove(this._observer);
  14633. this._observer = null;
  14634. element.removeEventListener("contextmenu", this._onContextMenu);
  14635. element.removeEventListener("mousemove", this._onMouseMove);
  14636. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14637. element.removeEventListener("MSGestureChange", this._onGesture);
  14638. element.removeEventListener("keydown", this._onKeyDown);
  14639. element.removeEventListener("keyup", this._onKeyUp);
  14640. this._isPanClick = false;
  14641. this.pinchInwards = true;
  14642. this._onKeyDown = null;
  14643. this._onKeyUp = null;
  14644. this._onMouseMove = null;
  14645. this._onGestureStart = null;
  14646. this._onGesture = null;
  14647. this._MSGestureHandler = null;
  14648. this._onLostFocus = null;
  14649. this._onContextMenu = null;
  14650. }
  14651. BABYLON.Tools.UnregisterTopRootEvents([
  14652. { name: "blur", handler: this._onLostFocus }
  14653. ]);
  14654. };
  14655. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14656. return "ArcRotateCameraPointersInput";
  14657. };
  14658. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14659. return "pointers";
  14660. };
  14661. __decorate([
  14662. BABYLON.serialize()
  14663. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14664. __decorate([
  14665. BABYLON.serialize()
  14666. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14667. __decorate([
  14668. BABYLON.serialize()
  14669. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14670. __decorate([
  14671. BABYLON.serialize()
  14672. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14673. __decorate([
  14674. BABYLON.serialize()
  14675. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14676. return ArcRotateCameraPointersInput;
  14677. }());
  14678. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14679. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14680. })(BABYLON || (BABYLON = {}));
  14681. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  14682. var BABYLON;
  14683. (function (BABYLON) {
  14684. var ArcRotateCameraGamepadInput = (function () {
  14685. function ArcRotateCameraGamepadInput() {
  14686. this.gamepadRotationSensibility = 80;
  14687. this.gamepadMoveSensibility = 40;
  14688. }
  14689. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14690. var _this = this;
  14691. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14692. };
  14693. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14694. if (this._gamepads) {
  14695. this._gamepads.dispose();
  14696. }
  14697. this.gamepad = null;
  14698. };
  14699. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14700. if (this.gamepad) {
  14701. var camera = this.camera;
  14702. var RSValues = this.gamepad.rightStick;
  14703. if (RSValues.x != 0) {
  14704. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14705. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14706. camera.inertialAlphaOffset += normalizedRX;
  14707. }
  14708. }
  14709. if (RSValues.y != 0) {
  14710. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14711. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14712. camera.inertialBetaOffset += normalizedRY;
  14713. }
  14714. }
  14715. var LSValues = this.gamepad.leftStick;
  14716. if (LSValues.y != 0) {
  14717. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14718. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14719. this.camera.inertialRadiusOffset -= normalizedLY;
  14720. }
  14721. }
  14722. }
  14723. };
  14724. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14725. // Only the first gamepad can control the camera
  14726. if (gamepad.index === 0) {
  14727. this.gamepad = gamepad;
  14728. }
  14729. };
  14730. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14731. return "ArcRotateCameraGamepadInput";
  14732. };
  14733. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14734. return "gamepad";
  14735. };
  14736. __decorate([
  14737. BABYLON.serialize()
  14738. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14739. __decorate([
  14740. BABYLON.serialize()
  14741. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14742. return ArcRotateCameraGamepadInput;
  14743. }());
  14744. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14745. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14746. })(BABYLON || (BABYLON = {}));
  14747. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  14748. var BABYLON;
  14749. (function (BABYLON) {
  14750. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14751. function ArcRotateCameraVRDeviceOrientationInput() {
  14752. this.alphaCorrection = 1;
  14753. this.betaCorrection = 1;
  14754. this.gammaCorrection = 1;
  14755. this._alpha = 0;
  14756. this._beta = 0;
  14757. this._gamma = 0;
  14758. this._dirty = false;
  14759. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14760. }
  14761. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14762. this.camera.attachControl(element, noPreventDefault);
  14763. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14764. };
  14765. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14766. var camera = this.camera;
  14767. this._alpha = +evt.alpha | 0;
  14768. this._beta = +evt.beta | 0;
  14769. this._gamma = +evt.gamma | 0;
  14770. this._dirty = true;
  14771. };
  14772. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14773. if (this._dirty) {
  14774. this._dirty = false;
  14775. if (this._gamma < 0) {
  14776. this._gamma = 180 + this._gamma;
  14777. }
  14778. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14779. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14780. }
  14781. };
  14782. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14783. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14784. };
  14785. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14786. return "ArcRotateCameraVRDeviceOrientationInput";
  14787. };
  14788. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14789. return "VRDeviceOrientation";
  14790. };
  14791. return ArcRotateCameraVRDeviceOrientationInput;
  14792. }());
  14793. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14794. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14795. })(BABYLON || (BABYLON = {}));
  14796. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  14797. var BABYLON;
  14798. (function (BABYLON) {
  14799. var TargetCamera = (function (_super) {
  14800. __extends(TargetCamera, _super);
  14801. function TargetCamera(name, position, scene) {
  14802. _super.call(this, name, position, scene);
  14803. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14804. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14805. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14806. this.speed = 2.0;
  14807. this.noRotationConstraint = false;
  14808. this.lockedTarget = null;
  14809. this._currentTarget = BABYLON.Vector3.Zero();
  14810. this._viewMatrix = BABYLON.Matrix.Zero();
  14811. this._camMatrix = BABYLON.Matrix.Zero();
  14812. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14813. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14814. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14815. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14816. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14817. this._lookAtTemp = BABYLON.Matrix.Zero();
  14818. this._tempMatrix = BABYLON.Matrix.Zero();
  14819. }
  14820. TargetCamera.prototype.getFrontPosition = function (distance) {
  14821. var direction = this.getTarget().subtract(this.position);
  14822. direction.normalize();
  14823. direction.scaleInPlace(distance);
  14824. return this.globalPosition.add(direction);
  14825. };
  14826. TargetCamera.prototype._getLockedTargetPosition = function () {
  14827. if (!this.lockedTarget) {
  14828. return null;
  14829. }
  14830. if (this.lockedTarget.absolutePosition) {
  14831. this.lockedTarget.computeWorldMatrix();
  14832. }
  14833. return this.lockedTarget.absolutePosition || this.lockedTarget;
  14834. };
  14835. // Cache
  14836. TargetCamera.prototype._initCache = function () {
  14837. _super.prototype._initCache.call(this);
  14838. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14839. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14840. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14841. };
  14842. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14843. if (!ignoreParentClass) {
  14844. _super.prototype._updateCache.call(this);
  14845. }
  14846. var lockedTargetPosition = this._getLockedTargetPosition();
  14847. if (!lockedTargetPosition) {
  14848. this._cache.lockedTarget = null;
  14849. }
  14850. else {
  14851. if (!this._cache.lockedTarget) {
  14852. this._cache.lockedTarget = lockedTargetPosition.clone();
  14853. }
  14854. else {
  14855. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14856. }
  14857. }
  14858. this._cache.rotation.copyFrom(this.rotation);
  14859. if (this.rotationQuaternion)
  14860. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14861. };
  14862. // Synchronized
  14863. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14864. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14865. return false;
  14866. }
  14867. var lockedTargetPosition = this._getLockedTargetPosition();
  14868. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14869. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14870. };
  14871. // Methods
  14872. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14873. var engine = this.getEngine();
  14874. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14875. };
  14876. // Target
  14877. TargetCamera.prototype.setTarget = function (target) {
  14878. this.upVector.normalize();
  14879. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14880. this._camMatrix.invert();
  14881. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14882. var vDir = target.subtract(this.position);
  14883. if (vDir.x >= 0.0) {
  14884. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14885. }
  14886. else {
  14887. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14888. }
  14889. this.rotation.z = 0;
  14890. if (isNaN(this.rotation.x)) {
  14891. this.rotation.x = 0;
  14892. }
  14893. if (isNaN(this.rotation.y)) {
  14894. this.rotation.y = 0;
  14895. }
  14896. if (isNaN(this.rotation.z)) {
  14897. this.rotation.z = 0;
  14898. }
  14899. if (this.rotationQuaternion) {
  14900. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14901. }
  14902. };
  14903. TargetCamera.prototype.getTarget = function () {
  14904. return this._currentTarget;
  14905. };
  14906. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14907. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14908. };
  14909. TargetCamera.prototype._updatePosition = function () {
  14910. this.position.addInPlace(this.cameraDirection);
  14911. };
  14912. TargetCamera.prototype._checkInputs = function () {
  14913. var needToMove = this._decideIfNeedsToMove();
  14914. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14915. // Move
  14916. if (needToMove) {
  14917. this._updatePosition();
  14918. }
  14919. // Rotate
  14920. if (needToRotate) {
  14921. this.rotation.x += this.cameraRotation.x;
  14922. this.rotation.y += this.cameraRotation.y;
  14923. if (!this.noRotationConstraint) {
  14924. var limit = (Math.PI / 2) * 0.95;
  14925. if (this.rotation.x > limit)
  14926. this.rotation.x = limit;
  14927. if (this.rotation.x < -limit)
  14928. this.rotation.x = -limit;
  14929. }
  14930. }
  14931. // Inertia
  14932. if (needToMove) {
  14933. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14934. this.cameraDirection.x = 0;
  14935. }
  14936. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14937. this.cameraDirection.y = 0;
  14938. }
  14939. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14940. this.cameraDirection.z = 0;
  14941. }
  14942. this.cameraDirection.scaleInPlace(this.inertia);
  14943. }
  14944. if (needToRotate) {
  14945. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14946. this.cameraRotation.x = 0;
  14947. }
  14948. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14949. this.cameraRotation.y = 0;
  14950. }
  14951. this.cameraRotation.scaleInPlace(this.inertia);
  14952. }
  14953. _super.prototype._checkInputs.call(this);
  14954. };
  14955. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14956. if (this.rotationQuaternion) {
  14957. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14958. //update the up vector!
  14959. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14960. }
  14961. else {
  14962. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14963. }
  14964. };
  14965. TargetCamera.prototype._getViewMatrix = function () {
  14966. if (!this.lockedTarget) {
  14967. // Compute
  14968. this._updateCameraRotationMatrix();
  14969. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14970. // Computing target and final matrix
  14971. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14972. }
  14973. else {
  14974. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14975. }
  14976. if (this.getScene().useRightHandedSystem) {
  14977. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14978. }
  14979. else {
  14980. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14981. }
  14982. return this._viewMatrix;
  14983. };
  14984. /**
  14985. * @override
  14986. * Override Camera.createRigCamera
  14987. */
  14988. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14989. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14990. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14991. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14992. if (!this.rotationQuaternion) {
  14993. this.rotationQuaternion = new BABYLON.Quaternion();
  14994. }
  14995. rigCamera._cameraRigParams = {};
  14996. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14997. }
  14998. return rigCamera;
  14999. }
  15000. return null;
  15001. };
  15002. /**
  15003. * @override
  15004. * Override Camera._updateRigCameras
  15005. */
  15006. TargetCamera.prototype._updateRigCameras = function () {
  15007. var camLeft = this._rigCameras[0];
  15008. var camRight = this._rigCameras[1];
  15009. switch (this.cameraRigMode) {
  15010. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15011. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15012. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15013. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15014. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15015. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15016. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15017. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15018. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15019. camLeft.setTarget(this.getTarget());
  15020. camRight.setTarget(this.getTarget());
  15021. break;
  15022. case BABYLON.Camera.RIG_MODE_VR:
  15023. case BABYLON.Camera.RIG_MODE_WEBVR:
  15024. if (camLeft.rotationQuaternion) {
  15025. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15026. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15027. }
  15028. else {
  15029. camLeft.rotation.copyFrom(this.rotation);
  15030. camRight.rotation.copyFrom(this.rotation);
  15031. }
  15032. camLeft.position.copyFrom(this.position);
  15033. camRight.position.copyFrom(this.position);
  15034. break;
  15035. }
  15036. _super.prototype._updateRigCameras.call(this);
  15037. };
  15038. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15039. if (!this._rigCamTransformMatrix) {
  15040. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15041. }
  15042. var target = this.getTarget();
  15043. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15044. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15045. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15046. };
  15047. TargetCamera.prototype.getClassName = function () {
  15048. return "TargetCamera";
  15049. };
  15050. __decorate([
  15051. BABYLON.serializeAsVector3()
  15052. ], TargetCamera.prototype, "rotation", void 0);
  15053. __decorate([
  15054. BABYLON.serialize()
  15055. ], TargetCamera.prototype, "speed", void 0);
  15056. __decorate([
  15057. BABYLON.serializeAsMeshReference("lockedTargetId")
  15058. ], TargetCamera.prototype, "lockedTarget", void 0);
  15059. return TargetCamera;
  15060. }(BABYLON.Camera));
  15061. BABYLON.TargetCamera = TargetCamera;
  15062. })(BABYLON || (BABYLON = {}));
  15063. //# sourceMappingURL=babylon.targetCamera.js.map
  15064. var BABYLON;
  15065. (function (BABYLON) {
  15066. var FreeCamera = (function (_super) {
  15067. __extends(FreeCamera, _super);
  15068. function FreeCamera(name, position, scene) {
  15069. var _this = this;
  15070. _super.call(this, name, position, scene);
  15071. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15072. this.checkCollisions = false;
  15073. this.applyGravity = false;
  15074. this._collider = new BABYLON.Collider();
  15075. this._needMoveForGravity = false;
  15076. this._oldPosition = BABYLON.Vector3.Zero();
  15077. this._diffPosition = BABYLON.Vector3.Zero();
  15078. this._newPosition = BABYLON.Vector3.Zero();
  15079. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15080. if (collidedMesh === void 0) { collidedMesh = null; }
  15081. //TODO move this to the collision coordinator!
  15082. if (_this.getScene().workerCollisions)
  15083. newPosition.multiplyInPlace(_this._collider.radius);
  15084. var updatePosition = function (newPos) {
  15085. _this._newPosition.copyFrom(newPos);
  15086. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15087. var oldPosition = _this.position.clone();
  15088. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15089. _this.position.addInPlace(_this._diffPosition);
  15090. if (_this.onCollide && collidedMesh) {
  15091. _this.onCollide(collidedMesh);
  15092. }
  15093. }
  15094. };
  15095. updatePosition(newPosition);
  15096. };
  15097. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  15098. this.inputs.addKeyboard().addMouse();
  15099. }
  15100. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15101. //-- begin properties for backward compatibility for inputs
  15102. get: function () {
  15103. var mouse = this.inputs.attached["mouse"];
  15104. if (mouse)
  15105. return mouse.angularSensibility;
  15106. },
  15107. set: function (value) {
  15108. var mouse = this.inputs.attached["mouse"];
  15109. if (mouse)
  15110. mouse.angularSensibility = value;
  15111. },
  15112. enumerable: true,
  15113. configurable: true
  15114. });
  15115. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15116. get: function () {
  15117. var keyboard = this.inputs.attached["keyboard"];
  15118. if (keyboard)
  15119. return keyboard.keysUp;
  15120. },
  15121. set: function (value) {
  15122. var keyboard = this.inputs.attached["keyboard"];
  15123. if (keyboard)
  15124. keyboard.keysUp = value;
  15125. },
  15126. enumerable: true,
  15127. configurable: true
  15128. });
  15129. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15130. get: function () {
  15131. var keyboard = this.inputs.attached["keyboard"];
  15132. if (keyboard)
  15133. return keyboard.keysDown;
  15134. },
  15135. set: function (value) {
  15136. var keyboard = this.inputs.attached["keyboard"];
  15137. if (keyboard)
  15138. keyboard.keysDown = value;
  15139. },
  15140. enumerable: true,
  15141. configurable: true
  15142. });
  15143. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15144. get: function () {
  15145. var keyboard = this.inputs.attached["keyboard"];
  15146. if (keyboard)
  15147. return keyboard.keysLeft;
  15148. },
  15149. set: function (value) {
  15150. var keyboard = this.inputs.attached["keyboard"];
  15151. if (keyboard)
  15152. keyboard.keysLeft = value;
  15153. },
  15154. enumerable: true,
  15155. configurable: true
  15156. });
  15157. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15158. get: function () {
  15159. var keyboard = this.inputs.attached["keyboard"];
  15160. if (keyboard)
  15161. return keyboard.keysRight;
  15162. },
  15163. set: function (value) {
  15164. var keyboard = this.inputs.attached["keyboard"];
  15165. if (keyboard)
  15166. keyboard.keysRight = value;
  15167. },
  15168. enumerable: true,
  15169. configurable: true
  15170. });
  15171. // Controls
  15172. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15173. this.inputs.attachElement(element, noPreventDefault);
  15174. };
  15175. FreeCamera.prototype.detachControl = function (element) {
  15176. this.inputs.detachElement(element);
  15177. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15178. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15179. };
  15180. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15181. var globalPosition;
  15182. if (this.parent) {
  15183. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15184. }
  15185. else {
  15186. globalPosition = this.position;
  15187. }
  15188. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15189. this._collider.radius = this.ellipsoid;
  15190. //no need for clone, as long as gravity is not on.
  15191. var actualVelocity = velocity;
  15192. //add gravity to the velocity to prevent the dual-collision checking
  15193. if (this.applyGravity) {
  15194. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15195. actualVelocity = velocity.add(this.getScene().gravity);
  15196. }
  15197. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15198. };
  15199. FreeCamera.prototype._checkInputs = function () {
  15200. if (!this._localDirection) {
  15201. this._localDirection = BABYLON.Vector3.Zero();
  15202. this._transformedDirection = BABYLON.Vector3.Zero();
  15203. }
  15204. this.inputs.checkInputs();
  15205. _super.prototype._checkInputs.call(this);
  15206. };
  15207. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15208. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15209. };
  15210. FreeCamera.prototype._updatePosition = function () {
  15211. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15212. this._collideWithWorld(this.cameraDirection);
  15213. }
  15214. else {
  15215. this.position.addInPlace(this.cameraDirection);
  15216. }
  15217. };
  15218. FreeCamera.prototype.dispose = function () {
  15219. this.inputs.clear();
  15220. _super.prototype.dispose.call(this);
  15221. };
  15222. FreeCamera.prototype.getClassName = function () {
  15223. return "FreeCamera";
  15224. };
  15225. __decorate([
  15226. BABYLON.serializeAsVector3()
  15227. ], FreeCamera.prototype, "ellipsoid", void 0);
  15228. __decorate([
  15229. BABYLON.serialize()
  15230. ], FreeCamera.prototype, "checkCollisions", void 0);
  15231. __decorate([
  15232. BABYLON.serialize()
  15233. ], FreeCamera.prototype, "applyGravity", void 0);
  15234. return FreeCamera;
  15235. }(BABYLON.TargetCamera));
  15236. BABYLON.FreeCamera = FreeCamera;
  15237. })(BABYLON || (BABYLON = {}));
  15238. //# sourceMappingURL=babylon.freeCamera.js.map
  15239. var BABYLON;
  15240. (function (BABYLON) {
  15241. var FreeCameraInputsManager = (function (_super) {
  15242. __extends(FreeCameraInputsManager, _super);
  15243. function FreeCameraInputsManager(camera) {
  15244. _super.call(this, camera);
  15245. }
  15246. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15247. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15248. return this;
  15249. };
  15250. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15251. if (touchEnabled === void 0) { touchEnabled = true; }
  15252. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15253. return this;
  15254. };
  15255. FreeCameraInputsManager.prototype.addGamepad = function () {
  15256. this.add(new BABYLON.FreeCameraGamepadInput());
  15257. return this;
  15258. };
  15259. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15260. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15261. return this;
  15262. };
  15263. FreeCameraInputsManager.prototype.addTouch = function () {
  15264. this.add(new BABYLON.FreeCameraTouchInput());
  15265. return this;
  15266. };
  15267. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15268. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15269. return this;
  15270. };
  15271. return FreeCameraInputsManager;
  15272. }(BABYLON.CameraInputsManager));
  15273. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15274. })(BABYLON || (BABYLON = {}));
  15275. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  15276. var BABYLON;
  15277. (function (BABYLON) {
  15278. var FollowCamera = (function (_super) {
  15279. __extends(FollowCamera, _super);
  15280. function FollowCamera(name, position, scene, lockedTarget) {
  15281. _super.call(this, name, position, scene);
  15282. this.radius = 12;
  15283. this.rotationOffset = 0;
  15284. this.heightOffset = 4;
  15285. this.cameraAcceleration = 0.05;
  15286. this.maxCameraSpeed = 20;
  15287. this.lockedTarget = lockedTarget;
  15288. }
  15289. FollowCamera.prototype.getRadians = function (degrees) {
  15290. return degrees * Math.PI / 180;
  15291. };
  15292. FollowCamera.prototype.follow = function (cameraTarget) {
  15293. if (!cameraTarget)
  15294. return;
  15295. var yRotation;
  15296. if (cameraTarget.rotationQuaternion) {
  15297. var rotMatrix = new BABYLON.Matrix();
  15298. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15299. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15300. }
  15301. else {
  15302. yRotation = cameraTarget.rotation.y;
  15303. }
  15304. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15305. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15306. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15307. var dx = targetX - this.position.x;
  15308. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15309. var dz = (targetZ) - this.position.z;
  15310. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15311. var vy = dy * this.cameraAcceleration;
  15312. var vz = dz * this.cameraAcceleration * 2;
  15313. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15314. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15315. }
  15316. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15317. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15318. }
  15319. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15320. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15321. }
  15322. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15323. this.setTarget(cameraTarget.position);
  15324. };
  15325. FollowCamera.prototype._checkInputs = function () {
  15326. _super.prototype._checkInputs.call(this);
  15327. this.follow(this.lockedTarget);
  15328. };
  15329. FollowCamera.prototype.getClassName = function () {
  15330. return "FollowCamera";
  15331. };
  15332. __decorate([
  15333. BABYLON.serialize()
  15334. ], FollowCamera.prototype, "radius", void 0);
  15335. __decorate([
  15336. BABYLON.serialize()
  15337. ], FollowCamera.prototype, "rotationOffset", void 0);
  15338. __decorate([
  15339. BABYLON.serialize()
  15340. ], FollowCamera.prototype, "heightOffset", void 0);
  15341. __decorate([
  15342. BABYLON.serialize()
  15343. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15344. __decorate([
  15345. BABYLON.serialize()
  15346. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15347. __decorate([
  15348. BABYLON.serializeAsMeshReference("lockedTargetId")
  15349. ], FollowCamera.prototype, "lockedTarget", void 0);
  15350. return FollowCamera;
  15351. }(BABYLON.TargetCamera));
  15352. BABYLON.FollowCamera = FollowCamera;
  15353. var ArcFollowCamera = (function (_super) {
  15354. __extends(ArcFollowCamera, _super);
  15355. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15356. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15357. this.alpha = alpha;
  15358. this.beta = beta;
  15359. this.radius = radius;
  15360. this.target = target;
  15361. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15362. this.follow();
  15363. }
  15364. ArcFollowCamera.prototype.follow = function () {
  15365. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15366. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15367. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15368. this.position = this.target.position.add(this._cartesianCoordinates);
  15369. this.setTarget(this.target.position);
  15370. };
  15371. ArcFollowCamera.prototype._checkInputs = function () {
  15372. _super.prototype._checkInputs.call(this);
  15373. this.follow();
  15374. };
  15375. ArcFollowCamera.prototype.getClassName = function () {
  15376. return "ArcFollowCamera";
  15377. };
  15378. return ArcFollowCamera;
  15379. }(BABYLON.TargetCamera));
  15380. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15381. })(BABYLON || (BABYLON = {}));
  15382. //# sourceMappingURL=babylon.followCamera.js.map
  15383. var BABYLON;
  15384. (function (BABYLON) {
  15385. // We're mainly based on the logic defined into the FreeCamera code
  15386. var TouchCamera = (function (_super) {
  15387. __extends(TouchCamera, _super);
  15388. //-- end properties for backward compatibility for inputs
  15389. function TouchCamera(name, position, scene) {
  15390. _super.call(this, name, position, scene);
  15391. this.inputs.addTouch();
  15392. this._setupInputs();
  15393. }
  15394. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15395. //-- Begin properties for backward compatibility for inputs
  15396. get: function () {
  15397. var touch = this.inputs.attached["touch"];
  15398. if (touch)
  15399. return touch.touchAngularSensibility;
  15400. },
  15401. set: function (value) {
  15402. var touch = this.inputs.attached["touch"];
  15403. if (touch)
  15404. touch.touchAngularSensibility = value;
  15405. },
  15406. enumerable: true,
  15407. configurable: true
  15408. });
  15409. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15410. get: function () {
  15411. var touch = this.inputs.attached["touch"];
  15412. if (touch)
  15413. return touch.touchMoveSensibility;
  15414. },
  15415. set: function (value) {
  15416. var touch = this.inputs.attached["touch"];
  15417. if (touch)
  15418. touch.touchMoveSensibility = value;
  15419. },
  15420. enumerable: true,
  15421. configurable: true
  15422. });
  15423. TouchCamera.prototype.getClassName = function () {
  15424. return "TouchCamera";
  15425. };
  15426. TouchCamera.prototype._setupInputs = function () {
  15427. var mouse = this.inputs.attached["mouse"];
  15428. if (mouse) {
  15429. mouse.touchEnabled = false;
  15430. }
  15431. };
  15432. return TouchCamera;
  15433. }(BABYLON.FreeCamera));
  15434. BABYLON.TouchCamera = TouchCamera;
  15435. })(BABYLON || (BABYLON = {}));
  15436. //# sourceMappingURL=babylon.touchCamera.js.map
  15437. var BABYLON;
  15438. (function (BABYLON) {
  15439. var ArcRotateCamera = (function (_super) {
  15440. __extends(ArcRotateCamera, _super);
  15441. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15442. var _this = this;
  15443. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15444. this.inertialAlphaOffset = 0;
  15445. this.inertialBetaOffset = 0;
  15446. this.inertialRadiusOffset = 0;
  15447. this.lowerAlphaLimit = null;
  15448. this.upperAlphaLimit = null;
  15449. this.lowerBetaLimit = 0.01;
  15450. this.upperBetaLimit = Math.PI;
  15451. this.lowerRadiusLimit = null;
  15452. this.upperRadiusLimit = null;
  15453. this.inertialPanningX = 0;
  15454. this.inertialPanningY = 0;
  15455. //-- end properties for backward compatibility for inputs
  15456. this.zoomOnFactor = 1;
  15457. this.targetScreenOffset = BABYLON.Vector2.Zero();
  15458. this.allowUpsideDown = true;
  15459. this._viewMatrix = new BABYLON.Matrix();
  15460. // Panning
  15461. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15462. this.checkCollisions = false;
  15463. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15464. this._collider = new BABYLON.Collider();
  15465. this._previousPosition = BABYLON.Vector3.Zero();
  15466. this._collisionVelocity = BABYLON.Vector3.Zero();
  15467. this._newPosition = BABYLON.Vector3.Zero();
  15468. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15469. if (collidedMesh === void 0) { collidedMesh = null; }
  15470. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15471. newPosition.multiplyInPlace(_this._collider.radius);
  15472. }
  15473. if (!collidedMesh) {
  15474. _this._previousPosition.copyFrom(_this.position);
  15475. }
  15476. else {
  15477. _this.setPosition(newPosition);
  15478. if (_this.onCollide) {
  15479. _this.onCollide(collidedMesh);
  15480. }
  15481. }
  15482. // Recompute because of constraints
  15483. var cosa = Math.cos(_this.alpha);
  15484. var sina = Math.sin(_this.alpha);
  15485. var cosb = Math.cos(_this.beta);
  15486. var sinb = Math.sin(_this.beta);
  15487. if (sinb === 0) {
  15488. sinb = 0.0001;
  15489. }
  15490. var target = _this._getTargetPosition();
  15491. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15492. _this.position.copyFrom(_this._newPosition);
  15493. var up = _this.upVector;
  15494. if (_this.allowUpsideDown && _this.beta < 0) {
  15495. up = up.clone();
  15496. up = up.negate();
  15497. }
  15498. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15499. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15500. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15501. _this._collisionTriggered = false;
  15502. };
  15503. if (!target) {
  15504. this.target = BABYLON.Vector3.Zero();
  15505. }
  15506. else {
  15507. this.target = target;
  15508. }
  15509. this.alpha = alpha;
  15510. this.beta = beta;
  15511. this.radius = radius;
  15512. this.getViewMatrix();
  15513. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15514. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15515. }
  15516. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15517. //-- begin properties for backward compatibility for inputs
  15518. get: function () {
  15519. var pointers = this.inputs.attached["pointers"];
  15520. if (pointers)
  15521. return pointers.angularSensibilityX;
  15522. },
  15523. set: function (value) {
  15524. var pointers = this.inputs.attached["pointers"];
  15525. if (pointers) {
  15526. pointers.angularSensibilityX = value;
  15527. }
  15528. },
  15529. enumerable: true,
  15530. configurable: true
  15531. });
  15532. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15533. get: function () {
  15534. var pointers = this.inputs.attached["pointers"];
  15535. if (pointers)
  15536. return pointers.angularSensibilityY;
  15537. },
  15538. set: function (value) {
  15539. var pointers = this.inputs.attached["pointers"];
  15540. if (pointers) {
  15541. pointers.angularSensibilityY = value;
  15542. }
  15543. },
  15544. enumerable: true,
  15545. configurable: true
  15546. });
  15547. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15548. get: function () {
  15549. var pointers = this.inputs.attached["pointers"];
  15550. if (pointers)
  15551. return pointers.pinchPrecision;
  15552. },
  15553. set: function (value) {
  15554. var pointers = this.inputs.attached["pointers"];
  15555. if (pointers) {
  15556. pointers.pinchPrecision = value;
  15557. }
  15558. },
  15559. enumerable: true,
  15560. configurable: true
  15561. });
  15562. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15563. get: function () {
  15564. var pointers = this.inputs.attached["pointers"];
  15565. if (pointers)
  15566. return pointers.panningSensibility;
  15567. },
  15568. set: function (value) {
  15569. var pointers = this.inputs.attached["pointers"];
  15570. if (pointers) {
  15571. pointers.panningSensibility = value;
  15572. }
  15573. },
  15574. enumerable: true,
  15575. configurable: true
  15576. });
  15577. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15578. get: function () {
  15579. var keyboard = this.inputs.attached["keyboard"];
  15580. if (keyboard)
  15581. return keyboard.keysUp;
  15582. },
  15583. set: function (value) {
  15584. var keyboard = this.inputs.attached["keyboard"];
  15585. if (keyboard)
  15586. keyboard.keysUp = value;
  15587. },
  15588. enumerable: true,
  15589. configurable: true
  15590. });
  15591. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15592. get: function () {
  15593. var keyboard = this.inputs.attached["keyboard"];
  15594. if (keyboard)
  15595. return keyboard.keysDown;
  15596. },
  15597. set: function (value) {
  15598. var keyboard = this.inputs.attached["keyboard"];
  15599. if (keyboard)
  15600. keyboard.keysDown = value;
  15601. },
  15602. enumerable: true,
  15603. configurable: true
  15604. });
  15605. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15606. get: function () {
  15607. var keyboard = this.inputs.attached["keyboard"];
  15608. if (keyboard)
  15609. return keyboard.keysLeft;
  15610. },
  15611. set: function (value) {
  15612. var keyboard = this.inputs.attached["keyboard"];
  15613. if (keyboard)
  15614. keyboard.keysLeft = value;
  15615. },
  15616. enumerable: true,
  15617. configurable: true
  15618. });
  15619. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15620. get: function () {
  15621. var keyboard = this.inputs.attached["keyboard"];
  15622. if (keyboard)
  15623. return keyboard.keysRight;
  15624. },
  15625. set: function (value) {
  15626. var keyboard = this.inputs.attached["keyboard"];
  15627. if (keyboard)
  15628. keyboard.keysRight = value;
  15629. },
  15630. enumerable: true,
  15631. configurable: true
  15632. });
  15633. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15634. get: function () {
  15635. var mousewheel = this.inputs.attached["mousewheel"];
  15636. if (mousewheel)
  15637. return mousewheel.wheelPrecision;
  15638. },
  15639. set: function (value) {
  15640. var mousewheel = this.inputs.attached["mousewheel"];
  15641. if (mousewheel)
  15642. mousewheel.wheelPrecision = value;
  15643. },
  15644. enumerable: true,
  15645. configurable: true
  15646. });
  15647. // Cache
  15648. ArcRotateCamera.prototype._initCache = function () {
  15649. _super.prototype._initCache.call(this);
  15650. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15651. this._cache.alpha = undefined;
  15652. this._cache.beta = undefined;
  15653. this._cache.radius = undefined;
  15654. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15655. };
  15656. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15657. if (!ignoreParentClass) {
  15658. _super.prototype._updateCache.call(this);
  15659. }
  15660. this._cache.target.copyFrom(this._getTargetPosition());
  15661. this._cache.alpha = this.alpha;
  15662. this._cache.beta = this.beta;
  15663. this._cache.radius = this.radius;
  15664. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15665. };
  15666. ArcRotateCamera.prototype._getTargetPosition = function () {
  15667. if (this.target.getAbsolutePosition) {
  15668. var pos = this.target.getAbsolutePosition();
  15669. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15670. }
  15671. return this.target;
  15672. };
  15673. // Synchronized
  15674. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15675. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15676. return false;
  15677. return this._cache.target.equals(this.target)
  15678. && this._cache.alpha === this.alpha
  15679. && this._cache.beta === this.beta
  15680. && this._cache.radius === this.radius
  15681. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15682. };
  15683. // Methods
  15684. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15685. var _this = this;
  15686. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15687. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15688. this._useCtrlForPanning = useCtrlForPanning;
  15689. this._panningMouseButton = panningMouseButton;
  15690. this.inputs.attachElement(element, noPreventDefault);
  15691. this._reset = function () {
  15692. _this.inertialAlphaOffset = 0;
  15693. _this.inertialBetaOffset = 0;
  15694. _this.inertialRadiusOffset = 0;
  15695. };
  15696. };
  15697. ArcRotateCamera.prototype.detachControl = function (element) {
  15698. this.inputs.detachElement(element);
  15699. if (this._reset) {
  15700. this._reset();
  15701. }
  15702. };
  15703. ArcRotateCamera.prototype._checkInputs = function () {
  15704. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15705. if (this._collisionTriggered) {
  15706. return;
  15707. }
  15708. this.inputs.checkInputs();
  15709. // Inertia
  15710. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15711. if (this.getScene().useRightHandedSystem) {
  15712. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15713. }
  15714. else {
  15715. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15716. }
  15717. this.beta += this.inertialBetaOffset;
  15718. this.radius -= this.inertialRadiusOffset;
  15719. this.inertialAlphaOffset *= this.inertia;
  15720. this.inertialBetaOffset *= this.inertia;
  15721. this.inertialRadiusOffset *= this.inertia;
  15722. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15723. this.inertialAlphaOffset = 0;
  15724. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15725. this.inertialBetaOffset = 0;
  15726. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15727. this.inertialRadiusOffset = 0;
  15728. }
  15729. // Panning inertia
  15730. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15731. if (!this._localDirection) {
  15732. this._localDirection = BABYLON.Vector3.Zero();
  15733. this._transformedDirection = BABYLON.Vector3.Zero();
  15734. }
  15735. this.inertialPanningX *= this.inertia;
  15736. this.inertialPanningY *= this.inertia;
  15737. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15738. this.inertialPanningX = 0;
  15739. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15740. this.inertialPanningY = 0;
  15741. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15742. this._localDirection.multiplyInPlace(this.panningAxis);
  15743. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15744. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15745. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15746. if (!this.panningAxis.y) {
  15747. this._transformedDirection.y = 0;
  15748. }
  15749. if (!this.target.getAbsolutePosition) {
  15750. this.target.addInPlace(this._transformedDirection);
  15751. }
  15752. }
  15753. // Limits
  15754. this._checkLimits();
  15755. _super.prototype._checkInputs.call(this);
  15756. };
  15757. ArcRotateCamera.prototype._checkLimits = function () {
  15758. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15759. if (this.allowUpsideDown && this.beta > Math.PI) {
  15760. this.beta = this.beta - (2 * Math.PI);
  15761. }
  15762. }
  15763. else {
  15764. if (this.beta < this.lowerBetaLimit) {
  15765. this.beta = this.lowerBetaLimit;
  15766. }
  15767. }
  15768. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15769. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15770. this.beta = this.beta + (2 * Math.PI);
  15771. }
  15772. }
  15773. else {
  15774. if (this.beta > this.upperBetaLimit) {
  15775. this.beta = this.upperBetaLimit;
  15776. }
  15777. }
  15778. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15779. this.alpha = this.lowerAlphaLimit;
  15780. }
  15781. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15782. this.alpha = this.upperAlphaLimit;
  15783. }
  15784. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15785. this.radius = this.lowerRadiusLimit;
  15786. }
  15787. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15788. this.radius = this.upperRadiusLimit;
  15789. }
  15790. };
  15791. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15792. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15793. this.radius = radiusv3.length();
  15794. // Alpha
  15795. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15796. if (radiusv3.z < 0) {
  15797. this.alpha = 2 * Math.PI - this.alpha;
  15798. }
  15799. // Beta
  15800. this.beta = Math.acos(radiusv3.y / this.radius);
  15801. this._checkLimits();
  15802. };
  15803. ArcRotateCamera.prototype.setPosition = function (position) {
  15804. if (this.position.equals(position)) {
  15805. return;
  15806. }
  15807. this.position.copyFrom(position);
  15808. this.rebuildAnglesAndRadius();
  15809. };
  15810. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15811. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15812. if (this._getTargetPosition().equals(target)) {
  15813. return;
  15814. }
  15815. if (toBoundingCenter && target.getBoundingInfo) {
  15816. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15817. }
  15818. else {
  15819. this._targetBoundingCenter = null;
  15820. }
  15821. this.target = target;
  15822. this.rebuildAnglesAndRadius();
  15823. };
  15824. ArcRotateCamera.prototype._getViewMatrix = function () {
  15825. // Compute
  15826. var cosa = Math.cos(this.alpha);
  15827. var sina = Math.sin(this.alpha);
  15828. var cosb = Math.cos(this.beta);
  15829. var sinb = Math.sin(this.beta);
  15830. if (sinb === 0) {
  15831. sinb = 0.0001;
  15832. }
  15833. var target = this._getTargetPosition();
  15834. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15835. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15836. this._collider.radius = this.collisionRadius;
  15837. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15838. this._collisionTriggered = true;
  15839. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15840. }
  15841. else {
  15842. this.position.copyFrom(this._newPosition);
  15843. var up = this.upVector;
  15844. if (this.allowUpsideDown && this.beta < 0) {
  15845. up = up.clone();
  15846. up = up.negate();
  15847. }
  15848. if (this.getScene().useRightHandedSystem) {
  15849. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15850. }
  15851. else {
  15852. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15853. }
  15854. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15855. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15856. }
  15857. this._currentTarget = target;
  15858. return this._viewMatrix;
  15859. };
  15860. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15861. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15862. meshes = meshes || this.getScene().meshes;
  15863. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15864. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15865. this.radius = distance * this.zoomOnFactor;
  15866. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15867. };
  15868. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15869. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15870. var meshesOrMinMaxVector;
  15871. var distance;
  15872. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15873. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15874. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15875. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15876. }
  15877. else {
  15878. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15879. distance = meshesOrMinMaxVectorAndDistance.distance;
  15880. }
  15881. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15882. if (!doNotUpdateMaxZ) {
  15883. this.maxZ = distance * 2;
  15884. }
  15885. };
  15886. /**
  15887. * @override
  15888. * Override Camera.createRigCamera
  15889. */
  15890. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15891. var alphaShift;
  15892. switch (this.cameraRigMode) {
  15893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15895. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15896. case BABYLON.Camera.RIG_MODE_VR:
  15897. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15898. break;
  15899. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15900. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15901. break;
  15902. }
  15903. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15904. rigCam._cameraRigParams = {};
  15905. return rigCam;
  15906. };
  15907. /**
  15908. * @override
  15909. * Override Camera._updateRigCameras
  15910. */
  15911. ArcRotateCamera.prototype._updateRigCameras = function () {
  15912. var camLeft = this._rigCameras[0];
  15913. var camRight = this._rigCameras[1];
  15914. camLeft.beta = camRight.beta = this.beta;
  15915. camLeft.radius = camRight.radius = this.radius;
  15916. switch (this.cameraRigMode) {
  15917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15919. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15920. case BABYLON.Camera.RIG_MODE_VR:
  15921. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15922. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15923. break;
  15924. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15925. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15926. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15927. break;
  15928. }
  15929. _super.prototype._updateRigCameras.call(this);
  15930. };
  15931. ArcRotateCamera.prototype.dispose = function () {
  15932. this.inputs.clear();
  15933. _super.prototype.dispose.call(this);
  15934. };
  15935. ArcRotateCamera.prototype.getClassName = function () {
  15936. return "ArcRotateCamera";
  15937. };
  15938. __decorate([
  15939. BABYLON.serialize()
  15940. ], ArcRotateCamera.prototype, "alpha", void 0);
  15941. __decorate([
  15942. BABYLON.serialize()
  15943. ], ArcRotateCamera.prototype, "beta", void 0);
  15944. __decorate([
  15945. BABYLON.serialize()
  15946. ], ArcRotateCamera.prototype, "radius", void 0);
  15947. __decorate([
  15948. BABYLON.serializeAsVector3()
  15949. ], ArcRotateCamera.prototype, "target", void 0);
  15950. __decorate([
  15951. BABYLON.serialize()
  15952. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15953. __decorate([
  15954. BABYLON.serialize()
  15955. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15956. __decorate([
  15957. BABYLON.serialize()
  15958. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15959. __decorate([
  15960. BABYLON.serialize()
  15961. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15962. __decorate([
  15963. BABYLON.serialize()
  15964. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15965. __decorate([
  15966. BABYLON.serialize()
  15967. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15968. __decorate([
  15969. BABYLON.serialize()
  15970. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15971. __decorate([
  15972. BABYLON.serialize()
  15973. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15974. __decorate([
  15975. BABYLON.serialize()
  15976. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15977. __decorate([
  15978. BABYLON.serialize()
  15979. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15980. __decorate([
  15981. BABYLON.serialize()
  15982. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15983. __decorate([
  15984. BABYLON.serialize()
  15985. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15986. __decorate([
  15987. BABYLON.serialize()
  15988. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15989. return ArcRotateCamera;
  15990. }(BABYLON.TargetCamera));
  15991. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15992. })(BABYLON || (BABYLON = {}));
  15993. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  15994. var BABYLON;
  15995. (function (BABYLON) {
  15996. var ArcRotateCameraInputsManager = (function (_super) {
  15997. __extends(ArcRotateCameraInputsManager, _super);
  15998. function ArcRotateCameraInputsManager(camera) {
  15999. _super.call(this, camera);
  16000. }
  16001. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  16002. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  16003. return this;
  16004. };
  16005. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16006. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16007. return this;
  16008. };
  16009. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16010. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16011. return this;
  16012. };
  16013. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16014. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16015. return this;
  16016. };
  16017. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16018. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16019. return this;
  16020. };
  16021. return ArcRotateCameraInputsManager;
  16022. }(BABYLON.CameraInputsManager));
  16023. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16024. })(BABYLON || (BABYLON = {}));
  16025. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16026. var BABYLON;
  16027. (function (BABYLON) {
  16028. var RenderingManager = (function () {
  16029. function RenderingManager(scene) {
  16030. this._renderingGroups = new Array();
  16031. this._autoClearDepthStencil = {};
  16032. this._customOpaqueSortCompareFn = {};
  16033. this._customAlphaTestSortCompareFn = {};
  16034. this._customTransparentSortCompareFn = {};
  16035. this._renderinGroupInfo = null;
  16036. this._scene = scene;
  16037. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16038. this._autoClearDepthStencil[i] = true;
  16039. }
  16040. }
  16041. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  16042. if (this._scene._activeParticleSystems.length === 0) {
  16043. return;
  16044. }
  16045. // Particles
  16046. var activeCamera = this._scene.activeCamera;
  16047. this._scene._particlesDuration.beginMonitoring();
  16048. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16049. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16050. if (particleSystem.renderingGroupId !== index) {
  16051. continue;
  16052. }
  16053. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16054. continue;
  16055. }
  16056. this._clearDepthStencilBuffer();
  16057. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  16058. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16059. }
  16060. }
  16061. this._scene._particlesDuration.endMonitoring(false);
  16062. };
  16063. RenderingManager.prototype._renderSprites = function (index) {
  16064. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  16065. return;
  16066. }
  16067. // Sprites
  16068. var activeCamera = this._scene.activeCamera;
  16069. this._scene._spritesDuration.beginMonitoring();
  16070. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  16071. var spriteManager = this._scene.spriteManagers[id];
  16072. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16073. this._clearDepthStencilBuffer();
  16074. spriteManager.render();
  16075. }
  16076. }
  16077. this._scene._spritesDuration.endMonitoring(false);
  16078. };
  16079. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  16080. if (this._depthStencilBufferAlreadyCleaned) {
  16081. return;
  16082. }
  16083. this._scene.getEngine().clear(0, false, true, true);
  16084. this._depthStencilBufferAlreadyCleaned = true;
  16085. };
  16086. RenderingManager.prototype._renderSpritesAndParticles = function () {
  16087. if (this._currentRenderSprites) {
  16088. this._renderSprites(this._currentIndex);
  16089. }
  16090. if (this._currentRenderParticles) {
  16091. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  16092. }
  16093. };
  16094. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16095. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16096. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16097. var info = null;
  16098. if (observable) {
  16099. if (!this._renderinGroupInfo) {
  16100. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16101. }
  16102. info = this._renderinGroupInfo;
  16103. info.scene = this._scene;
  16104. info.camera = this._scene.activeCamera;
  16105. }
  16106. this._currentActiveMeshes = activeMeshes;
  16107. this._currentRenderParticles = renderParticles;
  16108. this._currentRenderSprites = renderSprites;
  16109. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16110. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16111. var renderingGroup = this._renderingGroups[index];
  16112. this._currentIndex = index;
  16113. if (renderingGroup) {
  16114. var renderingGroupMask = 0;
  16115. // Fire PRECLEAR stage
  16116. if (observable) {
  16117. renderingGroupMask = Math.pow(2, index);
  16118. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16119. info.renderingGroupId = index;
  16120. observable.notifyObservers(info, renderingGroupMask);
  16121. }
  16122. // Clear depth/stencil if needed
  16123. if (this._autoClearDepthStencil[index]) {
  16124. this._clearDepthStencilBuffer();
  16125. }
  16126. // Fire PREOPAQUE stage
  16127. if (observable) {
  16128. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16129. observable.notifyObservers(info, renderingGroupMask);
  16130. }
  16131. if (!renderingGroup.onBeforeTransparentRendering) {
  16132. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  16133. }
  16134. // Fire PRETRANSPARENT stage
  16135. if (observable) {
  16136. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16137. observable.notifyObservers(info, renderingGroupMask);
  16138. }
  16139. renderingGroup.render(customRenderFunction);
  16140. // Fire POSTTRANSPARENT stage
  16141. if (observable) {
  16142. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16143. observable.notifyObservers(info, renderingGroupMask);
  16144. }
  16145. }
  16146. else {
  16147. this._renderSpritesAndParticles();
  16148. if (observable) {
  16149. var renderingGroupMask = Math.pow(2, index);
  16150. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16151. info.renderingGroupId = index;
  16152. observable.notifyObservers(info, renderingGroupMask);
  16153. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16154. observable.notifyObservers(info, renderingGroupMask);
  16155. }
  16156. }
  16157. }
  16158. };
  16159. RenderingManager.prototype.reset = function () {
  16160. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16161. var renderingGroup = this._renderingGroups[index];
  16162. if (renderingGroup) {
  16163. renderingGroup.prepare();
  16164. }
  16165. }
  16166. };
  16167. RenderingManager.prototype.dispatch = function (subMesh) {
  16168. var mesh = subMesh.getMesh();
  16169. var renderingGroupId = mesh.renderingGroupId || 0;
  16170. if (!this._renderingGroups[renderingGroupId]) {
  16171. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16172. }
  16173. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16174. };
  16175. /**
  16176. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16177. * This allowed control for front to back rendering or reversly depending of the special needs.
  16178. *
  16179. * @param renderingGroupId The rendering group id corresponding to its index
  16180. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16181. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16182. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16183. */
  16184. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16185. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16186. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16187. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16188. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16189. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16190. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16191. if (this._renderingGroups[renderingGroupId]) {
  16192. var group = this._renderingGroups[renderingGroupId];
  16193. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16194. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16195. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16196. }
  16197. };
  16198. /**
  16199. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16200. *
  16201. * @param renderingGroupId The rendering group id corresponding to its index
  16202. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16203. */
  16204. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  16205. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  16206. };
  16207. /**
  16208. * The max id used for rendering groups (not included)
  16209. */
  16210. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16211. /**
  16212. * The min id used for rendering groups (included)
  16213. */
  16214. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16215. return RenderingManager;
  16216. }());
  16217. BABYLON.RenderingManager = RenderingManager;
  16218. })(BABYLON || (BABYLON = {}));
  16219. //# sourceMappingURL=babylon.renderingManager.js.map
  16220. var BABYLON;
  16221. (function (BABYLON) {
  16222. var RenderingGroup = (function () {
  16223. /**
  16224. * Creates a new rendering group.
  16225. * @param index The rendering group index
  16226. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16227. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16228. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16229. */
  16230. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16231. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16232. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16233. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16234. this.index = index;
  16235. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16236. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16237. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16238. this._scene = scene;
  16239. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16240. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16241. this.transparentSortCompareFn = transparentSortCompareFn;
  16242. }
  16243. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16244. /**
  16245. * Set the opaque sort comparison function.
  16246. * If null the sub meshes will be render in the order they were created
  16247. */
  16248. set: function (value) {
  16249. this._opaqueSortCompareFn = value;
  16250. if (value) {
  16251. this._renderOpaque = this.renderOpaqueSorted;
  16252. }
  16253. else {
  16254. this._renderOpaque = RenderingGroup.renderUnsorted;
  16255. }
  16256. },
  16257. enumerable: true,
  16258. configurable: true
  16259. });
  16260. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16261. /**
  16262. * Set the alpha test sort comparison function.
  16263. * If null the sub meshes will be render in the order they were created
  16264. */
  16265. set: function (value) {
  16266. this._alphaTestSortCompareFn = value;
  16267. if (value) {
  16268. this._renderAlphaTest = this.renderAlphaTestSorted;
  16269. }
  16270. else {
  16271. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16272. }
  16273. },
  16274. enumerable: true,
  16275. configurable: true
  16276. });
  16277. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16278. /**
  16279. * Set the transparent sort comparison function.
  16280. * If null the sub meshes will be render in the order they were created
  16281. */
  16282. set: function (value) {
  16283. if (value) {
  16284. this._transparentSortCompareFn = value;
  16285. }
  16286. else {
  16287. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16288. }
  16289. this._renderTransparent = this.renderTransparentSorted;
  16290. },
  16291. enumerable: true,
  16292. configurable: true
  16293. });
  16294. /**
  16295. * Render all the sub meshes contained in the group.
  16296. * @param customRenderFunction Used to override the default render behaviour of the group.
  16297. * @returns true if rendered some submeshes.
  16298. */
  16299. RenderingGroup.prototype.render = function (customRenderFunction) {
  16300. if (customRenderFunction) {
  16301. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16302. return;
  16303. }
  16304. var engine = this._scene.getEngine();
  16305. // Opaque
  16306. if (this._opaqueSubMeshes.length !== 0) {
  16307. this._renderOpaque(this._opaqueSubMeshes);
  16308. }
  16309. // Alpha test
  16310. if (this._alphaTestSubMeshes.length !== 0) {
  16311. engine.setAlphaTesting(true);
  16312. this._renderAlphaTest(this._alphaTestSubMeshes);
  16313. engine.setAlphaTesting(false);
  16314. }
  16315. if (this.onBeforeTransparentRendering) {
  16316. this.onBeforeTransparentRendering();
  16317. }
  16318. // Transparent
  16319. if (this._transparentSubMeshes.length !== 0) {
  16320. this._renderTransparent(this._transparentSubMeshes);
  16321. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16322. }
  16323. };
  16324. /**
  16325. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16326. * @param subMeshes The submeshes to render
  16327. */
  16328. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16329. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16330. };
  16331. /**
  16332. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16333. * @param subMeshes The submeshes to render
  16334. */
  16335. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16336. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16337. };
  16338. /**
  16339. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16340. * @param subMeshes The submeshes to render
  16341. */
  16342. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16343. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16344. };
  16345. /**
  16346. * Renders the submeshes in a specified order.
  16347. * @param subMeshes The submeshes to sort before render
  16348. * @param sortCompareFn The comparison function use to sort
  16349. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16350. * @param transparent Specifies to activate blending if true
  16351. */
  16352. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16353. var subIndex = 0;
  16354. var subMesh;
  16355. for (; subIndex < subMeshes.length; subIndex++) {
  16356. subMesh = subMeshes.data[subIndex];
  16357. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16358. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16359. }
  16360. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16361. sortedArray.sort(sortCompareFn);
  16362. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16363. subMesh = sortedArray[subIndex];
  16364. subMesh.render(transparent);
  16365. }
  16366. };
  16367. /**
  16368. * Renders the submeshes in the order they were dispatched (no sort applied).
  16369. * @param subMeshes The submeshes to render
  16370. */
  16371. RenderingGroup.renderUnsorted = function (subMeshes) {
  16372. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16373. var submesh = subMeshes.data[subIndex];
  16374. submesh.render(false);
  16375. }
  16376. };
  16377. /**
  16378. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16379. * are rendered back to front if in the same alpha index.
  16380. *
  16381. * @param a The first submesh
  16382. * @param b The second submesh
  16383. * @returns The result of the comparison
  16384. */
  16385. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16386. // Alpha index first
  16387. if (a._alphaIndex > b._alphaIndex) {
  16388. return 1;
  16389. }
  16390. if (a._alphaIndex < b._alphaIndex) {
  16391. return -1;
  16392. }
  16393. // Then distance to camera
  16394. return RenderingGroup.backToFrontSortCompare(a, b);
  16395. };
  16396. /**
  16397. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16398. * are rendered back to front.
  16399. *
  16400. * @param a The first submesh
  16401. * @param b The second submesh
  16402. * @returns The result of the comparison
  16403. */
  16404. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16405. // Then distance to camera
  16406. if (a._distanceToCamera < b._distanceToCamera) {
  16407. return 1;
  16408. }
  16409. if (a._distanceToCamera > b._distanceToCamera) {
  16410. return -1;
  16411. }
  16412. return 0;
  16413. };
  16414. /**
  16415. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16416. * are rendered front to back (prevent overdraw).
  16417. *
  16418. * @param a The first submesh
  16419. * @param b The second submesh
  16420. * @returns The result of the comparison
  16421. */
  16422. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16423. // Then distance to camera
  16424. if (a._distanceToCamera < b._distanceToCamera) {
  16425. return -1;
  16426. }
  16427. if (a._distanceToCamera > b._distanceToCamera) {
  16428. return 1;
  16429. }
  16430. return 0;
  16431. };
  16432. /**
  16433. * Resets the different lists of submeshes to prepare a new frame.
  16434. */
  16435. RenderingGroup.prototype.prepare = function () {
  16436. this._opaqueSubMeshes.reset();
  16437. this._transparentSubMeshes.reset();
  16438. this._alphaTestSubMeshes.reset();
  16439. };
  16440. /**
  16441. * Inserts the submesh in its correct queue depending on its material.
  16442. * @param subMesh The submesh to dispatch
  16443. */
  16444. RenderingGroup.prototype.dispatch = function (subMesh) {
  16445. var material = subMesh.getMaterial();
  16446. var mesh = subMesh.getMesh();
  16447. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16448. this._transparentSubMeshes.push(subMesh);
  16449. }
  16450. else if (material.needAlphaTesting()) {
  16451. this._alphaTestSubMeshes.push(subMesh);
  16452. }
  16453. else {
  16454. this._opaqueSubMeshes.push(subMesh); // Opaque
  16455. }
  16456. };
  16457. return RenderingGroup;
  16458. }());
  16459. BABYLON.RenderingGroup = RenderingGroup;
  16460. })(BABYLON || (BABYLON = {}));
  16461. //# sourceMappingURL=babylon.renderingGroup.js.map
  16462. var BABYLON;
  16463. (function (BABYLON) {
  16464. var PointerEventTypes = (function () {
  16465. function PointerEventTypes() {
  16466. }
  16467. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16468. get: function () {
  16469. return PointerEventTypes._POINTERDOWN;
  16470. },
  16471. enumerable: true,
  16472. configurable: true
  16473. });
  16474. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16475. get: function () {
  16476. return PointerEventTypes._POINTERUP;
  16477. },
  16478. enumerable: true,
  16479. configurable: true
  16480. });
  16481. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16482. get: function () {
  16483. return PointerEventTypes._POINTERMOVE;
  16484. },
  16485. enumerable: true,
  16486. configurable: true
  16487. });
  16488. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16489. get: function () {
  16490. return PointerEventTypes._POINTERWHEEL;
  16491. },
  16492. enumerable: true,
  16493. configurable: true
  16494. });
  16495. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16496. get: function () {
  16497. return PointerEventTypes._POINTERPICK;
  16498. },
  16499. enumerable: true,
  16500. configurable: true
  16501. });
  16502. PointerEventTypes._POINTERDOWN = 0x01;
  16503. PointerEventTypes._POINTERUP = 0x02;
  16504. PointerEventTypes._POINTERMOVE = 0x04;
  16505. PointerEventTypes._POINTERWHEEL = 0x08;
  16506. PointerEventTypes._POINTERPICK = 0x10;
  16507. return PointerEventTypes;
  16508. }());
  16509. BABYLON.PointerEventTypes = PointerEventTypes;
  16510. var PointerInfoBase = (function () {
  16511. function PointerInfoBase(type, event) {
  16512. this.type = type;
  16513. this.event = event;
  16514. }
  16515. return PointerInfoBase;
  16516. }());
  16517. BABYLON.PointerInfoBase = PointerInfoBase;
  16518. /**
  16519. * This class is used to store pointer related info for the onPrePointerObservable event.
  16520. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16521. */
  16522. var PointerInfoPre = (function (_super) {
  16523. __extends(PointerInfoPre, _super);
  16524. function PointerInfoPre(type, event, localX, localY) {
  16525. _super.call(this, type, event);
  16526. this.skipOnPointerObservable = false;
  16527. this.localPosition = new BABYLON.Vector2(localX, localY);
  16528. }
  16529. return PointerInfoPre;
  16530. }(PointerInfoBase));
  16531. BABYLON.PointerInfoPre = PointerInfoPre;
  16532. /**
  16533. * This type contains all the data related to a pointer event in Babylon.js.
  16534. * 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.
  16535. */
  16536. var PointerInfo = (function (_super) {
  16537. __extends(PointerInfo, _super);
  16538. function PointerInfo(type, event, pickInfo) {
  16539. _super.call(this, type, event);
  16540. this.pickInfo = pickInfo;
  16541. }
  16542. return PointerInfo;
  16543. }(PointerInfoBase));
  16544. BABYLON.PointerInfo = PointerInfo;
  16545. /**
  16546. * This class is used by the onRenderingGroupObservable
  16547. */
  16548. var RenderingGroupInfo = (function () {
  16549. function RenderingGroupInfo() {
  16550. }
  16551. /**
  16552. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16553. * This stage will be fired no matter what
  16554. */
  16555. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16556. /**
  16557. * Called before opaque object are rendered.
  16558. * This stage will be fired only if there's 3D Opaque content to render
  16559. */
  16560. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16561. /**
  16562. * Called after the opaque objects are rendered and before the transparent ones
  16563. * This stage will be fired only if there's 3D transparent content to render
  16564. */
  16565. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16566. /**
  16567. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16568. * This stage will be fired no matter what
  16569. */
  16570. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16571. return RenderingGroupInfo;
  16572. }());
  16573. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16574. /**
  16575. * Represents a scene to be rendered by the engine.
  16576. * @see http://doc.babylonjs.com/page.php?p=21911
  16577. */
  16578. var Scene = (function () {
  16579. /**
  16580. * @constructor
  16581. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16582. */
  16583. function Scene(engine) {
  16584. // Members
  16585. this.autoClear = true;
  16586. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16587. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16588. this.forceWireframe = false;
  16589. this.forcePointsCloud = false;
  16590. this.forceShowBoundingBoxes = false;
  16591. this.animationsEnabled = true;
  16592. this.constantlyUpdateMeshUnderPointer = false;
  16593. this.useRightHandedSystem = false;
  16594. this.hoverCursor = "pointer";
  16595. // Metadata
  16596. this.metadata = null;
  16597. // Events
  16598. /**
  16599. * An event triggered when the scene is disposed.
  16600. * @type {BABYLON.Observable}
  16601. */
  16602. this.onDisposeObservable = new BABYLON.Observable();
  16603. /**
  16604. * An event triggered before rendering the scene
  16605. * @type {BABYLON.Observable}
  16606. */
  16607. this.onBeforeRenderObservable = new BABYLON.Observable();
  16608. /**
  16609. * An event triggered after rendering the scene
  16610. * @type {BABYLON.Observable}
  16611. */
  16612. this.onAfterRenderObservable = new BABYLON.Observable();
  16613. /**
  16614. * An event triggered when the scene is ready
  16615. * @type {BABYLON.Observable}
  16616. */
  16617. this.onReadyObservable = new BABYLON.Observable();
  16618. /**
  16619. * An event triggered before rendering a camera
  16620. * @type {BABYLON.Observable}
  16621. */
  16622. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16623. /**
  16624. * An event triggered after rendering a camera
  16625. * @type {BABYLON.Observable}
  16626. */
  16627. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16628. /**
  16629. * An event triggered when a camera is created
  16630. * @type {BABYLON.Observable}
  16631. */
  16632. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16633. /**
  16634. * An event triggered when a camera is removed
  16635. * @type {BABYLON.Observable}
  16636. */
  16637. this.onCameraRemovedObservable = new BABYLON.Observable();
  16638. /**
  16639. * An event triggered when a light is created
  16640. * @type {BABYLON.Observable}
  16641. */
  16642. this.onNewLightAddedObservable = new BABYLON.Observable();
  16643. /**
  16644. * An event triggered when a light is removed
  16645. * @type {BABYLON.Observable}
  16646. */
  16647. this.onLightRemovedObservable = new BABYLON.Observable();
  16648. /**
  16649. * An event triggered when a geometry is created
  16650. * @type {BABYLON.Observable}
  16651. */
  16652. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16653. /**
  16654. * An event triggered when a geometry is removed
  16655. * @type {BABYLON.Observable}
  16656. */
  16657. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16658. /**
  16659. * An event triggered when a mesh is created
  16660. * @type {BABYLON.Observable}
  16661. */
  16662. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16663. /**
  16664. * An event triggered when a mesh is removed
  16665. * @type {BABYLON.Observable}
  16666. */
  16667. this.onMeshRemovedObservable = new BABYLON.Observable();
  16668. /**
  16669. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16670. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16671. * 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)
  16672. */
  16673. this.onRenderingGroupObservable = new BABYLON.Observable();
  16674. // Animations
  16675. this.animations = [];
  16676. /**
  16677. * 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).
  16678. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16679. */
  16680. this.onPrePointerObservable = new BABYLON.Observable();
  16681. /**
  16682. * Observable event triggered each time an input event is received from the rendering canvas
  16683. */
  16684. this.onPointerObservable = new BABYLON.Observable();
  16685. 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
  16686. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16687. this._startingPointerTime = 0;
  16688. // Fog
  16689. /**
  16690. * is fog enabled on this scene.
  16691. * @type {boolean}
  16692. */
  16693. this.fogEnabled = true;
  16694. this.fogMode = Scene.FOGMODE_NONE;
  16695. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16696. this.fogDensity = 0.1;
  16697. this.fogStart = 0;
  16698. this.fogEnd = 1000.0;
  16699. // Lights
  16700. /**
  16701. * is shadow enabled on this scene.
  16702. * @type {boolean}
  16703. */
  16704. this.shadowsEnabled = true;
  16705. /**
  16706. * is light enabled on this scene.
  16707. * @type {boolean}
  16708. */
  16709. this.lightsEnabled = true;
  16710. /**
  16711. * All of the lights added to this scene.
  16712. * @see BABYLON.Light
  16713. * @type {BABYLON.Light[]}
  16714. */
  16715. this.lights = new Array();
  16716. // Cameras
  16717. /**
  16718. * All of the cameras added to this scene.
  16719. * @see BABYLON.Camera
  16720. * @type {BABYLON.Camera[]}
  16721. */
  16722. this.cameras = new Array();
  16723. this.activeCameras = new Array();
  16724. // Meshes
  16725. /**
  16726. * All of the (abstract) meshes added to this scene.
  16727. * @see BABYLON.AbstractMesh
  16728. * @type {BABYLON.AbstractMesh[]}
  16729. */
  16730. this.meshes = new Array();
  16731. // Geometries
  16732. this._geometries = new Array();
  16733. this.materials = new Array();
  16734. this.multiMaterials = new Array();
  16735. // Textures
  16736. this.texturesEnabled = true;
  16737. this.textures = new Array();
  16738. // Particles
  16739. this.particlesEnabled = true;
  16740. this.particleSystems = new Array();
  16741. // Sprites
  16742. this.spritesEnabled = true;
  16743. this.spriteManagers = new Array();
  16744. // Layers
  16745. this.layers = new Array();
  16746. this.highlightLayers = new Array();
  16747. // Skeletons
  16748. this.skeletonsEnabled = true;
  16749. this.skeletons = new Array();
  16750. // Lens flares
  16751. this.lensFlaresEnabled = true;
  16752. this.lensFlareSystems = new Array();
  16753. // Collisions
  16754. this.collisionsEnabled = true;
  16755. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16756. // Postprocesses
  16757. this.postProcessesEnabled = true;
  16758. // Customs render targets
  16759. this.renderTargetsEnabled = true;
  16760. this.dumpNextRenderTargets = false;
  16761. this.customRenderTargets = new Array();
  16762. // Imported meshes
  16763. this.importedMeshesFiles = new Array();
  16764. // Probes
  16765. this.probesEnabled = true;
  16766. this.reflectionProbes = new Array();
  16767. this._actionManagers = new Array();
  16768. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16769. // Procedural textures
  16770. this.proceduralTexturesEnabled = true;
  16771. this._proceduralTextures = new Array();
  16772. this.soundTracks = new Array();
  16773. this._audioEnabled = true;
  16774. this._headphone = false;
  16775. // Performance counters
  16776. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16777. this._totalLightsCounter = new BABYLON.PerfCounter();
  16778. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16779. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16780. this._totalVertices = new BABYLON.PerfCounter();
  16781. this._activeIndices = new BABYLON.PerfCounter();
  16782. this._activeParticles = new BABYLON.PerfCounter();
  16783. this._lastFrameDuration = new BABYLON.PerfCounter();
  16784. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16785. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16786. this._particlesDuration = new BABYLON.PerfCounter();
  16787. this._renderDuration = new BABYLON.PerfCounter();
  16788. this._spritesDuration = new BABYLON.PerfCounter();
  16789. this._activeBones = new BABYLON.PerfCounter();
  16790. this._renderId = 0;
  16791. this._executeWhenReadyTimeoutId = -1;
  16792. this._intermediateRendering = false;
  16793. this._toBeDisposed = new BABYLON.SmartArray(256);
  16794. this._pendingData = []; //ANY
  16795. this._activeMeshes = new BABYLON.SmartArray(256);
  16796. this._processedMaterials = new BABYLON.SmartArray(256);
  16797. this._renderTargets = new BABYLON.SmartArray(256);
  16798. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16799. this._activeSkeletons = new BABYLON.SmartArray(32);
  16800. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16801. this._activeAnimatables = new Array();
  16802. this._transformMatrix = BABYLON.Matrix.Zero();
  16803. this._edgesRenderers = new BABYLON.SmartArray(16);
  16804. this._uniqueIdCounter = 0;
  16805. this._engine = engine;
  16806. engine.scenes.push(this);
  16807. this._externalData = new BABYLON.StringDictionary();
  16808. this._uid = null;
  16809. this._renderingManager = new BABYLON.RenderingManager(this);
  16810. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16811. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16812. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16813. if (BABYLON.OutlineRenderer) {
  16814. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16815. }
  16816. this.attachControl();
  16817. if (BABYLON.SoundTrack) {
  16818. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16819. }
  16820. //simplification queue
  16821. if (BABYLON.SimplificationQueue) {
  16822. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16823. }
  16824. //collision coordinator initialization. For now legacy per default.
  16825. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16826. }
  16827. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16828. get: function () {
  16829. return Scene._FOGMODE_NONE;
  16830. },
  16831. enumerable: true,
  16832. configurable: true
  16833. });
  16834. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16835. get: function () {
  16836. return Scene._FOGMODE_EXP;
  16837. },
  16838. enumerable: true,
  16839. configurable: true
  16840. });
  16841. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16842. get: function () {
  16843. return Scene._FOGMODE_EXP2;
  16844. },
  16845. enumerable: true,
  16846. configurable: true
  16847. });
  16848. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16849. get: function () {
  16850. return Scene._FOGMODE_LINEAR;
  16851. },
  16852. enumerable: true,
  16853. configurable: true
  16854. });
  16855. Object.defineProperty(Scene.prototype, "onDispose", {
  16856. set: function (callback) {
  16857. if (this._onDisposeObserver) {
  16858. this.onDisposeObservable.remove(this._onDisposeObserver);
  16859. }
  16860. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16861. },
  16862. enumerable: true,
  16863. configurable: true
  16864. });
  16865. Object.defineProperty(Scene.prototype, "beforeRender", {
  16866. set: function (callback) {
  16867. if (this._onBeforeRenderObserver) {
  16868. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16869. }
  16870. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16871. },
  16872. enumerable: true,
  16873. configurable: true
  16874. });
  16875. Object.defineProperty(Scene.prototype, "afterRender", {
  16876. set: function (callback) {
  16877. if (this._onAfterRenderObserver) {
  16878. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16879. }
  16880. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16881. },
  16882. enumerable: true,
  16883. configurable: true
  16884. });
  16885. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16886. set: function (callback) {
  16887. if (this._onBeforeCameraRenderObserver) {
  16888. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16889. }
  16890. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16891. },
  16892. enumerable: true,
  16893. configurable: true
  16894. });
  16895. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16896. set: function (callback) {
  16897. if (this._onAfterCameraRenderObserver) {
  16898. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16899. }
  16900. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16901. },
  16902. enumerable: true,
  16903. configurable: true
  16904. });
  16905. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16906. get: function () {
  16907. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16908. },
  16909. enumerable: true,
  16910. configurable: true
  16911. });
  16912. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16913. get: function () {
  16914. if (!this._defaultMaterial) {
  16915. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16916. }
  16917. return this._defaultMaterial;
  16918. },
  16919. enumerable: true,
  16920. configurable: true
  16921. });
  16922. Object.defineProperty(Scene.prototype, "debugLayer", {
  16923. // Properties
  16924. get: function () {
  16925. if (!this._debugLayer) {
  16926. this._debugLayer = new BABYLON.DebugLayer(this);
  16927. }
  16928. return this._debugLayer;
  16929. },
  16930. enumerable: true,
  16931. configurable: true
  16932. });
  16933. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16934. get: function () {
  16935. return this._workerCollisions;
  16936. },
  16937. set: function (enabled) {
  16938. enabled = (enabled && !!Worker);
  16939. this._workerCollisions = enabled;
  16940. if (this.collisionCoordinator) {
  16941. this.collisionCoordinator.destroy();
  16942. }
  16943. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16944. this.collisionCoordinator.init(this);
  16945. },
  16946. enumerable: true,
  16947. configurable: true
  16948. });
  16949. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16950. get: function () {
  16951. return this._selectionOctree;
  16952. },
  16953. enumerable: true,
  16954. configurable: true
  16955. });
  16956. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16957. /**
  16958. * The mesh that is currently under the pointer.
  16959. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16960. */
  16961. get: function () {
  16962. return this._pointerOverMesh;
  16963. },
  16964. enumerable: true,
  16965. configurable: true
  16966. });
  16967. Object.defineProperty(Scene.prototype, "pointerX", {
  16968. /**
  16969. * Current on-screen X position of the pointer
  16970. * @return {number} X position of the pointer
  16971. */
  16972. get: function () {
  16973. return this._pointerX;
  16974. },
  16975. enumerable: true,
  16976. configurable: true
  16977. });
  16978. Object.defineProperty(Scene.prototype, "pointerY", {
  16979. /**
  16980. * Current on-screen Y position of the pointer
  16981. * @return {number} Y position of the pointer
  16982. */
  16983. get: function () {
  16984. return this._pointerY;
  16985. },
  16986. enumerable: true,
  16987. configurable: true
  16988. });
  16989. Scene.prototype.getCachedMaterial = function () {
  16990. return this._cachedMaterial;
  16991. };
  16992. Scene.prototype.getBoundingBoxRenderer = function () {
  16993. return this._boundingBoxRenderer;
  16994. };
  16995. Scene.prototype.getOutlineRenderer = function () {
  16996. return this._outlineRenderer;
  16997. };
  16998. Scene.prototype.getEngine = function () {
  16999. return this._engine;
  17000. };
  17001. Scene.prototype.getTotalVertices = function () {
  17002. return this._totalVertices.current;
  17003. };
  17004. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17005. get: function () {
  17006. return this._totalVertices;
  17007. },
  17008. enumerable: true,
  17009. configurable: true
  17010. });
  17011. Scene.prototype.getActiveIndices = function () {
  17012. return this._activeIndices.current;
  17013. };
  17014. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17015. get: function () {
  17016. return this._activeIndices;
  17017. },
  17018. enumerable: true,
  17019. configurable: true
  17020. });
  17021. Scene.prototype.getActiveParticles = function () {
  17022. return this._activeParticles.current;
  17023. };
  17024. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17025. get: function () {
  17026. return this._activeParticles;
  17027. },
  17028. enumerable: true,
  17029. configurable: true
  17030. });
  17031. Scene.prototype.getActiveBones = function () {
  17032. return this._activeBones.current;
  17033. };
  17034. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17035. get: function () {
  17036. return this._activeBones;
  17037. },
  17038. enumerable: true,
  17039. configurable: true
  17040. });
  17041. // Stats
  17042. Scene.prototype.getLastFrameDuration = function () {
  17043. return this._lastFrameDuration.current;
  17044. };
  17045. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17046. get: function () {
  17047. return this._lastFrameDuration;
  17048. },
  17049. enumerable: true,
  17050. configurable: true
  17051. });
  17052. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17053. return this._evaluateActiveMeshesDuration.current;
  17054. };
  17055. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17056. get: function () {
  17057. return this._evaluateActiveMeshesDuration;
  17058. },
  17059. enumerable: true,
  17060. configurable: true
  17061. });
  17062. Scene.prototype.getActiveMeshes = function () {
  17063. return this._activeMeshes;
  17064. };
  17065. Scene.prototype.getRenderTargetsDuration = function () {
  17066. return this._renderTargetsDuration.current;
  17067. };
  17068. Scene.prototype.getRenderDuration = function () {
  17069. return this._renderDuration.current;
  17070. };
  17071. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17072. get: function () {
  17073. return this._renderDuration;
  17074. },
  17075. enumerable: true,
  17076. configurable: true
  17077. });
  17078. Scene.prototype.getParticlesDuration = function () {
  17079. return this._particlesDuration.current;
  17080. };
  17081. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17082. get: function () {
  17083. return this._particlesDuration;
  17084. },
  17085. enumerable: true,
  17086. configurable: true
  17087. });
  17088. Scene.prototype.getSpritesDuration = function () {
  17089. return this._spritesDuration.current;
  17090. };
  17091. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17092. get: function () {
  17093. return this._spritesDuration;
  17094. },
  17095. enumerable: true,
  17096. configurable: true
  17097. });
  17098. Scene.prototype.getAnimationRatio = function () {
  17099. return this._animationRatio;
  17100. };
  17101. Scene.prototype.getRenderId = function () {
  17102. return this._renderId;
  17103. };
  17104. Scene.prototype.incrementRenderId = function () {
  17105. this._renderId++;
  17106. };
  17107. Scene.prototype._updatePointerPosition = function (evt) {
  17108. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17109. this._pointerX = evt.clientX - canvasRect.left;
  17110. this._pointerY = evt.clientY - canvasRect.top;
  17111. this._unTranslatedPointerX = this._pointerX;
  17112. this._unTranslatedPointerY = this._pointerY;
  17113. if (this.cameraToUseForPointers) {
  17114. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17115. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17116. }
  17117. };
  17118. // Pointers handling
  17119. /**
  17120. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17121. * @param attachUp defines if you want to attach events to pointerup
  17122. * @param attachDown defines if you want to attach events to pointerdown
  17123. * @param attachMove defines if you want to attach events to pointermove
  17124. */
  17125. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17126. var _this = this;
  17127. if (attachUp === void 0) { attachUp = true; }
  17128. if (attachDown === void 0) { attachDown = true; }
  17129. if (attachMove === void 0) { attachMove = true; }
  17130. var spritePredicate = function (sprite) {
  17131. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17132. };
  17133. this._onPointerMove = function (evt) {
  17134. _this._updatePointerPosition(evt);
  17135. // PreObservable support
  17136. if (_this.onPrePointerObservable.hasObservers()) {
  17137. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17138. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17139. _this.onPrePointerObservable.notifyObservers(pi, type);
  17140. if (pi.skipOnPointerObservable) {
  17141. return;
  17142. }
  17143. }
  17144. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17145. return;
  17146. }
  17147. var canvas = _this._engine.getRenderingCanvas();
  17148. if (!_this.pointerMovePredicate) {
  17149. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17150. }
  17151. // Meshes
  17152. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17153. if (pickResult.hit && pickResult.pickedMesh) {
  17154. _this.setPointerOverSprite(null);
  17155. _this.setPointerOverMesh(pickResult.pickedMesh);
  17156. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17157. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17158. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17159. }
  17160. else {
  17161. canvas.style.cursor = _this.hoverCursor;
  17162. }
  17163. }
  17164. else {
  17165. canvas.style.cursor = "";
  17166. }
  17167. }
  17168. else {
  17169. _this.setPointerOverMesh(null);
  17170. // Sprites
  17171. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17172. if (pickResult.hit && pickResult.pickedSprite) {
  17173. _this.setPointerOverSprite(pickResult.pickedSprite);
  17174. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17175. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17176. }
  17177. else {
  17178. canvas.style.cursor = _this.hoverCursor;
  17179. }
  17180. }
  17181. else {
  17182. _this.setPointerOverSprite(null);
  17183. // Restore pointer
  17184. canvas.style.cursor = "";
  17185. }
  17186. }
  17187. if (_this.onPointerMove) {
  17188. _this.onPointerMove(evt, pickResult);
  17189. }
  17190. if (_this.onPointerObservable.hasObservers()) {
  17191. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17192. var pi = new PointerInfo(type, evt, pickResult);
  17193. _this.onPointerObservable.notifyObservers(pi, type);
  17194. }
  17195. };
  17196. this._onPointerDown = function (evt) {
  17197. _this._updatePointerPosition(evt);
  17198. // PreObservable support
  17199. if (_this.onPrePointerObservable.hasObservers()) {
  17200. var type = PointerEventTypes.POINTERDOWN;
  17201. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17202. _this.onPrePointerObservable.notifyObservers(pi, type);
  17203. if (pi.skipOnPointerObservable) {
  17204. return;
  17205. }
  17206. }
  17207. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17208. return;
  17209. }
  17210. _this._startingPointerPosition.x = _this._pointerX;
  17211. _this._startingPointerPosition.y = _this._pointerY;
  17212. _this._startingPointerTime = new Date().getTime();
  17213. if (!_this.pointerDownPredicate) {
  17214. _this.pointerDownPredicate = function (mesh) {
  17215. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17216. };
  17217. }
  17218. // Meshes
  17219. _this._pickedDownMesh = null;
  17220. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17221. if (pickResult.hit && pickResult.pickedMesh) {
  17222. if (pickResult.pickedMesh.actionManager) {
  17223. _this._pickedDownMesh = pickResult.pickedMesh;
  17224. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17225. switch (evt.button) {
  17226. case 0:
  17227. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17228. break;
  17229. case 1:
  17230. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17231. break;
  17232. case 2:
  17233. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17234. break;
  17235. }
  17236. if (pickResult.pickedMesh.actionManager) {
  17237. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17238. }
  17239. }
  17240. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17241. var that = _this;
  17242. window.setTimeout(function () {
  17243. 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);
  17244. if (pickResult.hit && pickResult.pickedMesh) {
  17245. if (pickResult.pickedMesh.actionManager) {
  17246. 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)) {
  17247. that._startingPointerTime = 0;
  17248. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17249. }
  17250. }
  17251. }
  17252. }, BABYLON.ActionManager.LongPressDelay);
  17253. }
  17254. }
  17255. }
  17256. if (_this.onPointerDown) {
  17257. _this.onPointerDown(evt, pickResult);
  17258. }
  17259. if (_this.onPointerObservable.hasObservers()) {
  17260. var type = PointerEventTypes.POINTERDOWN;
  17261. var pi = new PointerInfo(type, evt, pickResult);
  17262. _this.onPointerObservable.notifyObservers(pi, type);
  17263. }
  17264. // Sprites
  17265. _this._pickedDownSprite = null;
  17266. if (_this.spriteManagers.length > 0) {
  17267. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17268. if (pickResult.hit && pickResult.pickedSprite) {
  17269. if (pickResult.pickedSprite.actionManager) {
  17270. _this._pickedDownSprite = pickResult.pickedSprite;
  17271. switch (evt.button) {
  17272. case 0:
  17273. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17274. break;
  17275. case 1:
  17276. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17277. break;
  17278. case 2:
  17279. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17280. break;
  17281. }
  17282. if (pickResult.pickedSprite.actionManager) {
  17283. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17284. }
  17285. }
  17286. }
  17287. }
  17288. };
  17289. this._onPointerUp = function (evt) {
  17290. _this._updatePointerPosition(evt);
  17291. // PreObservable support
  17292. if (_this.onPrePointerObservable.hasObservers()) {
  17293. var type = PointerEventTypes.POINTERUP;
  17294. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17295. _this.onPrePointerObservable.notifyObservers(pi, type);
  17296. if (pi.skipOnPointerObservable) {
  17297. return;
  17298. }
  17299. }
  17300. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17301. return;
  17302. }
  17303. if (!_this.pointerUpPredicate) {
  17304. _this.pointerUpPredicate = function (mesh) {
  17305. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17306. };
  17307. }
  17308. // Meshes
  17309. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17310. if (pickResult.hit && pickResult.pickedMesh) {
  17311. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17312. if (_this.onPointerPick) {
  17313. _this.onPointerPick(evt, pickResult);
  17314. }
  17315. if (_this.onPointerObservable.hasObservers()) {
  17316. var type = PointerEventTypes.POINTERPICK;
  17317. var pi = new PointerInfo(type, evt, pickResult);
  17318. _this.onPointerObservable.notifyObservers(pi, type);
  17319. }
  17320. }
  17321. if (pickResult.pickedMesh.actionManager) {
  17322. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17323. if (pickResult.pickedMesh.actionManager) {
  17324. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17325. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17326. }
  17327. }
  17328. }
  17329. }
  17330. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17331. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17332. }
  17333. if (_this.onPointerUp) {
  17334. _this.onPointerUp(evt, pickResult);
  17335. }
  17336. if (_this.onPointerObservable.hasObservers()) {
  17337. var type = PointerEventTypes.POINTERUP;
  17338. var pi = new PointerInfo(type, evt, pickResult);
  17339. _this.onPointerObservable.notifyObservers(pi, type);
  17340. }
  17341. _this._startingPointerTime = 0;
  17342. // Sprites
  17343. if (_this.spriteManagers.length > 0) {
  17344. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17345. if (pickResult.hit && pickResult.pickedSprite) {
  17346. if (pickResult.pickedSprite.actionManager) {
  17347. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17348. if (pickResult.pickedSprite.actionManager) {
  17349. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17350. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17351. }
  17352. }
  17353. }
  17354. }
  17355. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17356. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17357. }
  17358. }
  17359. };
  17360. this._onKeyDown = function (evt) {
  17361. if (_this.actionManager) {
  17362. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17363. }
  17364. };
  17365. this._onKeyUp = function (evt) {
  17366. if (_this.actionManager) {
  17367. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17368. }
  17369. };
  17370. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17371. var canvas = this._engine.getRenderingCanvas();
  17372. if (attachMove) {
  17373. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17374. // Wheel
  17375. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17376. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17377. }
  17378. if (attachDown) {
  17379. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17380. }
  17381. if (attachUp) {
  17382. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17383. }
  17384. canvas.tabIndex = 1;
  17385. canvas.addEventListener("keydown", this._onKeyDown, false);
  17386. canvas.addEventListener("keyup", this._onKeyUp, false);
  17387. };
  17388. Scene.prototype.detachControl = function () {
  17389. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17390. var canvas = this._engine.getRenderingCanvas();
  17391. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17392. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17393. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17394. // Wheel
  17395. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17396. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17397. canvas.removeEventListener("keydown", this._onKeyDown);
  17398. canvas.removeEventListener("keyup", this._onKeyUp);
  17399. };
  17400. // Ready
  17401. Scene.prototype.isReady = function () {
  17402. if (this._pendingData.length > 0) {
  17403. return false;
  17404. }
  17405. var index;
  17406. for (index = 0; index < this._geometries.length; index++) {
  17407. var geometry = this._geometries[index];
  17408. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17409. return false;
  17410. }
  17411. }
  17412. for (index = 0; index < this.meshes.length; index++) {
  17413. var mesh = this.meshes[index];
  17414. if (!mesh.isReady()) {
  17415. return false;
  17416. }
  17417. var mat = mesh.material;
  17418. if (mat) {
  17419. if (!mat.isReady(mesh)) {
  17420. return false;
  17421. }
  17422. }
  17423. }
  17424. return true;
  17425. };
  17426. Scene.prototype.resetCachedMaterial = function () {
  17427. this._cachedMaterial = null;
  17428. };
  17429. Scene.prototype.registerBeforeRender = function (func) {
  17430. this.onBeforeRenderObservable.add(func);
  17431. };
  17432. Scene.prototype.unregisterBeforeRender = function (func) {
  17433. this.onBeforeRenderObservable.removeCallback(func);
  17434. };
  17435. Scene.prototype.registerAfterRender = function (func) {
  17436. this.onAfterRenderObservable.add(func);
  17437. };
  17438. Scene.prototype.unregisterAfterRender = function (func) {
  17439. this.onAfterRenderObservable.removeCallback(func);
  17440. };
  17441. Scene.prototype._addPendingData = function (data) {
  17442. this._pendingData.push(data);
  17443. };
  17444. Scene.prototype._removePendingData = function (data) {
  17445. var index = this._pendingData.indexOf(data);
  17446. if (index !== -1) {
  17447. this._pendingData.splice(index, 1);
  17448. }
  17449. };
  17450. Scene.prototype.getWaitingItemsCount = function () {
  17451. return this._pendingData.length;
  17452. };
  17453. /**
  17454. * Registers a function to be executed when the scene is ready.
  17455. * @param {Function} func - the function to be executed.
  17456. */
  17457. Scene.prototype.executeWhenReady = function (func) {
  17458. var _this = this;
  17459. this.onReadyObservable.add(func);
  17460. if (this._executeWhenReadyTimeoutId !== -1) {
  17461. return;
  17462. }
  17463. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17464. _this._checkIsReady();
  17465. }, 150);
  17466. };
  17467. Scene.prototype._checkIsReady = function () {
  17468. var _this = this;
  17469. if (this.isReady()) {
  17470. this.onReadyObservable.notifyObservers(this);
  17471. this.onReadyObservable.clear();
  17472. this._executeWhenReadyTimeoutId = -1;
  17473. return;
  17474. }
  17475. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17476. _this._checkIsReady();
  17477. }, 150);
  17478. };
  17479. // Animations
  17480. /**
  17481. * Will start the animation sequence of a given target
  17482. * @param target - the target
  17483. * @param {number} from - from which frame should animation start
  17484. * @param {number} to - till which frame should animation run.
  17485. * @param {boolean} [loop] - should the animation loop
  17486. * @param {number} [speedRatio] - the speed in which to run the animation
  17487. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17488. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17489. * @return {BABYLON.Animatable} the animatable object created for this animation
  17490. * @see BABYLON.Animatable
  17491. * @see http://doc.babylonjs.com/page.php?p=22081
  17492. */
  17493. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17494. if (speedRatio === void 0) { speedRatio = 1.0; }
  17495. this.stopAnimation(target);
  17496. if (!animatable) {
  17497. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17498. }
  17499. // Local animations
  17500. if (target.animations) {
  17501. animatable.appendAnimations(target, target.animations);
  17502. }
  17503. // Children animations
  17504. if (target.getAnimatables) {
  17505. var animatables = target.getAnimatables();
  17506. for (var index = 0; index < animatables.length; index++) {
  17507. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17508. }
  17509. }
  17510. animatable.reset();
  17511. return animatable;
  17512. };
  17513. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17514. if (speedRatio === undefined) {
  17515. speedRatio = 1.0;
  17516. }
  17517. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17518. return animatable;
  17519. };
  17520. Scene.prototype.getAnimatableByTarget = function (target) {
  17521. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17522. if (this._activeAnimatables[index].target === target) {
  17523. return this._activeAnimatables[index];
  17524. }
  17525. }
  17526. return null;
  17527. };
  17528. Object.defineProperty(Scene.prototype, "Animatables", {
  17529. get: function () {
  17530. return this._activeAnimatables;
  17531. },
  17532. enumerable: true,
  17533. configurable: true
  17534. });
  17535. /**
  17536. * Will stop the animation of the given target
  17537. * @param target - the target
  17538. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17539. * @see beginAnimation
  17540. */
  17541. Scene.prototype.stopAnimation = function (target, animationName) {
  17542. var animatable = this.getAnimatableByTarget(target);
  17543. if (animatable) {
  17544. animatable.stop(animationName);
  17545. }
  17546. };
  17547. Scene.prototype._animate = function () {
  17548. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17549. return;
  17550. }
  17551. if (!this._animationStartDate) {
  17552. if (this._pendingData.length > 0) {
  17553. return;
  17554. }
  17555. this._animationStartDate = BABYLON.Tools.Now;
  17556. }
  17557. // Getting time
  17558. var now = BABYLON.Tools.Now;
  17559. var delay = now - this._animationStartDate;
  17560. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17561. this._activeAnimatables[index]._animate(delay);
  17562. }
  17563. };
  17564. // Matrix
  17565. Scene.prototype.getViewMatrix = function () {
  17566. return this._viewMatrix;
  17567. };
  17568. Scene.prototype.getProjectionMatrix = function () {
  17569. return this._projectionMatrix;
  17570. };
  17571. Scene.prototype.getTransformMatrix = function () {
  17572. return this._transformMatrix;
  17573. };
  17574. Scene.prototype.setTransformMatrix = function (view, projection) {
  17575. this._viewMatrix = view;
  17576. this._projectionMatrix = projection;
  17577. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17578. // Update frustum
  17579. if (!this._frustumPlanes) {
  17580. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17581. }
  17582. else {
  17583. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17584. }
  17585. };
  17586. // Methods
  17587. Scene.prototype.addMesh = function (newMesh) {
  17588. newMesh.uniqueId = this._uniqueIdCounter++;
  17589. var position = this.meshes.push(newMesh);
  17590. //notify the collision coordinator
  17591. this.collisionCoordinator.onMeshAdded(newMesh);
  17592. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17593. };
  17594. Scene.prototype.removeMesh = function (toRemove) {
  17595. var index = this.meshes.indexOf(toRemove);
  17596. if (index !== -1) {
  17597. // Remove from the scene if mesh found
  17598. this.meshes.splice(index, 1);
  17599. }
  17600. //notify the collision coordinator
  17601. this.collisionCoordinator.onMeshRemoved(toRemove);
  17602. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17603. return index;
  17604. };
  17605. Scene.prototype.removeSkeleton = function (toRemove) {
  17606. var index = this.skeletons.indexOf(toRemove);
  17607. if (index !== -1) {
  17608. // Remove from the scene if mesh found
  17609. this.skeletons.splice(index, 1);
  17610. }
  17611. return index;
  17612. };
  17613. Scene.prototype.removeLight = function (toRemove) {
  17614. var index = this.lights.indexOf(toRemove);
  17615. if (index !== -1) {
  17616. // Remove from the scene if mesh found
  17617. this.lights.splice(index, 1);
  17618. }
  17619. this.onLightRemovedObservable.notifyObservers(toRemove);
  17620. return index;
  17621. };
  17622. Scene.prototype.removeCamera = function (toRemove) {
  17623. var index = this.cameras.indexOf(toRemove);
  17624. if (index !== -1) {
  17625. // Remove from the scene if mesh found
  17626. this.cameras.splice(index, 1);
  17627. }
  17628. // Remove from activeCameras
  17629. var index2 = this.activeCameras.indexOf(toRemove);
  17630. if (index2 !== -1) {
  17631. // Remove from the scene if mesh found
  17632. this.activeCameras.splice(index2, 1);
  17633. }
  17634. // Reset the activeCamera
  17635. if (this.activeCamera === toRemove) {
  17636. if (this.cameras.length > 0) {
  17637. this.activeCamera = this.cameras[0];
  17638. }
  17639. else {
  17640. this.activeCamera = null;
  17641. }
  17642. }
  17643. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17644. return index;
  17645. };
  17646. Scene.prototype.addLight = function (newLight) {
  17647. newLight.uniqueId = this._uniqueIdCounter++;
  17648. var position = this.lights.push(newLight);
  17649. this.onNewLightAddedObservable.notifyObservers(newLight);
  17650. };
  17651. Scene.prototype.addCamera = function (newCamera) {
  17652. newCamera.uniqueId = this._uniqueIdCounter++;
  17653. var position = this.cameras.push(newCamera);
  17654. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17655. };
  17656. /**
  17657. * Switch active camera
  17658. * @param {Camera} newCamera - new active camera
  17659. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17660. */
  17661. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17662. if (attachControl === void 0) { attachControl = true; }
  17663. var canvas = this._engine.getRenderingCanvas();
  17664. this.activeCamera.detachControl(canvas);
  17665. this.activeCamera = newCamera;
  17666. if (attachControl) {
  17667. newCamera.attachControl(canvas);
  17668. }
  17669. };
  17670. /**
  17671. * sets the active camera of the scene using its ID
  17672. * @param {string} id - the camera's ID
  17673. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17674. * @see activeCamera
  17675. */
  17676. Scene.prototype.setActiveCameraByID = function (id) {
  17677. var camera = this.getCameraByID(id);
  17678. if (camera) {
  17679. this.activeCamera = camera;
  17680. return camera;
  17681. }
  17682. return null;
  17683. };
  17684. /**
  17685. * sets the active camera of the scene using its name
  17686. * @param {string} name - the camera's name
  17687. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17688. * @see activeCamera
  17689. */
  17690. Scene.prototype.setActiveCameraByName = function (name) {
  17691. var camera = this.getCameraByName(name);
  17692. if (camera) {
  17693. this.activeCamera = camera;
  17694. return camera;
  17695. }
  17696. return null;
  17697. };
  17698. /**
  17699. * get a material using its id
  17700. * @param {string} the material's ID
  17701. * @return {BABYLON.Material|null} the material or null if none found.
  17702. */
  17703. Scene.prototype.getMaterialByID = function (id) {
  17704. for (var index = 0; index < this.materials.length; index++) {
  17705. if (this.materials[index].id === id) {
  17706. return this.materials[index];
  17707. }
  17708. }
  17709. return null;
  17710. };
  17711. /**
  17712. * get a material using its name
  17713. * @param {string} the material's name
  17714. * @return {BABYLON.Material|null} the material or null if none found.
  17715. */
  17716. Scene.prototype.getMaterialByName = function (name) {
  17717. for (var index = 0; index < this.materials.length; index++) {
  17718. if (this.materials[index].name === name) {
  17719. return this.materials[index];
  17720. }
  17721. }
  17722. return null;
  17723. };
  17724. Scene.prototype.getLensFlareSystemByName = function (name) {
  17725. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17726. if (this.lensFlareSystems[index].name === name) {
  17727. return this.lensFlareSystems[index];
  17728. }
  17729. }
  17730. return null;
  17731. };
  17732. Scene.prototype.getLensFlareSystemByID = function (id) {
  17733. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17734. if (this.lensFlareSystems[index].id === id) {
  17735. return this.lensFlareSystems[index];
  17736. }
  17737. }
  17738. return null;
  17739. };
  17740. Scene.prototype.getCameraByID = function (id) {
  17741. for (var index = 0; index < this.cameras.length; index++) {
  17742. if (this.cameras[index].id === id) {
  17743. return this.cameras[index];
  17744. }
  17745. }
  17746. return null;
  17747. };
  17748. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17749. for (var index = 0; index < this.cameras.length; index++) {
  17750. if (this.cameras[index].uniqueId === uniqueId) {
  17751. return this.cameras[index];
  17752. }
  17753. }
  17754. return null;
  17755. };
  17756. /**
  17757. * get a camera using its name
  17758. * @param {string} the camera's name
  17759. * @return {BABYLON.Camera|null} the camera or null if none found.
  17760. */
  17761. Scene.prototype.getCameraByName = function (name) {
  17762. for (var index = 0; index < this.cameras.length; index++) {
  17763. if (this.cameras[index].name === name) {
  17764. return this.cameras[index];
  17765. }
  17766. }
  17767. return null;
  17768. };
  17769. /**
  17770. * get a bone using its id
  17771. * @param {string} the bone's id
  17772. * @return {BABYLON.Bone|null} the bone or null if not found
  17773. */
  17774. Scene.prototype.getBoneByID = function (id) {
  17775. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17776. var skeleton = this.skeletons[skeletonIndex];
  17777. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17778. if (skeleton.bones[boneIndex].id === id) {
  17779. return skeleton.bones[boneIndex];
  17780. }
  17781. }
  17782. }
  17783. return null;
  17784. };
  17785. /**
  17786. * get a bone using its id
  17787. * @param {string} the bone's name
  17788. * @return {BABYLON.Bone|null} the bone or null if not found
  17789. */
  17790. Scene.prototype.getBoneByName = function (name) {
  17791. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17792. var skeleton = this.skeletons[skeletonIndex];
  17793. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17794. if (skeleton.bones[boneIndex].name === name) {
  17795. return skeleton.bones[boneIndex];
  17796. }
  17797. }
  17798. }
  17799. return null;
  17800. };
  17801. /**
  17802. * get a light node using its name
  17803. * @param {string} the light's name
  17804. * @return {BABYLON.Light|null} the light or null if none found.
  17805. */
  17806. Scene.prototype.getLightByName = function (name) {
  17807. for (var index = 0; index < this.lights.length; index++) {
  17808. if (this.lights[index].name === name) {
  17809. return this.lights[index];
  17810. }
  17811. }
  17812. return null;
  17813. };
  17814. /**
  17815. * get a light node using its ID
  17816. * @param {string} the light's id
  17817. * @return {BABYLON.Light|null} the light or null if none found.
  17818. */
  17819. Scene.prototype.getLightByID = function (id) {
  17820. for (var index = 0; index < this.lights.length; index++) {
  17821. if (this.lights[index].id === id) {
  17822. return this.lights[index];
  17823. }
  17824. }
  17825. return null;
  17826. };
  17827. /**
  17828. * get a light node using its scene-generated unique ID
  17829. * @param {number} the light's unique id
  17830. * @return {BABYLON.Light|null} the light or null if none found.
  17831. */
  17832. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17833. for (var index = 0; index < this.lights.length; index++) {
  17834. if (this.lights[index].uniqueId === uniqueId) {
  17835. return this.lights[index];
  17836. }
  17837. }
  17838. return null;
  17839. };
  17840. /**
  17841. * get a particle system by id
  17842. * @param id {number} the particle system id
  17843. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17844. */
  17845. Scene.prototype.getParticleSystemByID = function (id) {
  17846. for (var index = 0; index < this.particleSystems.length; index++) {
  17847. if (this.particleSystems[index].id === id) {
  17848. return this.particleSystems[index];
  17849. }
  17850. }
  17851. return null;
  17852. };
  17853. /**
  17854. * get a geometry using its ID
  17855. * @param {string} the geometry's id
  17856. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17857. */
  17858. Scene.prototype.getGeometryByID = function (id) {
  17859. for (var index = 0; index < this._geometries.length; index++) {
  17860. if (this._geometries[index].id === id) {
  17861. return this._geometries[index];
  17862. }
  17863. }
  17864. return null;
  17865. };
  17866. /**
  17867. * add a new geometry to this scene.
  17868. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17869. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17870. * @return {boolean} was the geometry added or not
  17871. */
  17872. Scene.prototype.pushGeometry = function (geometry, force) {
  17873. if (!force && this.getGeometryByID(geometry.id)) {
  17874. return false;
  17875. }
  17876. this._geometries.push(geometry);
  17877. //notify the collision coordinator
  17878. this.collisionCoordinator.onGeometryAdded(geometry);
  17879. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17880. return true;
  17881. };
  17882. /**
  17883. * Removes an existing geometry
  17884. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17885. * @return {boolean} was the geometry removed or not
  17886. */
  17887. Scene.prototype.removeGeometry = function (geometry) {
  17888. var index = this._geometries.indexOf(geometry);
  17889. if (index > -1) {
  17890. this._geometries.splice(index, 1);
  17891. //notify the collision coordinator
  17892. this.collisionCoordinator.onGeometryDeleted(geometry);
  17893. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17894. return true;
  17895. }
  17896. return false;
  17897. };
  17898. Scene.prototype.getGeometries = function () {
  17899. return this._geometries;
  17900. };
  17901. /**
  17902. * Get the first added mesh found of a given ID
  17903. * @param {string} id - the id to search for
  17904. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17905. */
  17906. Scene.prototype.getMeshByID = function (id) {
  17907. for (var index = 0; index < this.meshes.length; index++) {
  17908. if (this.meshes[index].id === id) {
  17909. return this.meshes[index];
  17910. }
  17911. }
  17912. return null;
  17913. };
  17914. Scene.prototype.getMeshesByID = function (id) {
  17915. return this.meshes.filter(function (m) {
  17916. return m.id === id;
  17917. });
  17918. };
  17919. /**
  17920. * Get a mesh with its auto-generated unique id
  17921. * @param {number} uniqueId - the unique id to search for
  17922. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17923. */
  17924. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17925. for (var index = 0; index < this.meshes.length; index++) {
  17926. if (this.meshes[index].uniqueId === uniqueId) {
  17927. return this.meshes[index];
  17928. }
  17929. }
  17930. return null;
  17931. };
  17932. /**
  17933. * Get a the last added mesh found of a given ID
  17934. * @param {string} id - the id to search for
  17935. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17936. */
  17937. Scene.prototype.getLastMeshByID = function (id) {
  17938. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17939. if (this.meshes[index].id === id) {
  17940. return this.meshes[index];
  17941. }
  17942. }
  17943. return null;
  17944. };
  17945. /**
  17946. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17947. * @param {string} id - the id to search for
  17948. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17949. */
  17950. Scene.prototype.getLastEntryByID = function (id) {
  17951. var index;
  17952. for (index = this.meshes.length - 1; index >= 0; index--) {
  17953. if (this.meshes[index].id === id) {
  17954. return this.meshes[index];
  17955. }
  17956. }
  17957. for (index = this.cameras.length - 1; index >= 0; index--) {
  17958. if (this.cameras[index].id === id) {
  17959. return this.cameras[index];
  17960. }
  17961. }
  17962. for (index = this.lights.length - 1; index >= 0; index--) {
  17963. if (this.lights[index].id === id) {
  17964. return this.lights[index];
  17965. }
  17966. }
  17967. return null;
  17968. };
  17969. Scene.prototype.getNodeByID = function (id) {
  17970. var mesh = this.getMeshByID(id);
  17971. if (mesh) {
  17972. return mesh;
  17973. }
  17974. var light = this.getLightByID(id);
  17975. if (light) {
  17976. return light;
  17977. }
  17978. var camera = this.getCameraByID(id);
  17979. if (camera) {
  17980. return camera;
  17981. }
  17982. var bone = this.getBoneByID(id);
  17983. return bone;
  17984. };
  17985. Scene.prototype.getNodeByName = function (name) {
  17986. var mesh = this.getMeshByName(name);
  17987. if (mesh) {
  17988. return mesh;
  17989. }
  17990. var light = this.getLightByName(name);
  17991. if (light) {
  17992. return light;
  17993. }
  17994. var camera = this.getCameraByName(name);
  17995. if (camera) {
  17996. return camera;
  17997. }
  17998. var bone = this.getBoneByName(name);
  17999. return bone;
  18000. };
  18001. Scene.prototype.getMeshByName = function (name) {
  18002. for (var index = 0; index < this.meshes.length; index++) {
  18003. if (this.meshes[index].name === name) {
  18004. return this.meshes[index];
  18005. }
  18006. }
  18007. return null;
  18008. };
  18009. Scene.prototype.getSoundByName = function (name) {
  18010. var index;
  18011. if (BABYLON.AudioEngine) {
  18012. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18013. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18014. return this.mainSoundTrack.soundCollection[index];
  18015. }
  18016. }
  18017. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18018. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18019. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18020. return this.soundTracks[sdIndex].soundCollection[index];
  18021. }
  18022. }
  18023. }
  18024. }
  18025. return null;
  18026. };
  18027. Scene.prototype.getLastSkeletonByID = function (id) {
  18028. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18029. if (this.skeletons[index].id === id) {
  18030. return this.skeletons[index];
  18031. }
  18032. }
  18033. return null;
  18034. };
  18035. Scene.prototype.getSkeletonById = function (id) {
  18036. for (var index = 0; index < this.skeletons.length; index++) {
  18037. if (this.skeletons[index].id === id) {
  18038. return this.skeletons[index];
  18039. }
  18040. }
  18041. return null;
  18042. };
  18043. Scene.prototype.getSkeletonByName = function (name) {
  18044. for (var index = 0; index < this.skeletons.length; index++) {
  18045. if (this.skeletons[index].name === name) {
  18046. return this.skeletons[index];
  18047. }
  18048. }
  18049. return null;
  18050. };
  18051. Scene.prototype.isActiveMesh = function (mesh) {
  18052. return (this._activeMeshes.indexOf(mesh) !== -1);
  18053. };
  18054. Object.defineProperty(Scene.prototype, "uid", {
  18055. /**
  18056. * Return a unique id as a string which can serve as an identifier for the scene
  18057. */
  18058. get: function () {
  18059. if (!this._uid) {
  18060. this._uid = BABYLON.Tools.RandomId();
  18061. }
  18062. return this._uid;
  18063. },
  18064. enumerable: true,
  18065. configurable: true
  18066. });
  18067. /**
  18068. * Add an externaly attached data from its key.
  18069. * This method call will fail and return false, if such key already exists.
  18070. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18071. * @param key the unique key that identifies the data
  18072. * @param data the data object to associate to the key for this Engine instance
  18073. * @return true if no such key were already present and the data was added successfully, false otherwise
  18074. */
  18075. Scene.prototype.addExternalData = function (key, data) {
  18076. return this._externalData.add(key, data);
  18077. };
  18078. /**
  18079. * Get an externaly attached data from its key
  18080. * @param key the unique key that identifies the data
  18081. * @return the associated data, if present (can be null), or undefined if not present
  18082. */
  18083. Scene.prototype.getExternalData = function (key) {
  18084. return this._externalData.get(key);
  18085. };
  18086. /**
  18087. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18088. * @param key the unique key that identifies the data
  18089. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18090. * @return the associated data, can be null if the factory returned null.
  18091. */
  18092. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18093. return this._externalData.getOrAddWithFactory(key, factory);
  18094. };
  18095. /**
  18096. * Remove an externaly attached data from the Engine instance
  18097. * @param key the unique key that identifies the data
  18098. * @return true if the data was successfully removed, false if it doesn't exist
  18099. */
  18100. Scene.prototype.removeExternalData = function (key) {
  18101. return this._externalData.remove(key);
  18102. };
  18103. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18104. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18105. var material = subMesh.getMaterial();
  18106. if (mesh.showSubMeshesBoundingBox) {
  18107. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18108. }
  18109. if (material) {
  18110. // Render targets
  18111. if (material.getRenderTargetTextures) {
  18112. if (this._processedMaterials.indexOf(material) === -1) {
  18113. this._processedMaterials.push(material);
  18114. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18115. }
  18116. }
  18117. // Dispatch
  18118. this._activeIndices.addCount(subMesh.indexCount, false);
  18119. this._renderingManager.dispatch(subMesh);
  18120. }
  18121. }
  18122. };
  18123. Scene.prototype._isInIntermediateRendering = function () {
  18124. return this._intermediateRendering;
  18125. };
  18126. Scene.prototype._evaluateActiveMeshes = function () {
  18127. this.activeCamera._activeMeshes.reset();
  18128. this._activeMeshes.reset();
  18129. this._renderingManager.reset();
  18130. this._processedMaterials.reset();
  18131. this._activeParticleSystems.reset();
  18132. this._activeSkeletons.reset();
  18133. this._softwareSkinnedMeshes.reset();
  18134. this._boundingBoxRenderer.reset();
  18135. this._edgesRenderers.reset();
  18136. // Meshes
  18137. var meshes;
  18138. var len;
  18139. if (this._selectionOctree) {
  18140. var selection = this._selectionOctree.select(this._frustumPlanes);
  18141. meshes = selection.data;
  18142. len = selection.length;
  18143. }
  18144. else {
  18145. len = this.meshes.length;
  18146. meshes = this.meshes;
  18147. }
  18148. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18149. var mesh = meshes[meshIndex];
  18150. if (mesh.isBlocked) {
  18151. continue;
  18152. }
  18153. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18154. if (!mesh.isReady() || !mesh.isEnabled()) {
  18155. continue;
  18156. }
  18157. mesh.computeWorldMatrix();
  18158. // Intersections
  18159. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18160. this._meshesForIntersections.pushNoDuplicate(mesh);
  18161. }
  18162. // Switch to current LOD
  18163. var meshLOD = mesh.getLOD(this.activeCamera);
  18164. if (!meshLOD) {
  18165. continue;
  18166. }
  18167. mesh._preActivate();
  18168. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18169. this._activeMeshes.push(mesh);
  18170. this.activeCamera._activeMeshes.push(mesh);
  18171. mesh._activate(this._renderId);
  18172. this._activeMesh(mesh, meshLOD);
  18173. }
  18174. }
  18175. // Particle systems
  18176. this._particlesDuration.beginMonitoring();
  18177. var beforeParticlesDate = BABYLON.Tools.Now;
  18178. if (this.particlesEnabled) {
  18179. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18180. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18181. var particleSystem = this.particleSystems[particleIndex];
  18182. if (!particleSystem.isStarted()) {
  18183. continue;
  18184. }
  18185. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18186. this._activeParticleSystems.push(particleSystem);
  18187. particleSystem.animate();
  18188. }
  18189. }
  18190. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18191. }
  18192. this._particlesDuration.endMonitoring(false);
  18193. };
  18194. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18195. if (mesh.skeleton && this.skeletonsEnabled) {
  18196. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18197. mesh.skeleton.prepare();
  18198. }
  18199. if (!mesh.computeBonesUsingShaders) {
  18200. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18201. }
  18202. }
  18203. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18204. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18205. }
  18206. if (sourceMesh._edgesRenderer) {
  18207. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18208. }
  18209. if (mesh && mesh.subMeshes) {
  18210. // Submeshes Octrees
  18211. var len;
  18212. var subMeshes;
  18213. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18214. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18215. len = intersections.length;
  18216. subMeshes = intersections.data;
  18217. }
  18218. else {
  18219. subMeshes = mesh.subMeshes;
  18220. len = subMeshes.length;
  18221. }
  18222. for (var subIndex = 0; subIndex < len; subIndex++) {
  18223. var subMesh = subMeshes[subIndex];
  18224. this._evaluateSubMesh(subMesh, mesh);
  18225. }
  18226. }
  18227. };
  18228. Scene.prototype.updateTransformMatrix = function (force) {
  18229. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18230. };
  18231. Scene.prototype._renderForCamera = function (camera) {
  18232. var engine = this._engine;
  18233. var startTime = BABYLON.Tools.Now;
  18234. this.activeCamera = camera;
  18235. if (!this.activeCamera)
  18236. throw new Error("Active camera not set");
  18237. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18238. // Viewport
  18239. engine.setViewport(this.activeCamera.viewport);
  18240. // Camera
  18241. this.resetCachedMaterial();
  18242. this._renderId++;
  18243. this.updateTransformMatrix();
  18244. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18245. // Meshes
  18246. this._evaluateActiveMeshesDuration.beginMonitoring();
  18247. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18248. this._evaluateActiveMeshes();
  18249. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18250. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18251. // Software skinning
  18252. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18253. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18254. mesh.applySkeleton(mesh.skeleton);
  18255. }
  18256. // Render targets
  18257. this._renderTargetsDuration.beginMonitoring();
  18258. var needsRestoreFrameBuffer = false;
  18259. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18260. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18261. this._intermediateRendering = true;
  18262. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18263. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18264. var renderTarget = this._renderTargets.data[renderIndex];
  18265. if (renderTarget._shouldRender()) {
  18266. this._renderId++;
  18267. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18268. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18269. }
  18270. }
  18271. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18272. this._intermediateRendering = false;
  18273. this._renderId++;
  18274. needsRestoreFrameBuffer = true; // Restore back buffer
  18275. }
  18276. // Render HighlightLayer Texture
  18277. var stencilState = this._engine.getStencilBuffer();
  18278. var renderhighlights = false;
  18279. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18280. this._intermediateRendering = true;
  18281. for (var i = 0; i < this.highlightLayers.length; i++) {
  18282. var highlightLayer = this.highlightLayers[i];
  18283. if (highlightLayer.shouldRender() &&
  18284. (!highlightLayer.camera ||
  18285. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18286. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18287. renderhighlights = true;
  18288. var renderTarget = highlightLayer._mainTexture;
  18289. if (renderTarget._shouldRender()) {
  18290. this._renderId++;
  18291. renderTarget.render(false, false);
  18292. needsRestoreFrameBuffer = true;
  18293. }
  18294. }
  18295. }
  18296. this._intermediateRendering = false;
  18297. this._renderId++;
  18298. }
  18299. if (needsRestoreFrameBuffer) {
  18300. engine.restoreDefaultFramebuffer();
  18301. }
  18302. this._renderTargetsDuration.endMonitoring(false);
  18303. // Prepare Frame
  18304. this.postProcessManager._prepareFrame();
  18305. this._renderDuration.beginMonitoring();
  18306. // Backgrounds
  18307. var layerIndex;
  18308. var layer;
  18309. if (this.layers.length) {
  18310. engine.setDepthBuffer(false);
  18311. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18312. layer = this.layers[layerIndex];
  18313. if (layer.isBackground) {
  18314. layer.render();
  18315. }
  18316. }
  18317. engine.setDepthBuffer(true);
  18318. }
  18319. // Render
  18320. BABYLON.Tools.StartPerformanceCounter("Main render");
  18321. // Activate HighlightLayer stencil
  18322. if (renderhighlights) {
  18323. this._engine.setStencilBuffer(true);
  18324. }
  18325. this._renderingManager.render(null, null, true, true);
  18326. // Restore HighlightLayer stencil
  18327. if (renderhighlights) {
  18328. this._engine.setStencilBuffer(stencilState);
  18329. }
  18330. BABYLON.Tools.EndPerformanceCounter("Main render");
  18331. // Bounding boxes
  18332. this._boundingBoxRenderer.render();
  18333. // Edges
  18334. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18335. this._edgesRenderers.data[edgesRendererIndex].render();
  18336. }
  18337. // Lens flares
  18338. if (this.lensFlaresEnabled) {
  18339. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18340. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18341. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18342. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18343. lensFlareSystem.render();
  18344. }
  18345. }
  18346. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18347. }
  18348. // Foregrounds
  18349. if (this.layers.length) {
  18350. engine.setDepthBuffer(false);
  18351. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18352. layer = this.layers[layerIndex];
  18353. if (!layer.isBackground) {
  18354. layer.render();
  18355. }
  18356. }
  18357. engine.setDepthBuffer(true);
  18358. }
  18359. // Highlight Layer
  18360. if (renderhighlights) {
  18361. engine.setDepthBuffer(false);
  18362. for (var i = 0; i < this.highlightLayers.length; i++) {
  18363. if (this.highlightLayers[i].shouldRender()) {
  18364. this.highlightLayers[i].render();
  18365. }
  18366. }
  18367. engine.setDepthBuffer(true);
  18368. }
  18369. this._renderDuration.endMonitoring(false);
  18370. // Finalize frame
  18371. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18372. // Update camera
  18373. this.activeCamera._updateFromScene();
  18374. // Reset some special arrays
  18375. this._renderTargets.reset();
  18376. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18377. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18378. };
  18379. Scene.prototype._processSubCameras = function (camera) {
  18380. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18381. this._renderForCamera(camera);
  18382. return;
  18383. }
  18384. // rig cameras
  18385. for (var index = 0; index < camera._rigCameras.length; index++) {
  18386. this._renderForCamera(camera._rigCameras[index]);
  18387. }
  18388. this.activeCamera = camera;
  18389. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18390. // Update camera
  18391. this.activeCamera._updateFromScene();
  18392. };
  18393. Scene.prototype._checkIntersections = function () {
  18394. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18395. var sourceMesh = this._meshesForIntersections.data[index];
  18396. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18397. var action = sourceMesh.actionManager.actions[actionIndex];
  18398. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18399. var parameters = action.getTriggerParameter();
  18400. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18401. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18402. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18403. if (areIntersecting && currentIntersectionInProgress === -1) {
  18404. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18405. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18406. sourceMesh._intersectionsInProgress.push(otherMesh);
  18407. }
  18408. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18409. sourceMesh._intersectionsInProgress.push(otherMesh);
  18410. }
  18411. }
  18412. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18413. //They intersected, and now they don't.
  18414. //is this trigger an exit trigger? execute an event.
  18415. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18416. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18417. }
  18418. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18419. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18420. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18421. }
  18422. }
  18423. }
  18424. }
  18425. }
  18426. };
  18427. Scene.prototype.render = function () {
  18428. this._lastFrameDuration.beginMonitoring();
  18429. this._particlesDuration.fetchNewFrame();
  18430. this._spritesDuration.fetchNewFrame();
  18431. this._activeParticles.fetchNewFrame();
  18432. this._renderDuration.fetchNewFrame();
  18433. this._renderTargetsDuration.fetchNewFrame();
  18434. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18435. this._totalVertices.fetchNewFrame();
  18436. this._activeIndices.fetchNewFrame();
  18437. this._activeBones.fetchNewFrame();
  18438. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18439. this._meshesForIntersections.reset();
  18440. this.resetCachedMaterial();
  18441. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18442. // Actions
  18443. if (this.actionManager) {
  18444. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18445. }
  18446. //Simplification Queue
  18447. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18448. this.simplificationQueue.executeNext();
  18449. }
  18450. // Animations
  18451. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18452. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18453. this._animate();
  18454. // Physics
  18455. if (this._physicsEngine) {
  18456. BABYLON.Tools.StartPerformanceCounter("Physics");
  18457. this._physicsEngine._step(deltaTime / 1000.0);
  18458. BABYLON.Tools.EndPerformanceCounter("Physics");
  18459. }
  18460. // Before render
  18461. this.onBeforeRenderObservable.notifyObservers(this);
  18462. // Customs render targets
  18463. this._renderTargetsDuration.beginMonitoring();
  18464. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18465. var engine = this.getEngine();
  18466. var currentActiveCamera = this.activeCamera;
  18467. if (this.renderTargetsEnabled) {
  18468. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18469. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18470. var renderTarget = this.customRenderTargets[customIndex];
  18471. if (renderTarget._shouldRender()) {
  18472. this._renderId++;
  18473. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18474. if (!this.activeCamera)
  18475. throw new Error("Active camera not set");
  18476. // Viewport
  18477. engine.setViewport(this.activeCamera.viewport);
  18478. // Camera
  18479. this.updateTransformMatrix();
  18480. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18481. }
  18482. }
  18483. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18484. this._renderId++;
  18485. }
  18486. if (this.customRenderTargets.length > 0) {
  18487. engine.restoreDefaultFramebuffer();
  18488. }
  18489. this._renderTargetsDuration.endMonitoring();
  18490. this.activeCamera = currentActiveCamera;
  18491. // Procedural textures
  18492. if (this.proceduralTexturesEnabled) {
  18493. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18494. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18495. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18496. if (proceduralTexture._shouldRender()) {
  18497. proceduralTexture.render();
  18498. }
  18499. }
  18500. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18501. }
  18502. // Clear
  18503. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18504. // Shadows
  18505. if (this.shadowsEnabled) {
  18506. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18507. var light = this.lights[lightIndex];
  18508. var shadowGenerator = light.getShadowGenerator();
  18509. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18510. this._renderTargets.push(shadowGenerator.getShadowMap());
  18511. }
  18512. }
  18513. }
  18514. // Depth renderer
  18515. if (this._depthRenderer) {
  18516. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18517. }
  18518. // RenderPipeline
  18519. this.postProcessRenderPipelineManager.update();
  18520. // Multi-cameras?
  18521. if (this.activeCameras.length > 0) {
  18522. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18523. if (cameraIndex > 0) {
  18524. this._engine.clear(0, false, true, true);
  18525. }
  18526. this._processSubCameras(this.activeCameras[cameraIndex]);
  18527. }
  18528. }
  18529. else {
  18530. if (!this.activeCamera) {
  18531. throw new Error("No camera defined");
  18532. }
  18533. this._processSubCameras(this.activeCamera);
  18534. }
  18535. // Intersection checks
  18536. this._checkIntersections();
  18537. // Update the audio listener attached to the camera
  18538. if (BABYLON.AudioEngine) {
  18539. this._updateAudioParameters();
  18540. }
  18541. // After render
  18542. if (this.afterRender) {
  18543. this.afterRender();
  18544. }
  18545. this.onAfterRenderObservable.notifyObservers(this);
  18546. // Cleaning
  18547. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18548. this._toBeDisposed.data[index].dispose();
  18549. this._toBeDisposed[index] = null;
  18550. }
  18551. this._toBeDisposed.reset();
  18552. if (this.dumpNextRenderTargets) {
  18553. this.dumpNextRenderTargets = false;
  18554. }
  18555. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18556. this._lastFrameDuration.endMonitoring();
  18557. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18558. this._totalLightsCounter.addCount(this.lights.length, true);
  18559. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18560. this._totalTexturesCounter.addCount(this.textures.length, true);
  18561. this._activeBones.addCount(0, true);
  18562. this._activeIndices.addCount(0, true);
  18563. this._activeParticles.addCount(0, true);
  18564. };
  18565. Scene.prototype._updateAudioParameters = function () {
  18566. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18567. return;
  18568. }
  18569. var listeningCamera;
  18570. var audioEngine = BABYLON.Engine.audioEngine;
  18571. if (this.activeCameras.length > 0) {
  18572. listeningCamera = this.activeCameras[0];
  18573. }
  18574. else {
  18575. listeningCamera = this.activeCamera;
  18576. }
  18577. if (listeningCamera && audioEngine.canUseWebAudio) {
  18578. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18579. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18580. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18581. cameraDirection.normalize();
  18582. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18583. var i;
  18584. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18585. var sound = this.mainSoundTrack.soundCollection[i];
  18586. if (sound.useCustomAttenuation) {
  18587. sound.updateDistanceFromListener();
  18588. }
  18589. }
  18590. for (i = 0; i < this.soundTracks.length; i++) {
  18591. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18592. sound = this.soundTracks[i].soundCollection[j];
  18593. if (sound.useCustomAttenuation) {
  18594. sound.updateDistanceFromListener();
  18595. }
  18596. }
  18597. }
  18598. }
  18599. };
  18600. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18601. // Audio
  18602. get: function () {
  18603. return this._audioEnabled;
  18604. },
  18605. set: function (value) {
  18606. this._audioEnabled = value;
  18607. if (BABYLON.AudioEngine) {
  18608. if (this._audioEnabled) {
  18609. this._enableAudio();
  18610. }
  18611. else {
  18612. this._disableAudio();
  18613. }
  18614. }
  18615. },
  18616. enumerable: true,
  18617. configurable: true
  18618. });
  18619. Scene.prototype._disableAudio = function () {
  18620. var i;
  18621. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18622. this.mainSoundTrack.soundCollection[i].pause();
  18623. }
  18624. for (i = 0; i < this.soundTracks.length; i++) {
  18625. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18626. this.soundTracks[i].soundCollection[j].pause();
  18627. }
  18628. }
  18629. };
  18630. Scene.prototype._enableAudio = function () {
  18631. var i;
  18632. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18633. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18634. this.mainSoundTrack.soundCollection[i].play();
  18635. }
  18636. }
  18637. for (i = 0; i < this.soundTracks.length; i++) {
  18638. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18639. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18640. this.soundTracks[i].soundCollection[j].play();
  18641. }
  18642. }
  18643. }
  18644. };
  18645. Object.defineProperty(Scene.prototype, "headphone", {
  18646. get: function () {
  18647. return this._headphone;
  18648. },
  18649. set: function (value) {
  18650. this._headphone = value;
  18651. if (BABYLON.AudioEngine) {
  18652. if (this._headphone) {
  18653. this._switchAudioModeForHeadphones();
  18654. }
  18655. else {
  18656. this._switchAudioModeForNormalSpeakers();
  18657. }
  18658. }
  18659. },
  18660. enumerable: true,
  18661. configurable: true
  18662. });
  18663. Scene.prototype._switchAudioModeForHeadphones = function () {
  18664. this.mainSoundTrack.switchPanningModelToHRTF();
  18665. for (var i = 0; i < this.soundTracks.length; i++) {
  18666. this.soundTracks[i].switchPanningModelToHRTF();
  18667. }
  18668. };
  18669. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18670. this.mainSoundTrack.switchPanningModelToEqualPower();
  18671. for (var i = 0; i < this.soundTracks.length; i++) {
  18672. this.soundTracks[i].switchPanningModelToEqualPower();
  18673. }
  18674. };
  18675. Scene.prototype.enableDepthRenderer = function () {
  18676. if (this._depthRenderer) {
  18677. return this._depthRenderer;
  18678. }
  18679. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18680. return this._depthRenderer;
  18681. };
  18682. Scene.prototype.disableDepthRenderer = function () {
  18683. if (!this._depthRenderer) {
  18684. return;
  18685. }
  18686. this._depthRenderer.dispose();
  18687. this._depthRenderer = null;
  18688. };
  18689. Scene.prototype.freezeMaterials = function () {
  18690. for (var i = 0; i < this.materials.length; i++) {
  18691. this.materials[i].freeze();
  18692. }
  18693. };
  18694. Scene.prototype.unfreezeMaterials = function () {
  18695. for (var i = 0; i < this.materials.length; i++) {
  18696. this.materials[i].unfreeze();
  18697. }
  18698. };
  18699. Scene.prototype.dispose = function () {
  18700. this.beforeRender = null;
  18701. this.afterRender = null;
  18702. this.skeletons = [];
  18703. this._boundingBoxRenderer.dispose();
  18704. if (this._depthRenderer) {
  18705. this._depthRenderer.dispose();
  18706. }
  18707. // Debug layer
  18708. if (this._debugLayer) {
  18709. this._debugLayer.hide();
  18710. }
  18711. // Events
  18712. this.onDisposeObservable.notifyObservers(this);
  18713. this.onDisposeObservable.clear();
  18714. this.onBeforeRenderObservable.clear();
  18715. this.onAfterRenderObservable.clear();
  18716. this.detachControl();
  18717. // Release sounds & sounds tracks
  18718. if (BABYLON.AudioEngine) {
  18719. this.disposeSounds();
  18720. }
  18721. // Detach cameras
  18722. var canvas = this._engine.getRenderingCanvas();
  18723. var index;
  18724. for (index = 0; index < this.cameras.length; index++) {
  18725. this.cameras[index].detachControl(canvas);
  18726. }
  18727. // Release lights
  18728. while (this.lights.length) {
  18729. this.lights[0].dispose();
  18730. }
  18731. // Release meshes
  18732. while (this.meshes.length) {
  18733. this.meshes[0].dispose(true);
  18734. }
  18735. // Release cameras
  18736. while (this.cameras.length) {
  18737. this.cameras[0].dispose();
  18738. }
  18739. // Release materials
  18740. while (this.materials.length) {
  18741. this.materials[0].dispose();
  18742. }
  18743. // Release particles
  18744. while (this.particleSystems.length) {
  18745. this.particleSystems[0].dispose();
  18746. }
  18747. // Release sprites
  18748. while (this.spriteManagers.length) {
  18749. this.spriteManagers[0].dispose();
  18750. }
  18751. // Release layers
  18752. while (this.layers.length) {
  18753. this.layers[0].dispose();
  18754. }
  18755. while (this.highlightLayers.length) {
  18756. this.highlightLayers[0].dispose();
  18757. }
  18758. // Release textures
  18759. while (this.textures.length) {
  18760. this.textures[0].dispose();
  18761. }
  18762. // Post-processes
  18763. this.postProcessManager.dispose();
  18764. // Physics
  18765. if (this._physicsEngine) {
  18766. this.disablePhysicsEngine();
  18767. }
  18768. // Remove from engine
  18769. index = this._engine.scenes.indexOf(this);
  18770. if (index > -1) {
  18771. this._engine.scenes.splice(index, 1);
  18772. }
  18773. this._engine.wipeCaches();
  18774. };
  18775. // Release sounds & sounds tracks
  18776. Scene.prototype.disposeSounds = function () {
  18777. this.mainSoundTrack.dispose();
  18778. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18779. this.soundTracks[scIndex].dispose();
  18780. }
  18781. };
  18782. // Octrees
  18783. Scene.prototype.getWorldExtends = function () {
  18784. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18785. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18786. for (var index = 0; index < this.meshes.length; index++) {
  18787. var mesh = this.meshes[index];
  18788. mesh.computeWorldMatrix(true);
  18789. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18790. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18791. BABYLON.Tools.CheckExtends(minBox, min, max);
  18792. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18793. }
  18794. return {
  18795. min: min,
  18796. max: max
  18797. };
  18798. };
  18799. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18800. if (maxCapacity === void 0) { maxCapacity = 64; }
  18801. if (maxDepth === void 0) { maxDepth = 2; }
  18802. if (!this._selectionOctree) {
  18803. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18804. }
  18805. var worldExtends = this.getWorldExtends();
  18806. // Update octree
  18807. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18808. return this._selectionOctree;
  18809. };
  18810. // Picking
  18811. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18812. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18813. var engine = this._engine;
  18814. if (!camera) {
  18815. if (!this.activeCamera)
  18816. throw new Error("Active camera not set");
  18817. camera = this.activeCamera;
  18818. }
  18819. var cameraViewport = camera.viewport;
  18820. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18821. // Moving coordinates to local viewport world
  18822. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18823. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18824. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18825. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18826. };
  18827. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18828. var engine = this._engine;
  18829. if (!camera) {
  18830. if (!this.activeCamera)
  18831. throw new Error("Active camera not set");
  18832. camera = this.activeCamera;
  18833. }
  18834. var cameraViewport = camera.viewport;
  18835. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18836. var identity = BABYLON.Matrix.Identity();
  18837. // Moving coordinates to local viewport world
  18838. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18839. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18840. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18841. };
  18842. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18843. var pickingInfo = null;
  18844. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18845. var mesh = this.meshes[meshIndex];
  18846. if (predicate) {
  18847. if (!predicate(mesh)) {
  18848. continue;
  18849. }
  18850. }
  18851. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18852. continue;
  18853. }
  18854. var world = mesh.getWorldMatrix();
  18855. var ray = rayFunction(world);
  18856. var result = mesh.intersects(ray, fastCheck);
  18857. if (!result || !result.hit)
  18858. continue;
  18859. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18860. continue;
  18861. pickingInfo = result;
  18862. if (fastCheck) {
  18863. break;
  18864. }
  18865. }
  18866. return pickingInfo || new BABYLON.PickingInfo();
  18867. };
  18868. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18869. var pickingInfos = new Array();
  18870. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18871. var mesh = this.meshes[meshIndex];
  18872. if (predicate) {
  18873. if (!predicate(mesh)) {
  18874. continue;
  18875. }
  18876. }
  18877. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18878. continue;
  18879. }
  18880. var world = mesh.getWorldMatrix();
  18881. var ray = rayFunction(world);
  18882. var result = mesh.intersects(ray, false);
  18883. if (!result || !result.hit)
  18884. continue;
  18885. pickingInfos.push(result);
  18886. }
  18887. return pickingInfos;
  18888. };
  18889. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18890. var pickingInfo = null;
  18891. camera = camera || this.activeCamera;
  18892. if (this.spriteManagers.length > 0) {
  18893. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18894. var spriteManager = this.spriteManagers[spriteIndex];
  18895. if (!spriteManager.isPickable) {
  18896. continue;
  18897. }
  18898. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18899. if (!result || !result.hit)
  18900. continue;
  18901. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18902. continue;
  18903. pickingInfo = result;
  18904. if (fastCheck) {
  18905. break;
  18906. }
  18907. }
  18908. }
  18909. return pickingInfo || new BABYLON.PickingInfo();
  18910. };
  18911. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18912. /// <param name="x">X position on screen</param>
  18913. /// <param name="y">Y position on screen</param>
  18914. /// <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>
  18915. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18916. /// <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>
  18917. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18918. var _this = this;
  18919. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18920. };
  18921. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18922. /// <param name="x">X position on screen</param>
  18923. /// <param name="y">Y position on screen</param>
  18924. /// <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>
  18925. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18926. /// <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>
  18927. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18928. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18929. };
  18930. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18931. var _this = this;
  18932. return this._internalPick(function (world) {
  18933. if (!_this._pickWithRayInverseMatrix) {
  18934. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18935. }
  18936. world.invertToRef(_this._pickWithRayInverseMatrix);
  18937. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18938. }, predicate, fastCheck);
  18939. };
  18940. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18941. /// <param name="x">X position on screen</param>
  18942. /// <param name="y">Y position on screen</param>
  18943. /// <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>
  18944. /// <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>
  18945. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18946. var _this = this;
  18947. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18948. };
  18949. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18950. /// <param name="ray">Ray to use</param>
  18951. /// <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>
  18952. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18953. var _this = this;
  18954. return this._internalMultiPick(function (world) {
  18955. if (!_this._pickWithRayInverseMatrix) {
  18956. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18957. }
  18958. world.invertToRef(_this._pickWithRayInverseMatrix);
  18959. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18960. }, predicate);
  18961. };
  18962. Scene.prototype.setPointerOverMesh = function (mesh) {
  18963. if (this._pointerOverMesh === mesh) {
  18964. return;
  18965. }
  18966. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18967. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18968. }
  18969. this._pointerOverMesh = mesh;
  18970. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18971. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18972. }
  18973. };
  18974. Scene.prototype.getPointerOverMesh = function () {
  18975. return this._pointerOverMesh;
  18976. };
  18977. Scene.prototype.setPointerOverSprite = function (sprite) {
  18978. if (this._pointerOverSprite === sprite) {
  18979. return;
  18980. }
  18981. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18982. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18983. }
  18984. this._pointerOverSprite = sprite;
  18985. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18986. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18987. }
  18988. };
  18989. Scene.prototype.getPointerOverSprite = function () {
  18990. return this._pointerOverSprite;
  18991. };
  18992. // Physics
  18993. Scene.prototype.getPhysicsEngine = function () {
  18994. return this._physicsEngine;
  18995. };
  18996. /**
  18997. * Enables physics to the current scene
  18998. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18999. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19000. * @return {boolean} was the physics engine initialized
  19001. */
  19002. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19003. if (this._physicsEngine) {
  19004. return true;
  19005. }
  19006. try {
  19007. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19008. return true;
  19009. }
  19010. catch (e) {
  19011. BABYLON.Tools.Error(e.message);
  19012. return false;
  19013. }
  19014. };
  19015. Scene.prototype.disablePhysicsEngine = function () {
  19016. if (!this._physicsEngine) {
  19017. return;
  19018. }
  19019. this._physicsEngine.dispose();
  19020. this._physicsEngine = undefined;
  19021. };
  19022. Scene.prototype.isPhysicsEnabled = function () {
  19023. return this._physicsEngine !== undefined;
  19024. };
  19025. /**
  19026. *
  19027. * Sets the gravity of the physics engine (and NOT of the scene)
  19028. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19029. */
  19030. Scene.prototype.setGravity = function (gravity) {
  19031. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19032. if (!this._physicsEngine) {
  19033. return;
  19034. }
  19035. this._physicsEngine.setGravity(gravity);
  19036. };
  19037. /**
  19038. * Legacy support, using the new API
  19039. * @Deprecated
  19040. */
  19041. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19042. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19043. if (parts.parts) {
  19044. options = parts;
  19045. parts = parts.parts;
  19046. }
  19047. var mainMesh = parts[0].mesh;
  19048. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19049. for (var index = 1; index < parts.length; index++) {
  19050. var mesh = parts[index].mesh;
  19051. if (mesh.parent !== mainMesh) {
  19052. mesh.position = mesh.position.subtract(mainMesh.position);
  19053. mesh.parent = mainMesh;
  19054. }
  19055. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19056. }
  19057. mainMesh.physicsImpostor.forceUpdate();
  19058. };
  19059. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19060. var mesh = compound.parts[0].mesh;
  19061. mesh.physicsImpostor.dispose();
  19062. mesh.physicsImpostor = null;
  19063. };
  19064. // Misc.
  19065. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19066. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19067. // Light
  19068. if (this.lights.length === 0) {
  19069. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19070. }
  19071. // Camera
  19072. if (!this.activeCamera) {
  19073. // Compute position
  19074. var worldExtends = this.getWorldExtends();
  19075. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19076. var camera;
  19077. if (createArcRotateCamera) {
  19078. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19079. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19080. camera.setTarget(worldCenter);
  19081. }
  19082. else {
  19083. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19084. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19085. camera.setTarget(worldCenter);
  19086. }
  19087. this.activeCamera = camera;
  19088. }
  19089. };
  19090. // Tags
  19091. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19092. if (tagsQuery === undefined) {
  19093. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19094. return list;
  19095. }
  19096. var listByTags = [];
  19097. forEach = forEach || (function (item) { return; });
  19098. for (var i in list) {
  19099. var item = list[i];
  19100. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19101. listByTags.push(item);
  19102. forEach(item);
  19103. }
  19104. }
  19105. return listByTags;
  19106. };
  19107. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19108. return this._getByTags(this.meshes, tagsQuery, forEach);
  19109. };
  19110. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19111. return this._getByTags(this.cameras, tagsQuery, forEach);
  19112. };
  19113. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19114. return this._getByTags(this.lights, tagsQuery, forEach);
  19115. };
  19116. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19117. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19118. };
  19119. /**
  19120. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19121. * This allowed control for front to back rendering or reversly depending of the special needs.
  19122. *
  19123. * @param renderingGroupId The rendering group id corresponding to its index
  19124. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19125. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19126. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19127. */
  19128. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19129. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19130. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19131. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19132. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19133. };
  19134. /**
  19135. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19136. *
  19137. * @param renderingGroupId The rendering group id corresponding to its index
  19138. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19139. */
  19140. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  19141. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  19142. };
  19143. // Statics
  19144. Scene._FOGMODE_NONE = 0;
  19145. Scene._FOGMODE_EXP = 1;
  19146. Scene._FOGMODE_EXP2 = 2;
  19147. Scene._FOGMODE_LINEAR = 3;
  19148. Scene.MinDeltaTime = 1.0;
  19149. Scene.MaxDeltaTime = 1000.0;
  19150. return Scene;
  19151. }());
  19152. BABYLON.Scene = Scene;
  19153. })(BABYLON || (BABYLON = {}));
  19154. //# sourceMappingURL=babylon.scene.js.map
  19155. var BABYLON;
  19156. (function (BABYLON) {
  19157. var Buffer = (function () {
  19158. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19159. if (engine instanceof BABYLON.Mesh) {
  19160. this._engine = engine.getScene().getEngine();
  19161. }
  19162. else {
  19163. this._engine = engine;
  19164. }
  19165. this._updatable = updatable;
  19166. this._data = data;
  19167. this._strideSize = stride;
  19168. if (!postponeInternalCreation) {
  19169. this.create();
  19170. }
  19171. this._instanced = instanced;
  19172. }
  19173. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19174. // a lot of these parameters are ignored as they are overriden by the buffer
  19175. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19176. };
  19177. // Properties
  19178. Buffer.prototype.isUpdatable = function () {
  19179. return this._updatable;
  19180. };
  19181. Buffer.prototype.getData = function () {
  19182. return this._data;
  19183. };
  19184. Buffer.prototype.getBuffer = function () {
  19185. return this._buffer;
  19186. };
  19187. Buffer.prototype.getStrideSize = function () {
  19188. return this._strideSize;
  19189. };
  19190. Buffer.prototype.getIsInstanced = function () {
  19191. return this._instanced;
  19192. };
  19193. // Methods
  19194. Buffer.prototype.create = function (data) {
  19195. if (!data && this._buffer) {
  19196. return; // nothing to do
  19197. }
  19198. data = data || this._data;
  19199. if (!this._buffer) {
  19200. if (this._updatable) {
  19201. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19202. this._data = data;
  19203. }
  19204. else {
  19205. this._buffer = this._engine.createVertexBuffer(data);
  19206. }
  19207. }
  19208. else if (this._updatable) {
  19209. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19210. this._data = data;
  19211. }
  19212. };
  19213. Buffer.prototype.update = function (data) {
  19214. this.create(data);
  19215. };
  19216. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19217. if (!this._buffer) {
  19218. return;
  19219. }
  19220. if (this._updatable) {
  19221. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19222. this._data = null;
  19223. }
  19224. };
  19225. Buffer.prototype.dispose = function () {
  19226. if (!this._buffer) {
  19227. return;
  19228. }
  19229. if (this._engine._releaseBuffer(this._buffer)) {
  19230. this._buffer = null;
  19231. }
  19232. };
  19233. return Buffer;
  19234. }());
  19235. BABYLON.Buffer = Buffer;
  19236. })(BABYLON || (BABYLON = {}));
  19237. //# sourceMappingURL=babylon.buffer.js.map
  19238. var BABYLON;
  19239. (function (BABYLON) {
  19240. var VertexBuffer = (function () {
  19241. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19242. if (!stride) {
  19243. // Deduce stride from kind
  19244. switch (kind) {
  19245. case VertexBuffer.PositionKind:
  19246. stride = 3;
  19247. break;
  19248. case VertexBuffer.NormalKind:
  19249. stride = 3;
  19250. break;
  19251. case VertexBuffer.UVKind:
  19252. case VertexBuffer.UV2Kind:
  19253. case VertexBuffer.UV3Kind:
  19254. case VertexBuffer.UV4Kind:
  19255. case VertexBuffer.UV5Kind:
  19256. case VertexBuffer.UV6Kind:
  19257. stride = 2;
  19258. break;
  19259. case VertexBuffer.ColorKind:
  19260. stride = 4;
  19261. break;
  19262. case VertexBuffer.MatricesIndicesKind:
  19263. case VertexBuffer.MatricesIndicesExtraKind:
  19264. stride = 4;
  19265. break;
  19266. case VertexBuffer.MatricesWeightsKind:
  19267. case VertexBuffer.MatricesWeightsExtraKind:
  19268. stride = 4;
  19269. break;
  19270. }
  19271. }
  19272. if (data instanceof BABYLON.Buffer) {
  19273. if (!stride) {
  19274. stride = data.getStrideSize();
  19275. }
  19276. this._buffer = data;
  19277. this._ownsBuffer = false;
  19278. }
  19279. else {
  19280. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19281. this._ownsBuffer = true;
  19282. }
  19283. this._stride = stride;
  19284. this._offset = offset ? offset : 0;
  19285. this._size = size ? size : stride;
  19286. this._kind = kind;
  19287. }
  19288. VertexBuffer.prototype.getKind = function () {
  19289. return this._kind;
  19290. };
  19291. // Properties
  19292. VertexBuffer.prototype.isUpdatable = function () {
  19293. return this._buffer.isUpdatable();
  19294. };
  19295. VertexBuffer.prototype.getData = function () {
  19296. return this._buffer.getData();
  19297. };
  19298. VertexBuffer.prototype.getBuffer = function () {
  19299. return this._buffer.getBuffer();
  19300. };
  19301. VertexBuffer.prototype.getStrideSize = function () {
  19302. return this._stride;
  19303. };
  19304. VertexBuffer.prototype.getOffset = function () {
  19305. return this._offset;
  19306. };
  19307. VertexBuffer.prototype.getSize = function () {
  19308. return this._size;
  19309. };
  19310. VertexBuffer.prototype.getIsInstanced = function () {
  19311. return this._buffer.getIsInstanced();
  19312. };
  19313. // Methods
  19314. VertexBuffer.prototype.create = function (data) {
  19315. return this._buffer.create(data);
  19316. };
  19317. VertexBuffer.prototype.update = function (data) {
  19318. return this._buffer.update(data);
  19319. };
  19320. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19321. return this._buffer.updateDirectly(data, offset);
  19322. };
  19323. VertexBuffer.prototype.dispose = function () {
  19324. if (this._ownsBuffer) {
  19325. this._buffer.dispose();
  19326. }
  19327. };
  19328. Object.defineProperty(VertexBuffer, "PositionKind", {
  19329. get: function () {
  19330. return VertexBuffer._PositionKind;
  19331. },
  19332. enumerable: true,
  19333. configurable: true
  19334. });
  19335. Object.defineProperty(VertexBuffer, "NormalKind", {
  19336. get: function () {
  19337. return VertexBuffer._NormalKind;
  19338. },
  19339. enumerable: true,
  19340. configurable: true
  19341. });
  19342. Object.defineProperty(VertexBuffer, "UVKind", {
  19343. get: function () {
  19344. return VertexBuffer._UVKind;
  19345. },
  19346. enumerable: true,
  19347. configurable: true
  19348. });
  19349. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19350. get: function () {
  19351. return VertexBuffer._UV2Kind;
  19352. },
  19353. enumerable: true,
  19354. configurable: true
  19355. });
  19356. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19357. get: function () {
  19358. return VertexBuffer._UV3Kind;
  19359. },
  19360. enumerable: true,
  19361. configurable: true
  19362. });
  19363. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19364. get: function () {
  19365. return VertexBuffer._UV4Kind;
  19366. },
  19367. enumerable: true,
  19368. configurable: true
  19369. });
  19370. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19371. get: function () {
  19372. return VertexBuffer._UV5Kind;
  19373. },
  19374. enumerable: true,
  19375. configurable: true
  19376. });
  19377. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19378. get: function () {
  19379. return VertexBuffer._UV6Kind;
  19380. },
  19381. enumerable: true,
  19382. configurable: true
  19383. });
  19384. Object.defineProperty(VertexBuffer, "ColorKind", {
  19385. get: function () {
  19386. return VertexBuffer._ColorKind;
  19387. },
  19388. enumerable: true,
  19389. configurable: true
  19390. });
  19391. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19392. get: function () {
  19393. return VertexBuffer._MatricesIndicesKind;
  19394. },
  19395. enumerable: true,
  19396. configurable: true
  19397. });
  19398. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19399. get: function () {
  19400. return VertexBuffer._MatricesWeightsKind;
  19401. },
  19402. enumerable: true,
  19403. configurable: true
  19404. });
  19405. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19406. get: function () {
  19407. return VertexBuffer._MatricesIndicesExtraKind;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19413. get: function () {
  19414. return VertexBuffer._MatricesWeightsExtraKind;
  19415. },
  19416. enumerable: true,
  19417. configurable: true
  19418. });
  19419. // Enums
  19420. VertexBuffer._PositionKind = "position";
  19421. VertexBuffer._NormalKind = "normal";
  19422. VertexBuffer._UVKind = "uv";
  19423. VertexBuffer._UV2Kind = "uv2";
  19424. VertexBuffer._UV3Kind = "uv3";
  19425. VertexBuffer._UV4Kind = "uv4";
  19426. VertexBuffer._UV5Kind = "uv5";
  19427. VertexBuffer._UV6Kind = "uv6";
  19428. VertexBuffer._ColorKind = "color";
  19429. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19430. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19431. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19432. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19433. return VertexBuffer;
  19434. }());
  19435. BABYLON.VertexBuffer = VertexBuffer;
  19436. })(BABYLON || (BABYLON = {}));
  19437. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19438. var BABYLON;
  19439. (function (BABYLON) {
  19440. /**
  19441. * Creates an instance based on a source mesh.
  19442. */
  19443. var InstancedMesh = (function (_super) {
  19444. __extends(InstancedMesh, _super);
  19445. function InstancedMesh(name, source) {
  19446. _super.call(this, name, source.getScene());
  19447. source.instances.push(this);
  19448. this._sourceMesh = source;
  19449. this.position.copyFrom(source.position);
  19450. this.rotation.copyFrom(source.rotation);
  19451. this.scaling.copyFrom(source.scaling);
  19452. if (source.rotationQuaternion) {
  19453. this.rotationQuaternion = source.rotationQuaternion.clone();
  19454. }
  19455. this.infiniteDistance = source.infiniteDistance;
  19456. this.setPivotMatrix(source.getPivotMatrix());
  19457. this.refreshBoundingInfo();
  19458. this._syncSubMeshes();
  19459. }
  19460. InstancedMesh.prototype.getClassName = function () {
  19461. return "InstancedMesh";
  19462. };
  19463. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19464. // Methods
  19465. get: function () {
  19466. return this._sourceMesh.receiveShadows;
  19467. },
  19468. enumerable: true,
  19469. configurable: true
  19470. });
  19471. Object.defineProperty(InstancedMesh.prototype, "material", {
  19472. get: function () {
  19473. return this._sourceMesh.material;
  19474. },
  19475. enumerable: true,
  19476. configurable: true
  19477. });
  19478. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19479. get: function () {
  19480. return this._sourceMesh.visibility;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19486. get: function () {
  19487. return this._sourceMesh.skeleton;
  19488. },
  19489. enumerable: true,
  19490. configurable: true
  19491. });
  19492. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19493. get: function () {
  19494. return this._sourceMesh.renderingGroupId;
  19495. },
  19496. enumerable: true,
  19497. configurable: true
  19498. });
  19499. InstancedMesh.prototype.getTotalVertices = function () {
  19500. return this._sourceMesh.getTotalVertices();
  19501. };
  19502. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19503. get: function () {
  19504. return this._sourceMesh;
  19505. },
  19506. enumerable: true,
  19507. configurable: true
  19508. });
  19509. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19510. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19511. };
  19512. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19513. return this._sourceMesh.isVerticesDataPresent(kind);
  19514. };
  19515. InstancedMesh.prototype.getIndices = function () {
  19516. return this._sourceMesh.getIndices();
  19517. };
  19518. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19519. get: function () {
  19520. return this._sourceMesh._positions;
  19521. },
  19522. enumerable: true,
  19523. configurable: true
  19524. });
  19525. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19526. var meshBB = this._sourceMesh.getBoundingInfo();
  19527. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19528. this._updateBoundingInfo();
  19529. };
  19530. InstancedMesh.prototype._preActivate = function () {
  19531. if (this._currentLOD) {
  19532. this._currentLOD._preActivate();
  19533. }
  19534. };
  19535. InstancedMesh.prototype._activate = function (renderId) {
  19536. if (this._currentLOD) {
  19537. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19538. }
  19539. };
  19540. InstancedMesh.prototype.getLOD = function (camera) {
  19541. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19542. if (this._currentLOD === this.sourceMesh) {
  19543. return this;
  19544. }
  19545. return this._currentLOD;
  19546. };
  19547. InstancedMesh.prototype._syncSubMeshes = function () {
  19548. this.releaseSubMeshes();
  19549. if (this._sourceMesh.subMeshes) {
  19550. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19551. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19552. }
  19553. }
  19554. };
  19555. InstancedMesh.prototype._generatePointsArray = function () {
  19556. return this._sourceMesh._generatePointsArray();
  19557. };
  19558. // Clone
  19559. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19560. var result = this._sourceMesh.createInstance(name);
  19561. // Deep copy
  19562. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19563. // Bounding info
  19564. this.refreshBoundingInfo();
  19565. // Parent
  19566. if (newParent) {
  19567. result.parent = newParent;
  19568. }
  19569. if (!doNotCloneChildren) {
  19570. // Children
  19571. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19572. var mesh = this.getScene().meshes[index];
  19573. if (mesh.parent === this) {
  19574. mesh.clone(mesh.name, result);
  19575. }
  19576. }
  19577. }
  19578. result.computeWorldMatrix(true);
  19579. return result;
  19580. };
  19581. // Dispoe
  19582. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19583. // Remove from mesh
  19584. var index = this._sourceMesh.instances.indexOf(this);
  19585. this._sourceMesh.instances.splice(index, 1);
  19586. _super.prototype.dispose.call(this, doNotRecurse);
  19587. };
  19588. return InstancedMesh;
  19589. }(BABYLON.AbstractMesh));
  19590. BABYLON.InstancedMesh = InstancedMesh;
  19591. })(BABYLON || (BABYLON = {}));
  19592. //# sourceMappingURL=babylon.instancedMesh.js.map
  19593. var BABYLON;
  19594. (function (BABYLON) {
  19595. var _InstancesBatch = (function () {
  19596. function _InstancesBatch() {
  19597. this.mustReturn = false;
  19598. this.visibleInstances = new Array();
  19599. this.renderSelf = new Array();
  19600. }
  19601. return _InstancesBatch;
  19602. }());
  19603. BABYLON._InstancesBatch = _InstancesBatch;
  19604. var Mesh = (function (_super) {
  19605. __extends(Mesh, _super);
  19606. /**
  19607. * @constructor
  19608. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19609. * @param {Scene} scene The scene to add this mesh to.
  19610. * @param {Node} parent The parent of this mesh, if it has one
  19611. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19612. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19613. * When false, achieved by calling a clone(), also passing False.
  19614. * This will make creation of children, recursive.
  19615. */
  19616. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19617. if (parent === void 0) { parent = null; }
  19618. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19619. _super.call(this, name, scene);
  19620. // Events
  19621. /**
  19622. * An event triggered before rendering the mesh
  19623. * @type {BABYLON.Observable}
  19624. */
  19625. this.onBeforeRenderObservable = new BABYLON.Observable();
  19626. /**
  19627. * An event triggered after rendering the mesh
  19628. * @type {BABYLON.Observable}
  19629. */
  19630. this.onAfterRenderObservable = new BABYLON.Observable();
  19631. /**
  19632. * An event triggered before drawing the mesh
  19633. * @type {BABYLON.Observable}
  19634. */
  19635. this.onBeforeDrawObservable = new BABYLON.Observable();
  19636. // Members
  19637. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19638. this.instances = new Array();
  19639. this._LODLevels = new Array();
  19640. this._visibleInstances = {};
  19641. this._renderIdForInstances = new Array();
  19642. this._batchCache = new _InstancesBatch();
  19643. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19644. this._sideOrientation = Mesh._DEFAULTSIDE;
  19645. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19646. if (source) {
  19647. // Geometry
  19648. if (source._geometry) {
  19649. source._geometry.applyToMesh(this);
  19650. }
  19651. // Deep copy
  19652. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  19653. // Parent
  19654. this.parent = source.parent;
  19655. // Pivot
  19656. this.setPivotMatrix(source.getPivotMatrix());
  19657. this.id = name + "." + source.id;
  19658. // Material
  19659. this.material = source.material;
  19660. var index;
  19661. if (!doNotCloneChildren) {
  19662. // Children
  19663. for (index = 0; index < scene.meshes.length; index++) {
  19664. var mesh = scene.meshes[index];
  19665. if (mesh.parent === source) {
  19666. // doNotCloneChildren is always going to be False
  19667. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  19668. }
  19669. }
  19670. }
  19671. // Physics clone
  19672. var physicsEngine = this.getScene().getPhysicsEngine();
  19673. if (clonePhysicsImpostor && physicsEngine) {
  19674. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19675. if (impostor) {
  19676. this.physicsImpostor = impostor.clone(this);
  19677. }
  19678. }
  19679. // Particles
  19680. for (index = 0; index < scene.particleSystems.length; index++) {
  19681. var system = scene.particleSystems[index];
  19682. if (system.emitter === source) {
  19683. system.clone(system.name, this);
  19684. }
  19685. }
  19686. this.computeWorldMatrix(true);
  19687. }
  19688. // Parent
  19689. if (parent !== null) {
  19690. this.parent = parent;
  19691. }
  19692. }
  19693. Object.defineProperty(Mesh, "FRONTSIDE", {
  19694. /**
  19695. * Mesh side orientation : usually the external or front surface
  19696. */
  19697. get: function () {
  19698. return Mesh._FRONTSIDE;
  19699. },
  19700. enumerable: true,
  19701. configurable: true
  19702. });
  19703. Object.defineProperty(Mesh, "BACKSIDE", {
  19704. /**
  19705. * Mesh side orientation : usually the internal or back surface
  19706. */
  19707. get: function () {
  19708. return Mesh._BACKSIDE;
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19714. /**
  19715. * Mesh side orientation : both internal and external or front and back surfaces
  19716. */
  19717. get: function () {
  19718. return Mesh._DOUBLESIDE;
  19719. },
  19720. enumerable: true,
  19721. configurable: true
  19722. });
  19723. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19724. /**
  19725. * Mesh side orientation : by default, `FRONTSIDE`
  19726. */
  19727. get: function () {
  19728. return Mesh._DEFAULTSIDE;
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(Mesh, "NO_CAP", {
  19734. /**
  19735. * Mesh cap setting : no cap
  19736. */
  19737. get: function () {
  19738. return Mesh._NO_CAP;
  19739. },
  19740. enumerable: true,
  19741. configurable: true
  19742. });
  19743. Object.defineProperty(Mesh, "CAP_START", {
  19744. /**
  19745. * Mesh cap setting : one cap at the beginning of the mesh
  19746. */
  19747. get: function () {
  19748. return Mesh._CAP_START;
  19749. },
  19750. enumerable: true,
  19751. configurable: true
  19752. });
  19753. Object.defineProperty(Mesh, "CAP_END", {
  19754. /**
  19755. * Mesh cap setting : one cap at the end of the mesh
  19756. */
  19757. get: function () {
  19758. return Mesh._CAP_END;
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. Object.defineProperty(Mesh, "CAP_ALL", {
  19764. /**
  19765. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19766. */
  19767. get: function () {
  19768. return Mesh._CAP_ALL;
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19774. set: function (callback) {
  19775. if (this._onBeforeDrawObserver) {
  19776. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19777. }
  19778. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19779. },
  19780. enumerable: true,
  19781. configurable: true
  19782. });
  19783. // Methods
  19784. Mesh.prototype.getClassName = function () {
  19785. return "Mesh";
  19786. };
  19787. /**
  19788. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19789. */
  19790. Mesh.prototype.toString = function (fullDetails) {
  19791. var ret = _super.prototype.toString.call(this, fullDetails);
  19792. ret += ", n vertices: " + this.getTotalVertices();
  19793. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19794. if (this.animations) {
  19795. for (var i = 0; i < this.animations.length; i++) {
  19796. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19797. }
  19798. }
  19799. if (fullDetails) {
  19800. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19801. }
  19802. return ret;
  19803. };
  19804. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19805. get: function () {
  19806. return this._LODLevels.length > 0;
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Mesh.prototype._sortLODLevels = function () {
  19812. this._LODLevels.sort(function (a, b) {
  19813. if (a.distance < b.distance) {
  19814. return 1;
  19815. }
  19816. if (a.distance > b.distance) {
  19817. return -1;
  19818. }
  19819. return 0;
  19820. });
  19821. };
  19822. /**
  19823. * Add a mesh as LOD level triggered at the given distance.
  19824. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19825. * @param {number} distance The distance from the center of the object to show this level
  19826. * @param {Mesh} mesh The mesh to be added as LOD level
  19827. * @return {Mesh} This mesh (for chaining)
  19828. */
  19829. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19830. if (mesh && mesh._masterMesh) {
  19831. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19832. return this;
  19833. }
  19834. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19835. this._LODLevels.push(level);
  19836. if (mesh) {
  19837. mesh._masterMesh = this;
  19838. }
  19839. this._sortLODLevels();
  19840. return this;
  19841. };
  19842. /**
  19843. * Returns the LOD level mesh at the passed distance or null if not found.
  19844. * It is related to the method `addLODLevel(distance, mesh)`.
  19845. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19846. */
  19847. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19848. for (var index = 0; index < this._LODLevels.length; index++) {
  19849. var level = this._LODLevels[index];
  19850. if (level.distance === distance) {
  19851. return level.mesh;
  19852. }
  19853. }
  19854. return null;
  19855. };
  19856. /**
  19857. * Remove a mesh from the LOD array
  19858. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19859. * @param {Mesh} mesh The mesh to be removed.
  19860. * @return {Mesh} This mesh (for chaining)
  19861. */
  19862. Mesh.prototype.removeLODLevel = function (mesh) {
  19863. for (var index = 0; index < this._LODLevels.length; index++) {
  19864. if (this._LODLevels[index].mesh === mesh) {
  19865. this._LODLevels.splice(index, 1);
  19866. if (mesh) {
  19867. mesh._masterMesh = null;
  19868. }
  19869. }
  19870. }
  19871. this._sortLODLevels();
  19872. return this;
  19873. };
  19874. /**
  19875. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19876. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19877. */
  19878. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19879. if (!this._LODLevels || this._LODLevels.length === 0) {
  19880. return this;
  19881. }
  19882. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19883. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19884. if (this.onLODLevelSelection) {
  19885. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19886. }
  19887. return this;
  19888. }
  19889. for (var index = 0; index < this._LODLevels.length; index++) {
  19890. var level = this._LODLevels[index];
  19891. if (level.distance < distanceToCamera) {
  19892. if (level.mesh) {
  19893. level.mesh._preActivate();
  19894. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19895. }
  19896. if (this.onLODLevelSelection) {
  19897. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19898. }
  19899. return level.mesh;
  19900. }
  19901. }
  19902. if (this.onLODLevelSelection) {
  19903. this.onLODLevelSelection(distanceToCamera, this, this);
  19904. }
  19905. return this;
  19906. };
  19907. Object.defineProperty(Mesh.prototype, "geometry", {
  19908. /**
  19909. * Returns the mesh internal Geometry object.
  19910. */
  19911. get: function () {
  19912. return this._geometry;
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. /**
  19918. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19919. */
  19920. Mesh.prototype.getTotalVertices = function () {
  19921. if (!this._geometry) {
  19922. return 0;
  19923. }
  19924. return this._geometry.getTotalVertices();
  19925. };
  19926. /**
  19927. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19928. * 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.
  19929. * Returns null if the mesh has no geometry or no vertex buffer.
  19930. * Possible `kind` values :
  19931. * - BABYLON.VertexBuffer.PositionKind
  19932. * - BABYLON.VertexBuffer.UVKind
  19933. * - BABYLON.VertexBuffer.UV2Kind
  19934. * - BABYLON.VertexBuffer.UV3Kind
  19935. * - BABYLON.VertexBuffer.UV4Kind
  19936. * - BABYLON.VertexBuffer.UV5Kind
  19937. * - BABYLON.VertexBuffer.UV6Kind
  19938. * - BABYLON.VertexBuffer.ColorKind
  19939. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19940. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19941. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19942. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19943. */
  19944. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19945. if (!this._geometry) {
  19946. return null;
  19947. }
  19948. return this._geometry.getVerticesData(kind, copyWhenShared);
  19949. };
  19950. /**
  19951. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19952. * Returns `undefined` if the mesh has no geometry.
  19953. * Possible `kind` values :
  19954. * - BABYLON.VertexBuffer.PositionKind
  19955. * - BABYLON.VertexBuffer.UVKind
  19956. * - BABYLON.VertexBuffer.UV2Kind
  19957. * - BABYLON.VertexBuffer.UV3Kind
  19958. * - BABYLON.VertexBuffer.UV4Kind
  19959. * - BABYLON.VertexBuffer.UV5Kind
  19960. * - BABYLON.VertexBuffer.UV6Kind
  19961. * - BABYLON.VertexBuffer.ColorKind
  19962. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19963. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19964. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19965. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19966. */
  19967. Mesh.prototype.getVertexBuffer = function (kind) {
  19968. if (!this._geometry) {
  19969. return undefined;
  19970. }
  19971. return this._geometry.getVertexBuffer(kind);
  19972. };
  19973. /**
  19974. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19975. * Possible `kind` values :
  19976. * - BABYLON.VertexBuffer.PositionKind
  19977. * - BABYLON.VertexBuffer.UVKind
  19978. * - BABYLON.VertexBuffer.UV2Kind
  19979. * - BABYLON.VertexBuffer.UV3Kind
  19980. * - BABYLON.VertexBuffer.UV4Kind
  19981. * - BABYLON.VertexBuffer.UV5Kind
  19982. * - BABYLON.VertexBuffer.UV6Kind
  19983. * - BABYLON.VertexBuffer.ColorKind
  19984. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19985. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19986. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19987. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19988. */
  19989. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19990. if (!this._geometry) {
  19991. if (this._delayInfo) {
  19992. return this._delayInfo.indexOf(kind) !== -1;
  19993. }
  19994. return false;
  19995. }
  19996. return this._geometry.isVerticesDataPresent(kind);
  19997. };
  19998. /**
  19999. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20000. * Possible `kind` values :
  20001. * - BABYLON.VertexBuffer.PositionKind
  20002. * - BABYLON.VertexBuffer.UVKind
  20003. * - BABYLON.VertexBuffer.UV2Kind
  20004. * - BABYLON.VertexBuffer.UV3Kind
  20005. * - BABYLON.VertexBuffer.UV4Kind
  20006. * - BABYLON.VertexBuffer.UV5Kind
  20007. * - BABYLON.VertexBuffer.UV6Kind
  20008. * - BABYLON.VertexBuffer.ColorKind
  20009. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20010. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20011. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20012. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20013. */
  20014. Mesh.prototype.getVerticesDataKinds = function () {
  20015. if (!this._geometry) {
  20016. var result = [];
  20017. if (this._delayInfo) {
  20018. this._delayInfo.forEach(function (kind, index, array) {
  20019. result.push(kind);
  20020. });
  20021. }
  20022. return result;
  20023. }
  20024. return this._geometry.getVerticesDataKinds();
  20025. };
  20026. /**
  20027. * Returns a positive integer : the total number of indices in this mesh geometry.
  20028. * Returns zero if the mesh has no geometry.
  20029. */
  20030. Mesh.prototype.getTotalIndices = function () {
  20031. if (!this._geometry) {
  20032. return 0;
  20033. }
  20034. return this._geometry.getTotalIndices();
  20035. };
  20036. /**
  20037. * Returns an array of integers or a Int32Array populated with the mesh indices.
  20038. * 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.
  20039. * Returns an empty array if the mesh has no geometry.
  20040. */
  20041. Mesh.prototype.getIndices = function (copyWhenShared) {
  20042. if (!this._geometry) {
  20043. return [];
  20044. }
  20045. return this._geometry.getIndices(copyWhenShared);
  20046. };
  20047. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20048. get: function () {
  20049. return this._masterMesh !== null && this._masterMesh !== undefined;
  20050. },
  20051. enumerable: true,
  20052. configurable: true
  20053. });
  20054. /**
  20055. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20056. */
  20057. Mesh.prototype.isReady = function () {
  20058. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20059. return false;
  20060. }
  20061. return _super.prototype.isReady.call(this);
  20062. };
  20063. /**
  20064. * Boolean : true if the mesh has been disposed.
  20065. */
  20066. Mesh.prototype.isDisposed = function () {
  20067. return this._isDisposed;
  20068. };
  20069. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20070. get: function () {
  20071. return this._sideOrientation;
  20072. },
  20073. /**
  20074. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20075. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20076. */
  20077. set: function (sideO) {
  20078. this._sideOrientation = sideO;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20084. /**
  20085. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20086. * This property is pertinent only for updatable parametric shapes.
  20087. */
  20088. get: function () {
  20089. return this._areNormalsFrozen;
  20090. },
  20091. enumerable: true,
  20092. configurable: true
  20093. });
  20094. /**
  20095. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20096. * It has no effect at all on other shapes.
  20097. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20098. */
  20099. Mesh.prototype.freezeNormals = function () {
  20100. this._areNormalsFrozen = true;
  20101. };
  20102. /**
  20103. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20104. * It has no effect at all on other shapes.
  20105. * It reactivates the mesh normals computation if it was previously frozen.
  20106. */
  20107. Mesh.prototype.unfreezeNormals = function () {
  20108. this._areNormalsFrozen = false;
  20109. };
  20110. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20111. /**
  20112. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20113. */
  20114. set: function (count) {
  20115. this._overridenInstanceCount = count;
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. // Methods
  20121. Mesh.prototype._preActivate = function () {
  20122. var sceneRenderId = this.getScene().getRenderId();
  20123. if (this._preActivateId === sceneRenderId) {
  20124. return;
  20125. }
  20126. this._preActivateId = sceneRenderId;
  20127. this._visibleInstances = null;
  20128. };
  20129. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20130. if (this._visibleInstances) {
  20131. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20132. }
  20133. };
  20134. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20135. if (!this._visibleInstances) {
  20136. this._visibleInstances = {};
  20137. this._visibleInstances.defaultRenderId = renderId;
  20138. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20139. }
  20140. if (!this._visibleInstances[renderId]) {
  20141. this._visibleInstances[renderId] = new Array();
  20142. }
  20143. this._visibleInstances[renderId].push(instance);
  20144. };
  20145. /**
  20146. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20147. * This means the mesh underlying bounding box and sphere are recomputed.
  20148. */
  20149. Mesh.prototype.refreshBoundingInfo = function () {
  20150. if (this._boundingInfo.isLocked) {
  20151. return;
  20152. }
  20153. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20154. if (data) {
  20155. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20156. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20157. }
  20158. if (this.subMeshes) {
  20159. for (var index = 0; index < this.subMeshes.length; index++) {
  20160. this.subMeshes[index].refreshBoundingInfo();
  20161. }
  20162. }
  20163. this._updateBoundingInfo();
  20164. };
  20165. Mesh.prototype._createGlobalSubMesh = function () {
  20166. var totalVertices = this.getTotalVertices();
  20167. if (!totalVertices || !this.getIndices()) {
  20168. return null;
  20169. }
  20170. this.releaseSubMeshes();
  20171. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20172. };
  20173. Mesh.prototype.subdivide = function (count) {
  20174. if (count < 1) {
  20175. return;
  20176. }
  20177. var totalIndices = this.getTotalIndices();
  20178. var subdivisionSize = (totalIndices / count) | 0;
  20179. var offset = 0;
  20180. // Ensure that subdivisionSize is a multiple of 3
  20181. while (subdivisionSize % 3 !== 0) {
  20182. subdivisionSize++;
  20183. }
  20184. this.releaseSubMeshes();
  20185. for (var index = 0; index < count; index++) {
  20186. if (offset >= totalIndices) {
  20187. break;
  20188. }
  20189. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20190. offset += subdivisionSize;
  20191. }
  20192. this.synchronizeInstances();
  20193. };
  20194. /**
  20195. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20196. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20197. * The `data` are either a numeric array either a Float32Array.
  20198. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20199. * 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).
  20200. * Note that a new underlying VertexBuffer object is created each call.
  20201. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20202. *
  20203. * Possible `kind` values :
  20204. * - BABYLON.VertexBuffer.PositionKind
  20205. * - BABYLON.VertexBuffer.UVKind
  20206. * - BABYLON.VertexBuffer.UV2Kind
  20207. * - BABYLON.VertexBuffer.UV3Kind
  20208. * - BABYLON.VertexBuffer.UV4Kind
  20209. * - BABYLON.VertexBuffer.UV5Kind
  20210. * - BABYLON.VertexBuffer.UV6Kind
  20211. * - BABYLON.VertexBuffer.ColorKind
  20212. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20213. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20214. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20215. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20216. */
  20217. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20218. if (!this._geometry) {
  20219. var vertexData = new BABYLON.VertexData();
  20220. vertexData.set(data, kind);
  20221. var scene = this.getScene();
  20222. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20223. }
  20224. else {
  20225. this._geometry.setVerticesData(kind, data, updatable, stride);
  20226. }
  20227. };
  20228. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20229. if (!this._geometry) {
  20230. var scene = this.getScene();
  20231. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20232. }
  20233. this._geometry.setVerticesBuffer(buffer);
  20234. };
  20235. /**
  20236. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20237. * If the mesh has no geometry, it is simply returned as it is.
  20238. * The `data` are either a numeric array either a Float32Array.
  20239. * No new underlying VertexBuffer object is created.
  20240. * 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.
  20241. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20242. *
  20243. * Possible `kind` values :
  20244. * - BABYLON.VertexBuffer.PositionKind
  20245. * - BABYLON.VertexBuffer.UVKind
  20246. * - BABYLON.VertexBuffer.UV2Kind
  20247. * - BABYLON.VertexBuffer.UV3Kind
  20248. * - BABYLON.VertexBuffer.UV4Kind
  20249. * - BABYLON.VertexBuffer.UV5Kind
  20250. * - BABYLON.VertexBuffer.UV6Kind
  20251. * - BABYLON.VertexBuffer.ColorKind
  20252. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20253. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20254. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20255. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20256. */
  20257. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20258. if (!this._geometry) {
  20259. return;
  20260. }
  20261. if (!makeItUnique) {
  20262. this._geometry.updateVerticesData(kind, data, updateExtends);
  20263. }
  20264. else {
  20265. this.makeGeometryUnique();
  20266. this.updateVerticesData(kind, data, updateExtends, false);
  20267. }
  20268. };
  20269. /**
  20270. * Deprecated since BabylonJS v2.3
  20271. */
  20272. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20273. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20274. if (!this._geometry) {
  20275. return;
  20276. }
  20277. if (!makeItUnique) {
  20278. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20279. }
  20280. else {
  20281. this.makeGeometryUnique();
  20282. this.updateVerticesDataDirectly(kind, data, offset, false);
  20283. }
  20284. };
  20285. /**
  20286. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20287. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20288. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20289. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20290. */
  20291. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20292. if (computeNormals === void 0) { computeNormals = true; }
  20293. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20294. positionFunction(positions);
  20295. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20296. if (computeNormals) {
  20297. var indices = this.getIndices();
  20298. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20299. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20300. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20301. }
  20302. };
  20303. Mesh.prototype.makeGeometryUnique = function () {
  20304. if (!this._geometry) {
  20305. return;
  20306. }
  20307. var oldGeometry = this._geometry;
  20308. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20309. oldGeometry.releaseForMesh(this, true);
  20310. geometry.applyToMesh(this);
  20311. };
  20312. /**
  20313. * Sets the mesh indices.
  20314. * Expects an array populated with integers or a Int32Array.
  20315. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20316. * This method creates a new index buffer each call.
  20317. */
  20318. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20319. if (!this._geometry) {
  20320. var vertexData = new BABYLON.VertexData();
  20321. vertexData.indices = indices;
  20322. var scene = this.getScene();
  20323. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20324. }
  20325. else {
  20326. this._geometry.setIndices(indices, totalVertices);
  20327. }
  20328. };
  20329. /**
  20330. * Invert the geometry to move from a right handed system to a left handed one.
  20331. */
  20332. Mesh.prototype.toLeftHanded = function () {
  20333. if (!this._geometry) {
  20334. return;
  20335. }
  20336. this._geometry.toLeftHanded();
  20337. };
  20338. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20339. var engine = this.getScene().getEngine();
  20340. // Wireframe
  20341. var indexToBind;
  20342. if (this._unIndexed) {
  20343. indexToBind = null;
  20344. }
  20345. else {
  20346. switch (fillMode) {
  20347. case BABYLON.Material.PointFillMode:
  20348. indexToBind = null;
  20349. break;
  20350. case BABYLON.Material.WireFrameFillMode:
  20351. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20352. break;
  20353. default:
  20354. case BABYLON.Material.TriangleFillMode:
  20355. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20356. break;
  20357. }
  20358. }
  20359. // VBOs
  20360. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  20361. };
  20362. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20363. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20364. return;
  20365. }
  20366. this.onBeforeDrawObservable.notifyObservers(this);
  20367. var engine = this.getScene().getEngine();
  20368. // Draw order
  20369. switch (fillMode) {
  20370. case BABYLON.Material.PointFillMode:
  20371. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20372. break;
  20373. case BABYLON.Material.WireFrameFillMode:
  20374. if (this._unIndexed) {
  20375. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20376. }
  20377. else {
  20378. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20379. }
  20380. break;
  20381. default:
  20382. if (this._unIndexed) {
  20383. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20384. }
  20385. else {
  20386. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20387. }
  20388. }
  20389. };
  20390. /**
  20391. * Registers for this mesh a javascript function called just before the rendering process.
  20392. * This function is passed the current mesh and doesn't return anything.
  20393. */
  20394. Mesh.prototype.registerBeforeRender = function (func) {
  20395. this.onBeforeRenderObservable.add(func);
  20396. };
  20397. /**
  20398. * Disposes a previously registered javascript function called before the rendering.
  20399. * This function is passed the current mesh and doesn't return anything.
  20400. */
  20401. Mesh.prototype.unregisterBeforeRender = function (func) {
  20402. this.onBeforeRenderObservable.removeCallback(func);
  20403. };
  20404. /**
  20405. * Registers for this mesh a javascript function called just after the rendering is complete.
  20406. * This function is passed the current mesh and doesn't return anything.
  20407. */
  20408. Mesh.prototype.registerAfterRender = function (func) {
  20409. this.onAfterRenderObservable.add(func);
  20410. };
  20411. /**
  20412. * Disposes a previously registered javascript function called after the rendering.
  20413. * This function is passed the current mesh and doesn't return anything.
  20414. */
  20415. Mesh.prototype.unregisterAfterRender = function (func) {
  20416. this.onAfterRenderObservable.removeCallback(func);
  20417. };
  20418. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20419. var scene = this.getScene();
  20420. this._batchCache.mustReturn = false;
  20421. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20422. this._batchCache.visibleInstances[subMeshId] = null;
  20423. if (this._visibleInstances) {
  20424. var currentRenderId = scene.getRenderId();
  20425. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20426. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20427. var selfRenderId = this._renderId;
  20428. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20429. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20430. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20431. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20432. }
  20433. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20434. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20435. this._batchCache.mustReturn = true;
  20436. return this._batchCache;
  20437. }
  20438. if (currentRenderId !== selfRenderId) {
  20439. this._batchCache.renderSelf[subMeshId] = false;
  20440. }
  20441. }
  20442. this._renderIdForInstances[subMeshId] = currentRenderId;
  20443. }
  20444. return this._batchCache;
  20445. };
  20446. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20447. var visibleInstances = batch.visibleInstances[subMesh._id];
  20448. var matricesCount = visibleInstances.length + 1;
  20449. var bufferSize = matricesCount * 16 * 4;
  20450. var currentInstancesBufferSize = this._instancesBufferSize;
  20451. var instancesBuffer = this._instancesBuffer;
  20452. while (this._instancesBufferSize < bufferSize) {
  20453. this._instancesBufferSize *= 2;
  20454. }
  20455. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20456. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20457. }
  20458. var offset = 0;
  20459. var instancesCount = 0;
  20460. var world = this.getWorldMatrix();
  20461. if (batch.renderSelf[subMesh._id]) {
  20462. world.copyToArray(this._instancesData, offset);
  20463. offset += 16;
  20464. instancesCount++;
  20465. }
  20466. if (visibleInstances) {
  20467. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20468. var instance = visibleInstances[instanceIndex];
  20469. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20470. offset += 16;
  20471. instancesCount++;
  20472. }
  20473. }
  20474. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20475. if (instancesBuffer) {
  20476. instancesBuffer.dispose();
  20477. }
  20478. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20479. this._instancesBuffer = instancesBuffer;
  20480. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20481. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20482. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20483. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20484. }
  20485. else {
  20486. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20487. }
  20488. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20489. this._draw(subMesh, fillMode, instancesCount);
  20490. engine.unbindInstanceAttributes();
  20491. };
  20492. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20493. var scene = this.getScene();
  20494. var engine = scene.getEngine();
  20495. if (hardwareInstancedRendering) {
  20496. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20497. }
  20498. else {
  20499. if (batch.renderSelf[subMesh._id]) {
  20500. // Draw
  20501. if (onBeforeDraw) {
  20502. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20503. }
  20504. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20505. }
  20506. if (batch.visibleInstances[subMesh._id]) {
  20507. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20508. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20509. // World
  20510. var world = instance.getWorldMatrix();
  20511. if (onBeforeDraw) {
  20512. onBeforeDraw(true, world, effectiveMaterial);
  20513. }
  20514. // Draw
  20515. this._draw(subMesh, fillMode);
  20516. }
  20517. }
  20518. }
  20519. };
  20520. /**
  20521. * Triggers the draw call for the mesh.
  20522. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20523. */
  20524. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20525. var scene = this.getScene();
  20526. // Managing instances
  20527. var batch = this._getInstancesRenderList(subMesh._id);
  20528. if (batch.mustReturn) {
  20529. return;
  20530. }
  20531. // Checking geometry state
  20532. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20533. return;
  20534. }
  20535. var callbackIndex;
  20536. this.onBeforeRenderObservable.notifyObservers(this);
  20537. var engine = scene.getEngine();
  20538. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20539. // Material
  20540. var effectiveMaterial = subMesh.getMaterial();
  20541. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20542. return;
  20543. }
  20544. // Outline - step 1
  20545. var savedDepthWrite = engine.getDepthWrite();
  20546. if (this.renderOutline) {
  20547. engine.setDepthWrite(false);
  20548. scene.getOutlineRenderer().render(subMesh, batch);
  20549. engine.setDepthWrite(savedDepthWrite);
  20550. }
  20551. effectiveMaterial._preBind();
  20552. var effect = effectiveMaterial.getEffect();
  20553. // Bind
  20554. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20555. this._bind(subMesh, effect, fillMode);
  20556. var world = this.getWorldMatrix();
  20557. effectiveMaterial.bind(world, this);
  20558. // Alpha mode
  20559. if (enableAlphaMode) {
  20560. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20561. }
  20562. // Draw
  20563. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20564. // Unbind
  20565. effectiveMaterial.unbind();
  20566. // Outline - step 2
  20567. if (this.renderOutline && savedDepthWrite) {
  20568. engine.setDepthWrite(true);
  20569. engine.setColorWrite(false);
  20570. scene.getOutlineRenderer().render(subMesh, batch);
  20571. engine.setColorWrite(true);
  20572. }
  20573. // Overlay
  20574. if (this.renderOverlay) {
  20575. var currentMode = engine.getAlphaMode();
  20576. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20577. scene.getOutlineRenderer().render(subMesh, batch, true);
  20578. engine.setAlphaMode(currentMode);
  20579. }
  20580. this.onAfterRenderObservable.notifyObservers(this);
  20581. };
  20582. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20583. if (isInstance) {
  20584. effectiveMaterial.bindOnlyWorldMatrix(world);
  20585. }
  20586. };
  20587. /**
  20588. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20589. */
  20590. Mesh.prototype.getEmittedParticleSystems = function () {
  20591. var results = new Array();
  20592. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20593. var particleSystem = this.getScene().particleSystems[index];
  20594. if (particleSystem.emitter === this) {
  20595. results.push(particleSystem);
  20596. }
  20597. }
  20598. return results;
  20599. };
  20600. /**
  20601. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20602. */
  20603. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20604. var results = new Array();
  20605. var descendants = this.getDescendants();
  20606. descendants.push(this);
  20607. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20608. var particleSystem = this.getScene().particleSystems[index];
  20609. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20610. results.push(particleSystem);
  20611. }
  20612. }
  20613. return results;
  20614. };
  20615. Mesh.prototype._checkDelayState = function () {
  20616. var scene = this.getScene();
  20617. if (this._geometry) {
  20618. this._geometry.load(scene);
  20619. }
  20620. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20621. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20622. this._queueLoad(this, scene);
  20623. }
  20624. };
  20625. Mesh.prototype._queueLoad = function (mesh, scene) {
  20626. var _this = this;
  20627. scene._addPendingData(mesh);
  20628. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20629. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20630. if (data instanceof ArrayBuffer) {
  20631. _this._delayLoadingFunction(data, _this);
  20632. }
  20633. else {
  20634. _this._delayLoadingFunction(JSON.parse(data), _this);
  20635. }
  20636. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20637. scene._removePendingData(_this);
  20638. }, function () { }, scene.database, getBinaryData);
  20639. };
  20640. /**
  20641. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20642. */
  20643. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20644. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20645. return false;
  20646. }
  20647. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20648. return false;
  20649. }
  20650. this._checkDelayState();
  20651. return true;
  20652. };
  20653. /**
  20654. * Sets the mesh material by the material or multiMaterial `id` property.
  20655. * The material `id` is a string identifying the material or the multiMaterial.
  20656. * This method returns nothing.
  20657. */
  20658. Mesh.prototype.setMaterialByID = function (id) {
  20659. var materials = this.getScene().materials;
  20660. var index;
  20661. for (index = 0; index < materials.length; index++) {
  20662. if (materials[index].id === id) {
  20663. this.material = materials[index];
  20664. return;
  20665. }
  20666. }
  20667. // Multi
  20668. var multiMaterials = this.getScene().multiMaterials;
  20669. for (index = 0; index < multiMaterials.length; index++) {
  20670. if (multiMaterials[index].id === id) {
  20671. this.material = multiMaterials[index];
  20672. return;
  20673. }
  20674. }
  20675. };
  20676. /**
  20677. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20678. */
  20679. Mesh.prototype.getAnimatables = function () {
  20680. var results = [];
  20681. if (this.material) {
  20682. results.push(this.material);
  20683. }
  20684. if (this.skeleton) {
  20685. results.push(this.skeleton);
  20686. }
  20687. return results;
  20688. };
  20689. /**
  20690. * Modifies the mesh geometry according to the passed transformation matrix.
  20691. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20692. * The mesh normals are modified accordingly the same transformation.
  20693. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20694. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20695. */
  20696. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20697. // Position
  20698. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20699. return;
  20700. }
  20701. var submeshes = this.subMeshes.splice(0);
  20702. this._resetPointsArrayCache();
  20703. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20704. var temp = [];
  20705. var index;
  20706. for (index = 0; index < data.length; index += 3) {
  20707. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20708. }
  20709. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20710. // Normals
  20711. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20712. return;
  20713. }
  20714. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20715. temp = [];
  20716. for (index = 0; index < data.length; index += 3) {
  20717. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20718. }
  20719. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20720. // flip faces?
  20721. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20722. this.flipFaces();
  20723. }
  20724. // Restore submeshes
  20725. this.releaseSubMeshes();
  20726. this.subMeshes = submeshes;
  20727. };
  20728. /**
  20729. * Modifies the mesh geometry according to its own current World Matrix.
  20730. * The mesh World Matrix is then reset.
  20731. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20732. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20733. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20734. */
  20735. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20736. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20737. this.scaling.copyFromFloats(1, 1, 1);
  20738. this.position.copyFromFloats(0, 0, 0);
  20739. this.rotation.copyFromFloats(0, 0, 0);
  20740. //only if quaternion is already set
  20741. if (this.rotationQuaternion) {
  20742. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20743. }
  20744. this._worldMatrix = BABYLON.Matrix.Identity();
  20745. };
  20746. // Cache
  20747. Mesh.prototype._resetPointsArrayCache = function () {
  20748. this._positions = null;
  20749. };
  20750. Mesh.prototype._generatePointsArray = function () {
  20751. if (this._positions)
  20752. return true;
  20753. this._positions = [];
  20754. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20755. if (!data) {
  20756. return false;
  20757. }
  20758. for (var index = 0; index < data.length; index += 3) {
  20759. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20760. }
  20761. return true;
  20762. };
  20763. /**
  20764. * Returns a new Mesh object generated from the current mesh properties.
  20765. * This method must not get confused with createInstance().
  20766. * The parameter `name` is a string, the name given to the new mesh.
  20767. * The optional parameter `newParent` can be any Node object (default `null`).
  20768. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20769. * 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.
  20770. */
  20771. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20772. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20773. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20774. };
  20775. /**
  20776. * Disposes the mesh.
  20777. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20778. */
  20779. Mesh.prototype.dispose = function (doNotRecurse) {
  20780. if (this._geometry) {
  20781. this._geometry.releaseForMesh(this, true);
  20782. }
  20783. // Instances
  20784. if (this._instancesBuffer) {
  20785. this._instancesBuffer.dispose();
  20786. this._instancesBuffer = null;
  20787. }
  20788. while (this.instances.length) {
  20789. this.instances[0].dispose();
  20790. }
  20791. // Highlight layers.
  20792. var highlightLayers = this.getScene().highlightLayers;
  20793. for (var i = 0; i < highlightLayers.length; i++) {
  20794. var highlightLayer = highlightLayers[i];
  20795. if (highlightLayer) {
  20796. highlightLayer.removeMesh(this);
  20797. highlightLayer.removeExcludedMesh(this);
  20798. }
  20799. }
  20800. _super.prototype.dispose.call(this, doNotRecurse);
  20801. };
  20802. /**
  20803. * Modifies the mesh geometry according to a displacement map.
  20804. * 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.
  20805. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20806. * This method returns nothing.
  20807. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20808. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20809. * 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.
  20810. */
  20811. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20812. var _this = this;
  20813. var scene = this.getScene();
  20814. var onload = function (img) {
  20815. // Getting height map data
  20816. var canvas = document.createElement("canvas");
  20817. var context = canvas.getContext("2d");
  20818. var heightMapWidth = img.width;
  20819. var heightMapHeight = img.height;
  20820. canvas.width = heightMapWidth;
  20821. canvas.height = heightMapHeight;
  20822. context.drawImage(img, 0, 0);
  20823. // Create VertexData from map data
  20824. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20825. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20826. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20827. //execute success callback, if set
  20828. if (onSuccess) {
  20829. onSuccess(_this);
  20830. }
  20831. };
  20832. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20833. };
  20834. /**
  20835. * Modifies the mesh geometry according to a displacementMap buffer.
  20836. * 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.
  20837. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20838. * This method returns nothing.
  20839. * 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.
  20840. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20841. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20842. */
  20843. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20844. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20845. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20846. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20847. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20848. return;
  20849. }
  20850. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20851. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20852. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20853. var position = BABYLON.Vector3.Zero();
  20854. var normal = BABYLON.Vector3.Zero();
  20855. var uv = BABYLON.Vector2.Zero();
  20856. for (var index = 0; index < positions.length; index += 3) {
  20857. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20858. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20859. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20860. // Compute height
  20861. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20862. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20863. var pos = (u + v * heightMapWidth) * 4;
  20864. var r = buffer[pos] / 255.0;
  20865. var g = buffer[pos + 1] / 255.0;
  20866. var b = buffer[pos + 2] / 255.0;
  20867. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20868. normal.normalize();
  20869. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20870. position = position.add(normal);
  20871. position.toArray(positions, index);
  20872. }
  20873. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20874. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20875. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20876. };
  20877. /**
  20878. * Modify the mesh to get a flat shading rendering.
  20879. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20880. * This method returns nothing.
  20881. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20882. */
  20883. Mesh.prototype.convertToFlatShadedMesh = function () {
  20884. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20885. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20886. var kinds = this.getVerticesDataKinds();
  20887. var vbs = [];
  20888. var data = [];
  20889. var newdata = [];
  20890. var updatableNormals = false;
  20891. var kindIndex;
  20892. var kind;
  20893. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20894. kind = kinds[kindIndex];
  20895. var vertexBuffer = this.getVertexBuffer(kind);
  20896. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20897. updatableNormals = vertexBuffer.isUpdatable();
  20898. kinds.splice(kindIndex, 1);
  20899. kindIndex--;
  20900. continue;
  20901. }
  20902. vbs[kind] = vertexBuffer;
  20903. data[kind] = vbs[kind].getData();
  20904. newdata[kind] = [];
  20905. }
  20906. // Save previous submeshes
  20907. var previousSubmeshes = this.subMeshes.slice(0);
  20908. var indices = this.getIndices();
  20909. var totalIndices = this.getTotalIndices();
  20910. // Generating unique vertices per face
  20911. var index;
  20912. for (index = 0; index < totalIndices; index++) {
  20913. var vertexIndex = indices[index];
  20914. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20915. kind = kinds[kindIndex];
  20916. var stride = vbs[kind].getStrideSize();
  20917. for (var offset = 0; offset < stride; offset++) {
  20918. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20919. }
  20920. }
  20921. }
  20922. // Updating faces & normal
  20923. var normals = [];
  20924. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20925. for (index = 0; index < totalIndices; index += 3) {
  20926. indices[index] = index;
  20927. indices[index + 1] = index + 1;
  20928. indices[index + 2] = index + 2;
  20929. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20930. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20931. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20932. var p1p2 = p1.subtract(p2);
  20933. var p3p2 = p3.subtract(p2);
  20934. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20935. // Store same normals for every vertex
  20936. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20937. normals.push(normal.x);
  20938. normals.push(normal.y);
  20939. normals.push(normal.z);
  20940. }
  20941. }
  20942. this.setIndices(indices);
  20943. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20944. // Updating vertex buffers
  20945. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20946. kind = kinds[kindIndex];
  20947. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20948. }
  20949. // Updating submeshes
  20950. this.releaseSubMeshes();
  20951. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20952. var previousOne = previousSubmeshes[submeshIndex];
  20953. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20954. }
  20955. this.synchronizeInstances();
  20956. };
  20957. /**
  20958. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20959. * In other words, more vertices, no more indices and a single bigger VBO.
  20960. * This method returns nothing.
  20961. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20962. *
  20963. */
  20964. Mesh.prototype.convertToUnIndexedMesh = function () {
  20965. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20966. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20967. var kinds = this.getVerticesDataKinds();
  20968. var vbs = [];
  20969. var data = [];
  20970. var newdata = [];
  20971. var updatableNormals = false;
  20972. var kindIndex;
  20973. var kind;
  20974. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20975. kind = kinds[kindIndex];
  20976. var vertexBuffer = this.getVertexBuffer(kind);
  20977. vbs[kind] = vertexBuffer;
  20978. data[kind] = vbs[kind].getData();
  20979. newdata[kind] = [];
  20980. }
  20981. // Save previous submeshes
  20982. var previousSubmeshes = this.subMeshes.slice(0);
  20983. var indices = this.getIndices();
  20984. var totalIndices = this.getTotalIndices();
  20985. // Generating unique vertices per face
  20986. var index;
  20987. for (index = 0; index < totalIndices; index++) {
  20988. var vertexIndex = indices[index];
  20989. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20990. kind = kinds[kindIndex];
  20991. var stride = vbs[kind].getStrideSize();
  20992. for (var offset = 0; offset < stride; offset++) {
  20993. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20994. }
  20995. }
  20996. }
  20997. // Updating indices
  20998. for (index = 0; index < totalIndices; index += 3) {
  20999. indices[index] = index;
  21000. indices[index + 1] = index + 1;
  21001. indices[index + 2] = index + 2;
  21002. }
  21003. this.setIndices(indices);
  21004. // Updating vertex buffers
  21005. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21006. kind = kinds[kindIndex];
  21007. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21008. }
  21009. // Updating submeshes
  21010. this.releaseSubMeshes();
  21011. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21012. var previousOne = previousSubmeshes[submeshIndex];
  21013. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21014. }
  21015. this._unIndexed = true;
  21016. this.synchronizeInstances();
  21017. };
  21018. /**
  21019. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21020. * This method returns nothing.
  21021. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21022. */
  21023. Mesh.prototype.flipFaces = function (flipNormals) {
  21024. if (flipNormals === void 0) { flipNormals = false; }
  21025. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21026. var i;
  21027. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21028. for (i = 0; i < vertex_data.normals.length; i++) {
  21029. vertex_data.normals[i] *= -1;
  21030. }
  21031. }
  21032. var temp;
  21033. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21034. // reassign indices
  21035. temp = vertex_data.indices[i + 1];
  21036. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21037. vertex_data.indices[i + 2] = temp;
  21038. }
  21039. vertex_data.applyToMesh(this);
  21040. };
  21041. // Instances
  21042. /**
  21043. * Creates a new InstancedMesh object from the mesh model.
  21044. * An instance shares the same properties and the same material than its model.
  21045. * Only these properties of each instance can then be set individually :
  21046. * - position
  21047. * - rotation
  21048. * - rotationQuaternion
  21049. * - setPivotMatrix
  21050. * - scaling
  21051. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21052. * Warning : this method is not supported for Line mesh and LineSystem
  21053. */
  21054. Mesh.prototype.createInstance = function (name) {
  21055. return new BABYLON.InstancedMesh(name, this);
  21056. };
  21057. /**
  21058. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21059. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21060. * This method returns nothing.
  21061. */
  21062. Mesh.prototype.synchronizeInstances = function () {
  21063. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21064. var instance = this.instances[instanceIndex];
  21065. instance._syncSubMeshes();
  21066. }
  21067. };
  21068. /**
  21069. * Simplify the mesh according to the given array of settings.
  21070. * Function will return immediately and will simplify async. It returns nothing.
  21071. * @param settings a collection of simplification settings.
  21072. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21073. * @param type the type of simplification to run.
  21074. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21075. */
  21076. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21077. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21078. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21079. this.getScene().simplificationQueue.addTask({
  21080. settings: settings,
  21081. parallelProcessing: parallelProcessing,
  21082. mesh: this,
  21083. simplificationType: simplificationType,
  21084. successCallback: successCallback
  21085. });
  21086. };
  21087. /**
  21088. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21089. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21090. * This should be used together with the simplification to avoid disappearing triangles.
  21091. * @param successCallback an optional success callback to be called after the optimization finished.
  21092. */
  21093. Mesh.prototype.optimizeIndices = function (successCallback) {
  21094. var _this = this;
  21095. var indices = this.getIndices();
  21096. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21097. var vectorPositions = [];
  21098. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21099. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21100. }
  21101. var dupes = [];
  21102. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21103. var realPos = vectorPositions.length - 1 - iteration;
  21104. var testedPosition = vectorPositions[realPos];
  21105. for (var j = 0; j < realPos; ++j) {
  21106. var againstPosition = vectorPositions[j];
  21107. if (testedPosition.equals(againstPosition)) {
  21108. dupes[realPos] = j;
  21109. break;
  21110. }
  21111. }
  21112. }, function () {
  21113. for (var i = 0; i < indices.length; ++i) {
  21114. indices[i] = dupes[indices[i]] || indices[i];
  21115. }
  21116. //indices are now reordered
  21117. var originalSubMeshes = _this.subMeshes.slice(0);
  21118. _this.setIndices(indices);
  21119. _this.subMeshes = originalSubMeshes;
  21120. if (successCallback) {
  21121. successCallback(_this);
  21122. }
  21123. });
  21124. };
  21125. // Statics
  21126. /**
  21127. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21128. * The parameter `parsedMesh` is the mesh to be copied.
  21129. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21130. */
  21131. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21132. var mesh = new Mesh(parsedMesh.name, scene);
  21133. mesh.id = parsedMesh.id;
  21134. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21135. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21136. if (parsedMesh.metadata !== undefined) {
  21137. mesh.metadata = parsedMesh.metadata;
  21138. }
  21139. if (parsedMesh.rotationQuaternion) {
  21140. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21141. }
  21142. else if (parsedMesh.rotation) {
  21143. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21144. }
  21145. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21146. if (parsedMesh.localMatrix) {
  21147. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21148. }
  21149. else if (parsedMesh.pivotMatrix) {
  21150. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21151. }
  21152. mesh.setEnabled(parsedMesh.isEnabled);
  21153. mesh.isVisible = parsedMesh.isVisible;
  21154. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21155. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21156. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21157. if (parsedMesh.applyFog !== undefined) {
  21158. mesh.applyFog = parsedMesh.applyFog;
  21159. }
  21160. if (parsedMesh.pickable !== undefined) {
  21161. mesh.isPickable = parsedMesh.pickable;
  21162. }
  21163. if (parsedMesh.alphaIndex !== undefined) {
  21164. mesh.alphaIndex = parsedMesh.alphaIndex;
  21165. }
  21166. mesh.receiveShadows = parsedMesh.receiveShadows;
  21167. mesh.billboardMode = parsedMesh.billboardMode;
  21168. if (parsedMesh.visibility !== undefined) {
  21169. mesh.visibility = parsedMesh.visibility;
  21170. }
  21171. mesh.checkCollisions = parsedMesh.checkCollisions;
  21172. if (parsedMesh.isBlocker !== undefined) {
  21173. mesh.isBlocker = parsedMesh.isBlocker;
  21174. }
  21175. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21176. // freezeWorldMatrix
  21177. if (parsedMesh.freezeWorldMatrix) {
  21178. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21179. }
  21180. // Parent
  21181. if (parsedMesh.parentId) {
  21182. mesh._waitingParentId = parsedMesh.parentId;
  21183. }
  21184. // Actions
  21185. if (parsedMesh.actions !== undefined) {
  21186. mesh._waitingActions = parsedMesh.actions;
  21187. }
  21188. // Overlay
  21189. if (parsedMesh.overlayAlpha !== undefined) {
  21190. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21191. }
  21192. if (parsedMesh.overlayColor !== undefined) {
  21193. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21194. }
  21195. if (parsedMesh.renderOverlay !== undefined) {
  21196. mesh.renderOverlay = parsedMesh.renderOverlay;
  21197. }
  21198. // Geometry
  21199. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21200. if (parsedMesh.delayLoadingFile) {
  21201. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21202. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21203. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21204. if (parsedMesh._binaryInfo) {
  21205. mesh._binaryInfo = parsedMesh._binaryInfo;
  21206. }
  21207. mesh._delayInfo = [];
  21208. if (parsedMesh.hasUVs) {
  21209. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21210. }
  21211. if (parsedMesh.hasUVs2) {
  21212. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21213. }
  21214. if (parsedMesh.hasUVs3) {
  21215. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21216. }
  21217. if (parsedMesh.hasUVs4) {
  21218. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21219. }
  21220. if (parsedMesh.hasUVs5) {
  21221. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21222. }
  21223. if (parsedMesh.hasUVs6) {
  21224. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21225. }
  21226. if (parsedMesh.hasColors) {
  21227. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21228. }
  21229. if (parsedMesh.hasMatricesIndices) {
  21230. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21231. }
  21232. if (parsedMesh.hasMatricesWeights) {
  21233. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21234. }
  21235. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21236. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21237. mesh._checkDelayState();
  21238. }
  21239. }
  21240. else {
  21241. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21242. }
  21243. // Material
  21244. if (parsedMesh.materialId) {
  21245. mesh.setMaterialByID(parsedMesh.materialId);
  21246. }
  21247. else {
  21248. mesh.material = null;
  21249. }
  21250. // Skeleton
  21251. if (parsedMesh.skeletonId > -1) {
  21252. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21253. if (parsedMesh.numBoneInfluencers) {
  21254. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21255. }
  21256. }
  21257. // Animations
  21258. if (parsedMesh.animations) {
  21259. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21260. var parsedAnimation = parsedMesh.animations[animationIndex];
  21261. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21262. }
  21263. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21264. }
  21265. if (parsedMesh.autoAnimate) {
  21266. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21267. }
  21268. // Layer Mask
  21269. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21270. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21271. }
  21272. else {
  21273. mesh.layerMask = 0x0FFFFFFF;
  21274. }
  21275. //(Deprecated) physics
  21276. if (parsedMesh.physicsImpostor) {
  21277. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21278. mass: parsedMesh.physicsMass,
  21279. friction: parsedMesh.physicsFriction,
  21280. restitution: parsedMesh.physicsRestitution
  21281. }, scene);
  21282. }
  21283. // Instances
  21284. if (parsedMesh.instances) {
  21285. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21286. var parsedInstance = parsedMesh.instances[index];
  21287. var instance = mesh.createInstance(parsedInstance.name);
  21288. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21289. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21290. if (parsedInstance.parentId) {
  21291. instance._waitingParentId = parsedInstance.parentId;
  21292. }
  21293. if (parsedInstance.rotationQuaternion) {
  21294. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21295. }
  21296. else if (parsedInstance.rotation) {
  21297. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21298. }
  21299. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21300. instance.checkCollisions = mesh.checkCollisions;
  21301. if (parsedMesh.animations) {
  21302. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21303. parsedAnimation = parsedMesh.animations[animationIndex];
  21304. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21305. }
  21306. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21307. }
  21308. }
  21309. }
  21310. return mesh;
  21311. };
  21312. /**
  21313. * Creates a ribbon mesh.
  21314. * Please consider using the same method from the MeshBuilder class instead.
  21315. * 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.
  21316. *
  21317. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21318. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21319. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21320. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21321. * 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.
  21322. * 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.
  21323. * 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
  21324. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21327. */
  21328. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21329. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21330. pathArray: pathArray,
  21331. closeArray: closeArray,
  21332. closePath: closePath,
  21333. offset: offset,
  21334. updatable: updatable,
  21335. sideOrientation: sideOrientation,
  21336. instance: instance
  21337. }, scene);
  21338. };
  21339. /**
  21340. * Creates a plane polygonal mesh. By default, this is a disc.
  21341. * Please consider using the same method from the MeshBuilder class instead.
  21342. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21343. * 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.
  21344. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21345. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21346. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21347. */
  21348. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21349. var options = {
  21350. radius: radius,
  21351. tessellation: tessellation,
  21352. sideOrientation: sideOrientation,
  21353. updatable: updatable
  21354. };
  21355. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21356. };
  21357. /**
  21358. * Creates a box mesh.
  21359. * Please consider using the same method from the MeshBuilder class instead.
  21360. * The parameter `size` sets the size (float) of each box side (default 1).
  21361. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21362. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21364. */
  21365. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21366. var options = {
  21367. size: size,
  21368. sideOrientation: sideOrientation,
  21369. updatable: updatable
  21370. };
  21371. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21372. };
  21373. /**
  21374. * Creates a sphere mesh.
  21375. * Please consider using the same method from the MeshBuilder class instead.
  21376. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21377. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21378. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21379. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21380. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21381. */
  21382. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21383. var options = {
  21384. segments: segments,
  21385. diameterX: diameter,
  21386. diameterY: diameter,
  21387. diameterZ: diameter,
  21388. sideOrientation: sideOrientation,
  21389. updatable: updatable
  21390. };
  21391. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21392. };
  21393. /**
  21394. * Creates a cylinder or a cone mesh.
  21395. * Please consider using the same method from the MeshBuilder class instead.
  21396. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21397. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21398. * 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.
  21399. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21400. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21404. */
  21405. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21406. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21407. if (scene !== undefined) {
  21408. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21409. updatable = scene;
  21410. }
  21411. scene = subdivisions;
  21412. subdivisions = 1;
  21413. }
  21414. var options = {
  21415. height: height,
  21416. diameterTop: diameterTop,
  21417. diameterBottom: diameterBottom,
  21418. tessellation: tessellation,
  21419. subdivisions: subdivisions,
  21420. sideOrientation: sideOrientation,
  21421. updatable: updatable
  21422. };
  21423. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21424. };
  21425. // Torus (Code from SharpDX.org)
  21426. /**
  21427. * Creates a torus mesh.
  21428. * Please consider using the same method from the MeshBuilder class instead.
  21429. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21430. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21431. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21432. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21433. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21435. */
  21436. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21437. var options = {
  21438. diameter: diameter,
  21439. thickness: thickness,
  21440. tessellation: tessellation,
  21441. sideOrientation: sideOrientation,
  21442. updatable: updatable
  21443. };
  21444. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21445. };
  21446. /**
  21447. * Creates a torus knot mesh.
  21448. * Please consider using the same method from the MeshBuilder class instead.
  21449. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21450. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21451. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21452. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21453. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21454. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21456. */
  21457. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21458. var options = {
  21459. radius: radius,
  21460. tube: tube,
  21461. radialSegments: radialSegments,
  21462. tubularSegments: tubularSegments,
  21463. p: p,
  21464. q: q,
  21465. sideOrientation: sideOrientation,
  21466. updatable: updatable
  21467. };
  21468. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21469. };
  21470. /**
  21471. * Creates a line mesh.
  21472. * Please consider using the same method from the MeshBuilder class instead.
  21473. * 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.
  21474. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21475. * The parameter `points` is an array successive Vector3.
  21476. * 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
  21477. * When updating an instance, remember that only point positions can change, not the number of points.
  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.CreateLines = function (name, points, scene, updatable, instance) {
  21481. var options = {
  21482. points: points,
  21483. updatable: updatable,
  21484. instance: instance
  21485. };
  21486. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21487. };
  21488. /**
  21489. * Creates a dashed line mesh.
  21490. * Please consider using the same method from the MeshBuilder class instead.
  21491. * 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.
  21492. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21493. * The parameter `points` is an array successive Vector3.
  21494. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21495. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21496. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21497. * 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
  21498. * When updating an instance, remember that only point positions can change, not the number of points.
  21499. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21500. */
  21501. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21502. var options = {
  21503. points: points,
  21504. dashSize: dashSize,
  21505. gapSize: gapSize,
  21506. dashNb: dashNb,
  21507. updatable: updatable,
  21508. instance: instance
  21509. };
  21510. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21511. };
  21512. /**
  21513. * Creates an extruded shape mesh.
  21514. * 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.
  21515. * Please consider using the same method from the MeshBuilder class instead.
  21516. *
  21517. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21518. * 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
  21519. * extruded along the Z axis.
  21520. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21521. * 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.
  21522. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21523. * 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
  21524. * 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
  21525. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21526. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21527. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21529. */
  21530. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21531. var options = {
  21532. shape: shape,
  21533. path: path,
  21534. scale: scale,
  21535. rotation: rotation,
  21536. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21537. sideOrientation: sideOrientation,
  21538. instance: instance,
  21539. updatable: updatable
  21540. };
  21541. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21542. };
  21543. /**
  21544. * Creates an custom extruded shape mesh.
  21545. * 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.
  21546. * Please consider using the same method from the MeshBuilder class instead.
  21547. *
  21548. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21549. * 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
  21550. * extruded along the Z axis.
  21551. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21552. * 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
  21553. * and the distance of this point from the begining of the path :
  21554. * ```javascript
  21555. * var rotationFunction = function(i, distance) {
  21556. * // do things
  21557. * return rotationValue; }
  21558. * ```
  21559. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21560. * 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
  21561. * and the distance of this point from the begining of the path :
  21562. * ```javascript
  21563. * var scaleFunction = function(i, distance) {
  21564. * // do things
  21565. * return scaleValue;}
  21566. * ```
  21567. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21568. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21569. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21570. * 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
  21571. * 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
  21572. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21576. */
  21577. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21578. var options = {
  21579. shape: shape,
  21580. path: path,
  21581. scaleFunction: scaleFunction,
  21582. rotationFunction: rotationFunction,
  21583. ribbonCloseArray: ribbonCloseArray,
  21584. ribbonClosePath: ribbonClosePath,
  21585. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21586. sideOrientation: sideOrientation,
  21587. instance: instance,
  21588. updatable: updatable
  21589. };
  21590. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21591. };
  21592. /**
  21593. * Creates lathe mesh.
  21594. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21595. * Please consider using the same method from the MeshBuilder class instead.
  21596. * 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
  21597. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21598. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21599. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21600. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21601. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21603. */
  21604. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21605. var options = {
  21606. shape: shape,
  21607. radius: radius,
  21608. tessellation: tessellation,
  21609. sideOrientation: sideOrientation,
  21610. updatable: updatable
  21611. };
  21612. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21613. };
  21614. /**
  21615. * Creates a plane mesh.
  21616. * Please consider using the same method from the MeshBuilder class instead.
  21617. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21619. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21621. */
  21622. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21623. var options = {
  21624. size: size,
  21625. width: size,
  21626. height: size,
  21627. sideOrientation: sideOrientation,
  21628. updatable: updatable
  21629. };
  21630. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21631. };
  21632. /**
  21633. * Creates a ground mesh.
  21634. * Please consider using the same method from the MeshBuilder class instead.
  21635. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21636. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21638. */
  21639. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21640. var options = {
  21641. width: width,
  21642. height: height,
  21643. subdivisions: subdivisions,
  21644. updatable: updatable
  21645. };
  21646. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21647. };
  21648. /**
  21649. * Creates a tiled ground mesh.
  21650. * Please consider using the same method from the MeshBuilder class instead.
  21651. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21652. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21653. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21654. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21655. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21656. * numbers of subdivisions on the ground width and height of each tile.
  21657. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21658. */
  21659. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21660. var options = {
  21661. xmin: xmin,
  21662. zmin: zmin,
  21663. xmax: xmax,
  21664. zmax: zmax,
  21665. subdivisions: subdivisions,
  21666. precision: precision,
  21667. updatable: updatable
  21668. };
  21669. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21670. };
  21671. /**
  21672. * Creates a ground mesh from a height map.
  21673. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21674. * Please consider using the same method from the MeshBuilder class instead.
  21675. * The parameter `url` sets the URL of the height map image resource.
  21676. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21677. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21678. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21679. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21680. * 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).
  21681. * This function is passed the newly built mesh :
  21682. * ```javascript
  21683. * function(mesh) { // do things
  21684. * return; }
  21685. * ```
  21686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21687. */
  21688. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21689. var options = {
  21690. width: width,
  21691. height: height,
  21692. subdivisions: subdivisions,
  21693. minHeight: minHeight,
  21694. maxHeight: maxHeight,
  21695. updatable: updatable,
  21696. onReady: onReady
  21697. };
  21698. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21699. };
  21700. /**
  21701. * Creates a tube mesh.
  21702. * 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.
  21703. * Please consider using the same method from the MeshBuilder class instead.
  21704. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21705. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21706. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21707. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21708. * 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.
  21709. * It must return a radius value (positive float) :
  21710. * ```javascript
  21711. * var radiusFunction = function(i, distance) {
  21712. * // do things
  21713. * return radius; }
  21714. * ```
  21715. * 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
  21716. * 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
  21717. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21718. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21720. */
  21721. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21722. var options = {
  21723. path: path,
  21724. radius: radius,
  21725. tessellation: tessellation,
  21726. radiusFunction: radiusFunction,
  21727. arc: 1,
  21728. cap: cap,
  21729. updatable: updatable,
  21730. sideOrientation: sideOrientation,
  21731. instance: instance
  21732. };
  21733. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21734. };
  21735. /**
  21736. * Creates a polyhedron mesh.
  21737. * Please consider using the same method from the MeshBuilder class instead.
  21738. * 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
  21739. * to choose the wanted type.
  21740. * The parameter `size` (positive float, default 1) sets the polygon size.
  21741. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21742. * 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`.
  21743. * 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
  21744. * 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)`).
  21745. * 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
  21746. * 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.
  21747. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21748. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21750. */
  21751. Mesh.CreatePolyhedron = function (name, options, scene) {
  21752. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21753. };
  21754. /**
  21755. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21756. * Please consider using the same method from the MeshBuilder class instead.
  21757. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21758. * 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`).
  21759. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21760. * 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.
  21761. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21762. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21763. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21764. */
  21765. Mesh.CreateIcoSphere = function (name, options, scene) {
  21766. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21767. };
  21768. /**
  21769. * Creates a decal mesh.
  21770. * Please consider using the same method from the MeshBuilder class instead.
  21771. * 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.
  21772. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21773. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21774. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21775. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21776. */
  21777. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21778. var options = {
  21779. position: position,
  21780. normal: normal,
  21781. size: size,
  21782. angle: angle
  21783. };
  21784. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21785. };
  21786. // Skeletons
  21787. /**
  21788. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21789. */
  21790. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21791. var source;
  21792. if (!this._sourcePositions) {
  21793. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21794. this._sourcePositions = new Float32Array(source);
  21795. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21796. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21797. }
  21798. }
  21799. return this._sourcePositions;
  21800. };
  21801. /**
  21802. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21803. */
  21804. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21805. var source;
  21806. if (!this._sourceNormals) {
  21807. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21808. this._sourceNormals = new Float32Array(source);
  21809. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21810. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21811. }
  21812. }
  21813. return this._sourceNormals;
  21814. };
  21815. /**
  21816. * Update the vertex buffers by applying transformation from the bones
  21817. * @param {skeleton} skeleton to apply
  21818. */
  21819. Mesh.prototype.applySkeleton = function (skeleton) {
  21820. if (!this.geometry) {
  21821. return;
  21822. }
  21823. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21824. return;
  21825. }
  21826. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21827. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21828. return this;
  21829. }
  21830. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21831. return this;
  21832. }
  21833. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21834. return this;
  21835. }
  21836. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21837. return this;
  21838. }
  21839. if (!this._sourcePositions) {
  21840. var submeshes = this.subMeshes.slice();
  21841. this.setPositionsForCPUSkinning();
  21842. this.subMeshes = submeshes;
  21843. }
  21844. if (!this._sourceNormals) {
  21845. this.setNormalsForCPUSkinning();
  21846. }
  21847. // positionsData checks for not being Float32Array will only pass at most once
  21848. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21849. if (!(positionsData instanceof Float32Array)) {
  21850. positionsData = new Float32Array(positionsData);
  21851. }
  21852. // normalsData checks for not being Float32Array will only pass at most once
  21853. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21854. if (!(normalsData instanceof Float32Array)) {
  21855. normalsData = new Float32Array(normalsData);
  21856. }
  21857. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21858. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21859. var needExtras = this.numBoneInfluencers > 4;
  21860. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21861. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21862. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21863. var tempVector3 = BABYLON.Vector3.Zero();
  21864. var finalMatrix = new BABYLON.Matrix();
  21865. var tempMatrix = new BABYLON.Matrix();
  21866. var matWeightIdx = 0;
  21867. var inf;
  21868. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21869. var weight;
  21870. for (inf = 0; inf < 4; inf++) {
  21871. weight = matricesWeightsData[matWeightIdx + inf];
  21872. if (weight > 0) {
  21873. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21874. finalMatrix.addToSelf(tempMatrix);
  21875. }
  21876. else
  21877. break;
  21878. }
  21879. if (needExtras) {
  21880. for (inf = 0; inf < 4; inf++) {
  21881. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21882. if (weight > 0) {
  21883. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21884. finalMatrix.addToSelf(tempMatrix);
  21885. }
  21886. else
  21887. break;
  21888. }
  21889. }
  21890. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21891. tempVector3.toArray(positionsData, index);
  21892. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21893. tempVector3.toArray(normalsData, index);
  21894. finalMatrix.reset();
  21895. }
  21896. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21897. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21898. return this;
  21899. };
  21900. // Tools
  21901. /**
  21902. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21903. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21904. */
  21905. Mesh.MinMax = function (meshes) {
  21906. var minVector = null;
  21907. var maxVector = null;
  21908. meshes.forEach(function (mesh, index, array) {
  21909. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21910. if (!minVector) {
  21911. minVector = boundingBox.minimumWorld;
  21912. maxVector = boundingBox.maximumWorld;
  21913. }
  21914. else {
  21915. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21916. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21917. }
  21918. });
  21919. return {
  21920. min: minVector,
  21921. max: maxVector
  21922. };
  21923. };
  21924. /**
  21925. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21926. */
  21927. Mesh.Center = function (meshesOrMinMaxVector) {
  21928. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21929. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21930. };
  21931. /**
  21932. * Merge the array of meshes into a single mesh for performance reasons.
  21933. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21934. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21935. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21936. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21937. */
  21938. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21939. if (disposeSource === void 0) { disposeSource = true; }
  21940. var index;
  21941. if (!allow32BitsIndices) {
  21942. var totalVertices = 0;
  21943. // Counting vertices
  21944. for (index = 0; index < meshes.length; index++) {
  21945. if (meshes[index]) {
  21946. totalVertices += meshes[index].getTotalVertices();
  21947. if (totalVertices > 65536) {
  21948. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21949. return null;
  21950. }
  21951. }
  21952. }
  21953. }
  21954. // Merge
  21955. var vertexData;
  21956. var otherVertexData;
  21957. var source;
  21958. for (index = 0; index < meshes.length; index++) {
  21959. if (meshes[index]) {
  21960. meshes[index].computeWorldMatrix(true);
  21961. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21962. otherVertexData.transform(meshes[index].getWorldMatrix());
  21963. if (vertexData) {
  21964. vertexData.merge(otherVertexData);
  21965. }
  21966. else {
  21967. vertexData = otherVertexData;
  21968. source = meshes[index];
  21969. }
  21970. }
  21971. }
  21972. if (!meshSubclass) {
  21973. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21974. }
  21975. vertexData.applyToMesh(meshSubclass);
  21976. // Setting properties
  21977. meshSubclass.material = source.material;
  21978. meshSubclass.checkCollisions = source.checkCollisions;
  21979. // Cleaning
  21980. if (disposeSource) {
  21981. for (index = 0; index < meshes.length; index++) {
  21982. if (meshes[index]) {
  21983. meshes[index].dispose();
  21984. }
  21985. }
  21986. }
  21987. return meshSubclass;
  21988. };
  21989. // Consts
  21990. Mesh._FRONTSIDE = 0;
  21991. Mesh._BACKSIDE = 1;
  21992. Mesh._DOUBLESIDE = 2;
  21993. Mesh._DEFAULTSIDE = 0;
  21994. Mesh._NO_CAP = 0;
  21995. Mesh._CAP_START = 1;
  21996. Mesh._CAP_END = 2;
  21997. Mesh._CAP_ALL = 3;
  21998. return Mesh;
  21999. }(BABYLON.AbstractMesh));
  22000. BABYLON.Mesh = Mesh;
  22001. })(BABYLON || (BABYLON = {}));
  22002. //# sourceMappingURL=babylon.mesh.js.map
  22003. var BABYLON;
  22004. (function (BABYLON) {
  22005. var SubMesh = (function () {
  22006. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22007. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22008. this.materialIndex = materialIndex;
  22009. this.verticesStart = verticesStart;
  22010. this.verticesCount = verticesCount;
  22011. this.indexStart = indexStart;
  22012. this.indexCount = indexCount;
  22013. this._renderId = 0;
  22014. this._mesh = mesh;
  22015. this._renderingMesh = renderingMesh || mesh;
  22016. mesh.subMeshes.push(this);
  22017. this._trianglePlanes = [];
  22018. this._id = mesh.subMeshes.length - 1;
  22019. if (createBoundingBox) {
  22020. this.refreshBoundingInfo();
  22021. mesh.computeWorldMatrix(true);
  22022. }
  22023. }
  22024. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22025. get: function () {
  22026. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22027. },
  22028. enumerable: true,
  22029. configurable: true
  22030. });
  22031. SubMesh.prototype.getBoundingInfo = function () {
  22032. if (this.IsGlobal) {
  22033. return this._mesh.getBoundingInfo();
  22034. }
  22035. return this._boundingInfo;
  22036. };
  22037. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22038. this._boundingInfo = boundingInfo;
  22039. };
  22040. SubMesh.prototype.getMesh = function () {
  22041. return this._mesh;
  22042. };
  22043. SubMesh.prototype.getRenderingMesh = function () {
  22044. return this._renderingMesh;
  22045. };
  22046. SubMesh.prototype.getMaterial = function () {
  22047. var rootMaterial = this._renderingMesh.material;
  22048. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22049. var multiMaterial = rootMaterial;
  22050. return multiMaterial.getSubMaterial(this.materialIndex);
  22051. }
  22052. if (!rootMaterial) {
  22053. return this._mesh.getScene().defaultMaterial;
  22054. }
  22055. return rootMaterial;
  22056. };
  22057. // Methods
  22058. SubMesh.prototype.refreshBoundingInfo = function () {
  22059. this._lastColliderWorldVertices = null;
  22060. if (this.IsGlobal) {
  22061. return;
  22062. }
  22063. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22064. if (!data) {
  22065. this._boundingInfo = this._mesh._boundingInfo;
  22066. return;
  22067. }
  22068. var indices = this._renderingMesh.getIndices();
  22069. var extend;
  22070. //is this the only submesh?
  22071. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22072. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22073. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22074. }
  22075. else {
  22076. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22077. }
  22078. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22079. };
  22080. SubMesh.prototype._checkCollision = function (collider) {
  22081. return this.getBoundingInfo()._checkCollision(collider);
  22082. };
  22083. SubMesh.prototype.updateBoundingInfo = function (world) {
  22084. if (!this.getBoundingInfo()) {
  22085. this.refreshBoundingInfo();
  22086. }
  22087. this.getBoundingInfo().update(world);
  22088. };
  22089. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22090. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22091. };
  22092. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22093. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22094. };
  22095. SubMesh.prototype.render = function (enableAlphaMode) {
  22096. this._renderingMesh.render(this, enableAlphaMode);
  22097. };
  22098. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22099. if (!this._linesIndexBuffer) {
  22100. var linesIndices = [];
  22101. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22102. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22103. }
  22104. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22105. this.linesIndexCount = linesIndices.length;
  22106. }
  22107. return this._linesIndexBuffer;
  22108. };
  22109. SubMesh.prototype.canIntersects = function (ray) {
  22110. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22111. };
  22112. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22113. var intersectInfo = null;
  22114. // LineMesh first as it's also a Mesh...
  22115. if (this._mesh instanceof BABYLON.LinesMesh) {
  22116. var lineMesh = this._mesh;
  22117. // Line test
  22118. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22119. var p0 = positions[indices[index]];
  22120. var p1 = positions[indices[index + 1]];
  22121. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22122. if (length < 0) {
  22123. continue;
  22124. }
  22125. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22126. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22127. if (fastCheck) {
  22128. break;
  22129. }
  22130. }
  22131. }
  22132. }
  22133. else {
  22134. // Triangles test
  22135. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22136. var p0 = positions[indices[index]];
  22137. var p1 = positions[indices[index + 1]];
  22138. var p2 = positions[indices[index + 2]];
  22139. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22140. if (currentIntersectInfo) {
  22141. if (currentIntersectInfo.distance < 0) {
  22142. continue;
  22143. }
  22144. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22145. intersectInfo = currentIntersectInfo;
  22146. intersectInfo.faceId = index / 3;
  22147. if (fastCheck) {
  22148. break;
  22149. }
  22150. }
  22151. }
  22152. }
  22153. }
  22154. return intersectInfo;
  22155. };
  22156. // Clone
  22157. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22158. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22159. if (!this.IsGlobal) {
  22160. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22161. }
  22162. return result;
  22163. };
  22164. // Dispose
  22165. SubMesh.prototype.dispose = function () {
  22166. if (this._linesIndexBuffer) {
  22167. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22168. this._linesIndexBuffer = null;
  22169. }
  22170. // Remove from mesh
  22171. var index = this._mesh.subMeshes.indexOf(this);
  22172. this._mesh.subMeshes.splice(index, 1);
  22173. };
  22174. // Statics
  22175. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22176. var minVertexIndex = Number.MAX_VALUE;
  22177. var maxVertexIndex = -Number.MAX_VALUE;
  22178. renderingMesh = renderingMesh || mesh;
  22179. var indices = renderingMesh.getIndices();
  22180. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22181. var vertexIndex = indices[index];
  22182. if (vertexIndex < minVertexIndex)
  22183. minVertexIndex = vertexIndex;
  22184. if (vertexIndex > maxVertexIndex)
  22185. maxVertexIndex = vertexIndex;
  22186. }
  22187. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22188. };
  22189. return SubMesh;
  22190. }());
  22191. BABYLON.SubMesh = SubMesh;
  22192. })(BABYLON || (BABYLON = {}));
  22193. //# sourceMappingURL=babylon.subMesh.js.map
  22194. var BABYLON;
  22195. (function (BABYLON) {
  22196. var MeshBuilder = (function () {
  22197. function MeshBuilder() {
  22198. }
  22199. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22200. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22201. return BABYLON.Mesh.DOUBLESIDE;
  22202. }
  22203. if (orientation === undefined || orientation === null) {
  22204. return BABYLON.Mesh.FRONTSIDE;
  22205. }
  22206. return orientation;
  22207. };
  22208. /**
  22209. * Creates a box mesh.
  22210. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22211. * The parameter `size` sets the size (float) of each box side (default 1).
  22212. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22213. * 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).
  22214. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22215. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22216. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22218. */
  22219. MeshBuilder.CreateBox = function (name, options, scene) {
  22220. var box = new BABYLON.Mesh(name, scene);
  22221. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22222. box.sideOrientation = options.sideOrientation;
  22223. var vertexData = BABYLON.VertexData.CreateBox(options);
  22224. vertexData.applyToMesh(box, options.updatable);
  22225. return box;
  22226. };
  22227. /**
  22228. * Creates a sphere mesh.
  22229. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22230. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22231. * 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`).
  22232. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22233. * 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
  22234. * 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).
  22235. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22236. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22238. */
  22239. MeshBuilder.CreateSphere = function (name, options, scene) {
  22240. var sphere = new BABYLON.Mesh(name, scene);
  22241. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22242. sphere.sideOrientation = options.sideOrientation;
  22243. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22244. vertexData.applyToMesh(sphere, options.updatable);
  22245. return sphere;
  22246. };
  22247. /**
  22248. * Creates a plane polygonal mesh. By default, this is a disc.
  22249. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22250. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22251. * 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.
  22252. * 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
  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.CreateDisc = function (name, options, scene) {
  22258. var disc = new BABYLON.Mesh(name, scene);
  22259. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22260. disc.sideOrientation = options.sideOrientation;
  22261. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22262. vertexData.applyToMesh(disc, options.updatable);
  22263. return disc;
  22264. };
  22265. /**
  22266. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22267. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22268. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22269. * 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`).
  22270. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22271. * 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.
  22272. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22273. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22275. */
  22276. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22277. var sphere = new BABYLON.Mesh(name, scene);
  22278. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22279. sphere.sideOrientation = options.sideOrientation;
  22280. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22281. vertexData.applyToMesh(sphere, options.updatable);
  22282. return sphere;
  22283. };
  22284. ;
  22285. /**
  22286. * Creates a ribbon mesh.
  22287. * 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.
  22288. *
  22289. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22290. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22291. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22292. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22293. * 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.
  22294. * 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.
  22295. * 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
  22296. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22297. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22298. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22300. */
  22301. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22302. var pathArray = options.pathArray;
  22303. var closeArray = options.closeArray;
  22304. var closePath = options.closePath;
  22305. var offset = options.offset;
  22306. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22307. var instance = options.instance;
  22308. var updatable = options.updatable;
  22309. if (instance) {
  22310. // positionFunction : ribbon case
  22311. // only pathArray and sideOrientation parameters are taken into account for positions update
  22312. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22313. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22314. var positionFunction = function (positions) {
  22315. var minlg = pathArray[0].length;
  22316. var i = 0;
  22317. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22318. for (var si = 1; si <= ns; si++) {
  22319. for (var p = 0; p < pathArray.length; p++) {
  22320. var path = pathArray[p];
  22321. var l = path.length;
  22322. minlg = (minlg < l) ? minlg : l;
  22323. var j = 0;
  22324. while (j < minlg) {
  22325. positions[i] = path[j].x;
  22326. positions[i + 1] = path[j].y;
  22327. positions[i + 2] = path[j].z;
  22328. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22329. BABYLON.Tmp.Vector3[0].x = path[j].x;
  22330. }
  22331. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  22332. BABYLON.Tmp.Vector3[1].x = path[j].x;
  22333. }
  22334. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  22335. BABYLON.Tmp.Vector3[0].y = path[j].y;
  22336. }
  22337. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  22338. BABYLON.Tmp.Vector3[1].y = path[j].y;
  22339. }
  22340. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  22341. BABYLON.Tmp.Vector3[0].z = path[j].z;
  22342. }
  22343. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  22344. BABYLON.Tmp.Vector3[1].z = path[j].z;
  22345. }
  22346. j++;
  22347. i += 3;
  22348. }
  22349. if (instance._closePath) {
  22350. positions[i] = path[0].x;
  22351. positions[i + 1] = path[0].y;
  22352. positions[i + 2] = path[0].z;
  22353. i += 3;
  22354. }
  22355. }
  22356. }
  22357. };
  22358. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22359. positionFunction(positions);
  22360. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  22361. instance._boundingInfo.update(instance._worldMatrix);
  22362. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22363. if (!(instance.areNormalsFrozen)) {
  22364. var indices = instance.getIndices();
  22365. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22366. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22367. if (instance._closePath) {
  22368. var indexFirst = 0;
  22369. var indexLast = 0;
  22370. for (var p = 0; p < pathArray.length; p++) {
  22371. indexFirst = instance._idx[p] * 3;
  22372. if (p + 1 < pathArray.length) {
  22373. indexLast = (instance._idx[p + 1] - 1) * 3;
  22374. }
  22375. else {
  22376. indexLast = normals.length - 3;
  22377. }
  22378. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  22379. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  22380. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  22381. normals[indexLast] = normals[indexFirst];
  22382. normals[indexLast + 1] = normals[indexFirst + 1];
  22383. normals[indexLast + 2] = normals[indexFirst + 2];
  22384. }
  22385. }
  22386. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22387. }
  22388. return instance;
  22389. }
  22390. else {
  22391. var ribbon = new BABYLON.Mesh(name, scene);
  22392. ribbon.sideOrientation = sideOrientation;
  22393. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  22394. if (closePath) {
  22395. ribbon._idx = vertexData._idx;
  22396. }
  22397. ribbon._closePath = closePath;
  22398. ribbon._closeArray = closeArray;
  22399. vertexData.applyToMesh(ribbon, updatable);
  22400. return ribbon;
  22401. }
  22402. };
  22403. /**
  22404. * Creates a cylinder or a cone mesh.
  22405. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  22406. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22407. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22408. * 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.
  22409. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22410. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22411. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  22412. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  22413. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  22414. * 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).
  22415. * 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
  22416. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  22417. * 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
  22418. * 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.
  22419. * If `enclose` is false, a ring surface is one element.
  22420. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  22421. * 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
  22422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22423. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22425. */
  22426. MeshBuilder.CreateCylinder = function (name, options, scene) {
  22427. var cylinder = new BABYLON.Mesh(name, scene);
  22428. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22429. cylinder.sideOrientation = options.sideOrientation;
  22430. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  22431. vertexData.applyToMesh(cylinder, options.updatable);
  22432. return cylinder;
  22433. };
  22434. /**
  22435. * Creates a torus mesh.
  22436. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  22437. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22438. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22439. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22443. */
  22444. MeshBuilder.CreateTorus = function (name, options, scene) {
  22445. var torus = new BABYLON.Mesh(name, scene);
  22446. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22447. torus.sideOrientation = options.sideOrientation;
  22448. var vertexData = BABYLON.VertexData.CreateTorus(options);
  22449. vertexData.applyToMesh(torus, options.updatable);
  22450. return torus;
  22451. };
  22452. /**
  22453. * Creates a torus knot mesh.
  22454. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  22455. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22456. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22457. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22458. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22459. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22460. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22462. */
  22463. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  22464. var torusKnot = new BABYLON.Mesh(name, scene);
  22465. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22466. torusKnot.sideOrientation = options.sideOrientation;
  22467. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  22468. vertexData.applyToMesh(torusKnot, options.updatable);
  22469. return torusKnot;
  22470. };
  22471. /**
  22472. * Creates a line system mesh.
  22473. * A line system is a pool of many lines gathered in a single mesh.
  22474. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22475. * 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.
  22476. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22477. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22478. * 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
  22479. * 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
  22480. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22482. */
  22483. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22484. var instance = options.instance;
  22485. var lines = options.lines;
  22486. if (instance) {
  22487. var positionFunction = function (positions) {
  22488. var i = 0;
  22489. for (var l = 0; l < lines.length; l++) {
  22490. var points = lines[l];
  22491. for (var p = 0; p < points.length; p++) {
  22492. positions[i] = points[p].x;
  22493. positions[i + 1] = points[p].y;
  22494. positions[i + 2] = points[p].z;
  22495. i += 3;
  22496. }
  22497. }
  22498. };
  22499. instance.updateMeshPositions(positionFunction, false);
  22500. return instance;
  22501. }
  22502. // line system creation
  22503. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22504. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22505. vertexData.applyToMesh(lineSystem, options.updatable);
  22506. return lineSystem;
  22507. };
  22508. /**
  22509. * Creates a line mesh.
  22510. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22511. * 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.
  22512. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22513. * The parameter `points` is an array successive Vector3.
  22514. * 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
  22515. * When updating an instance, remember that only point positions can change, not the number of points.
  22516. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22517. */
  22518. MeshBuilder.CreateLines = function (name, options, scene) {
  22519. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22520. return lines;
  22521. };
  22522. /**
  22523. * Creates a dashed line mesh.
  22524. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22525. * 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.
  22526. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22527. * The parameter `points` is an array successive Vector3.
  22528. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22529. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22530. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22531. * 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
  22532. * When updating an instance, remember that only point positions can change, not the number of points.
  22533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22534. */
  22535. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22536. var points = options.points;
  22537. var instance = options.instance;
  22538. var gapSize = options.gapSize;
  22539. var dashNb = options.dashNb;
  22540. var dashSize = options.dashSize;
  22541. if (instance) {
  22542. var positionFunction = function (positions) {
  22543. var curvect = BABYLON.Vector3.Zero();
  22544. var nbSeg = positions.length / 6;
  22545. var lg = 0;
  22546. var nb = 0;
  22547. var shft = 0;
  22548. var dashshft = 0;
  22549. var curshft = 0;
  22550. var p = 0;
  22551. var i = 0;
  22552. var j = 0;
  22553. for (i = 0; i < points.length - 1; i++) {
  22554. points[i + 1].subtractToRef(points[i], curvect);
  22555. lg += curvect.length();
  22556. }
  22557. shft = lg / nbSeg;
  22558. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22559. for (i = 0; i < points.length - 1; i++) {
  22560. points[i + 1].subtractToRef(points[i], curvect);
  22561. nb = Math.floor(curvect.length() / shft);
  22562. curvect.normalize();
  22563. j = 0;
  22564. while (j < nb && p < positions.length) {
  22565. curshft = shft * j;
  22566. positions[p] = points[i].x + curshft * curvect.x;
  22567. positions[p + 1] = points[i].y + curshft * curvect.y;
  22568. positions[p + 2] = points[i].z + curshft * curvect.z;
  22569. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22570. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22571. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22572. p += 6;
  22573. j++;
  22574. }
  22575. }
  22576. while (p < positions.length) {
  22577. positions[p] = points[i].x;
  22578. positions[p + 1] = points[i].y;
  22579. positions[p + 2] = points[i].z;
  22580. p += 3;
  22581. }
  22582. };
  22583. instance.updateMeshPositions(positionFunction, false);
  22584. return instance;
  22585. }
  22586. // dashed lines creation
  22587. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22588. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22589. vertexData.applyToMesh(dashedLines, options.updatable);
  22590. dashedLines.dashSize = dashSize;
  22591. dashedLines.gapSize = gapSize;
  22592. return dashedLines;
  22593. };
  22594. /**
  22595. * Creates an extruded shape mesh.
  22596. * 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.
  22597. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22598. *
  22599. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22600. * 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
  22601. * extruded along the Z axis.
  22602. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22603. * 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.
  22604. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22605. * 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
  22606. * 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
  22607. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22608. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22609. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22610. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22611. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22612. */
  22613. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22614. var path = options.path;
  22615. var shape = options.shape;
  22616. var scale = options.scale || 1;
  22617. var rotation = options.rotation || 0;
  22618. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22619. var updatable = options.updatable;
  22620. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22621. var instance = options.instance;
  22622. var invertUV = options.invertUV || false;
  22623. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22624. };
  22625. /**
  22626. * Creates an custom extruded shape mesh.
  22627. * 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.
  22628. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22629. *
  22630. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22631. * 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
  22632. * extruded along the Z axis.
  22633. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22634. * 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
  22635. * and the distance of this point from the begining of the path :
  22636. * ```javascript
  22637. * var rotationFunction = function(i, distance) {
  22638. * // do things
  22639. * return rotationValue; }
  22640. * ```
  22641. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22642. * 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
  22643. * and the distance of this point from the begining of the path :
  22644. * ```javascript
  22645. * var scaleFunction = function(i, distance) {
  22646. * // do things
  22647. * return scaleValue;}
  22648. * ```
  22649. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22650. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22651. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22652. * 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
  22653. * 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
  22654. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22655. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22656. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22657. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22658. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22659. */
  22660. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22661. var path = options.path;
  22662. var shape = options.shape;
  22663. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22664. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22665. var ribbonCloseArray = options.ribbonCloseArray || false;
  22666. var ribbonClosePath = options.ribbonClosePath || false;
  22667. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22668. var updatable = options.updatable;
  22669. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22670. var instance = options.instance;
  22671. var invertUV = options.invertUV || false;
  22672. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22673. };
  22674. /**
  22675. * Creates lathe mesh.
  22676. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22677. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22678. *
  22679. * 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
  22680. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22681. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22682. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22683. * 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.
  22684. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22685. * 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
  22686. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22687. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22688. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22690. */
  22691. MeshBuilder.CreateLathe = function (name, options, scene) {
  22692. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22693. var closed = (options.closed === undefined) ? true : options.closed;
  22694. var shape = options.shape;
  22695. var radius = options.radius || 1;
  22696. var tessellation = options.tessellation || 64;
  22697. var updatable = options.updatable;
  22698. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22699. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22700. var pi2 = Math.PI * 2;
  22701. var paths = new Array();
  22702. var invertUV = options.invertUV || false;
  22703. var i = 0;
  22704. var p = 0;
  22705. var step = pi2 / tessellation * arc;
  22706. var rotated;
  22707. var path = new Array();
  22708. ;
  22709. for (i = 0; i <= tessellation; i++) {
  22710. var path = [];
  22711. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22712. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22713. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22714. }
  22715. for (p = 0; p < shape.length; p++) {
  22716. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22717. path.push(rotated);
  22718. }
  22719. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22720. 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));
  22721. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22722. }
  22723. paths.push(path);
  22724. }
  22725. // lathe ribbon
  22726. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22727. return lathe;
  22728. };
  22729. /**
  22730. * Creates a plane mesh.
  22731. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22732. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22733. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22734. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22735. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22736. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22737. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22738. */
  22739. MeshBuilder.CreatePlane = function (name, options, scene) {
  22740. var plane = new BABYLON.Mesh(name, scene);
  22741. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22742. plane.sideOrientation = options.sideOrientation;
  22743. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22744. vertexData.applyToMesh(plane, options.updatable);
  22745. if (options.sourcePlane) {
  22746. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22747. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22748. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22749. plane.rotate(vectorProduct, product);
  22750. }
  22751. return plane;
  22752. };
  22753. /**
  22754. * Creates a ground mesh.
  22755. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22756. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22757. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22759. */
  22760. MeshBuilder.CreateGround = function (name, options, scene) {
  22761. var ground = new BABYLON.GroundMesh(name, scene);
  22762. ground._setReady(false);
  22763. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22764. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22765. ground._width = options.width || 1;
  22766. ground._height = options.height || 1;
  22767. ground._maxX = ground._width / 2;
  22768. ground._maxZ = ground._height / 2;
  22769. ground._minX = -ground._maxX;
  22770. ground._minZ = -ground._maxZ;
  22771. var vertexData = BABYLON.VertexData.CreateGround(options);
  22772. vertexData.applyToMesh(ground, options.updatable);
  22773. ground._setReady(true);
  22774. return ground;
  22775. };
  22776. /**
  22777. * Creates a tiled ground mesh.
  22778. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22779. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22780. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22781. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22782. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22783. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22784. * numbers of subdivisions on the ground width and height of each tile.
  22785. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22786. */
  22787. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22788. var tiledGround = new BABYLON.Mesh(name, scene);
  22789. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22790. vertexData.applyToMesh(tiledGround, options.updatable);
  22791. return tiledGround;
  22792. };
  22793. /**
  22794. * Creates a ground mesh from a height map.
  22795. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22796. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22797. * The parameter `url` sets the URL of the height map image resource.
  22798. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22799. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22800. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22801. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22802. * 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).
  22803. * This function is passed the newly built mesh :
  22804. * ```javascript
  22805. * function(mesh) { // do things
  22806. * return; }
  22807. * ```
  22808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22809. */
  22810. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22811. var width = options.width || 10.0;
  22812. var height = options.height || 10.0;
  22813. var subdivisions = options.subdivisions || 1 | 0;
  22814. var minHeight = options.minHeight || 0.0;
  22815. var maxHeight = options.maxHeight || 10.0;
  22816. var updatable = options.updatable;
  22817. var onReady = options.onReady;
  22818. var ground = new BABYLON.GroundMesh(name, scene);
  22819. ground._subdivisionsX = subdivisions;
  22820. ground._subdivisionsY = subdivisions;
  22821. ground._width = width;
  22822. ground._height = height;
  22823. ground._maxX = ground._width / 2.0;
  22824. ground._maxZ = ground._height / 2.0;
  22825. ground._minX = -ground._maxX;
  22826. ground._minZ = -ground._maxZ;
  22827. ground._setReady(false);
  22828. var onload = function (img) {
  22829. // Getting height map data
  22830. var canvas = document.createElement("canvas");
  22831. var context = canvas.getContext("2d");
  22832. var bufferWidth = img.width;
  22833. var bufferHeight = img.height;
  22834. canvas.width = bufferWidth;
  22835. canvas.height = bufferHeight;
  22836. context.drawImage(img, 0, 0);
  22837. // Create VertexData from map data
  22838. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22839. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22840. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22841. width: width, height: height,
  22842. subdivisions: subdivisions,
  22843. minHeight: minHeight, maxHeight: maxHeight,
  22844. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22845. });
  22846. vertexData.applyToMesh(ground, updatable);
  22847. ground._setReady(true);
  22848. //execute ready callback, if set
  22849. if (onReady) {
  22850. onReady(ground);
  22851. }
  22852. };
  22853. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22854. return ground;
  22855. };
  22856. /**
  22857. * Creates a tube mesh.
  22858. * 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.
  22859. *
  22860. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22861. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22862. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22863. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22864. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22865. * 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.
  22866. * It must return a radius value (positive float) :
  22867. * ```javascript
  22868. * var radiusFunction = function(i, distance) {
  22869. * // do things
  22870. * return radius; }
  22871. * ```
  22872. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22873. * 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
  22874. * 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
  22875. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22876. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22877. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22879. */
  22880. MeshBuilder.CreateTube = function (name, options, scene) {
  22881. var path = options.path;
  22882. var radius = options.radius || 1.0;
  22883. var tessellation = options.tessellation || 64 | 0;
  22884. var radiusFunction = options.radiusFunction;
  22885. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22886. var invertUV = options.invertUV || false;
  22887. var updatable = options.updatable;
  22888. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22889. var instance = options.instance;
  22890. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22891. // tube geometry
  22892. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22893. var tangents = path3D.getTangents();
  22894. var normals = path3D.getNormals();
  22895. var distances = path3D.getDistances();
  22896. var pi2 = Math.PI * 2;
  22897. var step = pi2 / tessellation * arc;
  22898. var returnRadius = function () { return radius; };
  22899. var radiusFunctionFinal = radiusFunction || returnRadius;
  22900. var circlePath;
  22901. var rad;
  22902. var normal;
  22903. var rotated;
  22904. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22905. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22906. for (var i = 0; i < path.length; i++) {
  22907. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22908. circlePath = Array(); // current circle array
  22909. normal = normals[i]; // current normal
  22910. for (var t = 0; t < tessellation; t++) {
  22911. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22912. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22913. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22914. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22915. circlePath[t] = rotated;
  22916. }
  22917. circlePaths[index] = circlePath;
  22918. index++;
  22919. }
  22920. // cap
  22921. var capPath = function (nbPoints, pathIndex) {
  22922. var pointCap = Array();
  22923. for (var i = 0; i < nbPoints; i++) {
  22924. pointCap.push(path[pathIndex]);
  22925. }
  22926. return pointCap;
  22927. };
  22928. switch (cap) {
  22929. case BABYLON.Mesh.NO_CAP:
  22930. break;
  22931. case BABYLON.Mesh.CAP_START:
  22932. circlePaths[0] = capPath(tessellation, 0);
  22933. circlePaths[1] = circlePaths[2].slice(0);
  22934. break;
  22935. case BABYLON.Mesh.CAP_END:
  22936. circlePaths[index] = circlePaths[index - 1].slice(0);
  22937. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22938. break;
  22939. case BABYLON.Mesh.CAP_ALL:
  22940. circlePaths[0] = capPath(tessellation, 0);
  22941. circlePaths[1] = circlePaths[2].slice(0);
  22942. circlePaths[index] = circlePaths[index - 1].slice(0);
  22943. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22944. break;
  22945. default:
  22946. break;
  22947. }
  22948. return circlePaths;
  22949. };
  22950. var path3D;
  22951. var pathArray;
  22952. if (instance) {
  22953. var arc = options.arc || instance.arc;
  22954. path3D = (instance.path3D).update(path);
  22955. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22956. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22957. instance.path3D = path3D;
  22958. instance.pathArray = pathArray;
  22959. instance.arc = arc;
  22960. return instance;
  22961. }
  22962. // tube creation
  22963. path3D = new BABYLON.Path3D(path);
  22964. var newPathArray = new Array();
  22965. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22966. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22967. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22968. tube.pathArray = pathArray;
  22969. tube.path3D = path3D;
  22970. tube.tessellation = tessellation;
  22971. tube.cap = cap;
  22972. tube.arc = options.arc;
  22973. return tube;
  22974. };
  22975. /**
  22976. * Creates a polyhedron mesh.
  22977. *
  22978. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22979. * 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
  22980. * to choose the wanted type.
  22981. * The parameter `size` (positive float, default 1) sets the polygon size.
  22982. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22983. * 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`.
  22984. * 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
  22985. * 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)`).
  22986. * 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
  22987. * 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.
  22988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22991. */
  22992. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22993. var polyhedron = new BABYLON.Mesh(name, scene);
  22994. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22995. polyhedron.sideOrientation = options.sideOrientation;
  22996. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22997. vertexData.applyToMesh(polyhedron, options.updatable);
  22998. return polyhedron;
  22999. };
  23000. /**
  23001. * Creates a decal mesh.
  23002. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23003. * 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.
  23004. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23005. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23006. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23007. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23008. */
  23009. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23010. var indices = sourceMesh.getIndices();
  23011. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23012. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23013. var position = options.position || BABYLON.Vector3.Zero();
  23014. var normal = options.normal || BABYLON.Vector3.Up();
  23015. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23016. var angle = options.angle || 0;
  23017. // Getting correct rotation
  23018. if (!normal) {
  23019. var target = new BABYLON.Vector3(0, 0, 1);
  23020. var camera = sourceMesh.getScene().activeCamera;
  23021. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23022. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23023. }
  23024. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23025. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23026. var pitch = Math.atan2(normal.y, len);
  23027. // Matrix
  23028. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23029. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23030. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23031. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23032. var vertexData = new BABYLON.VertexData();
  23033. vertexData.indices = [];
  23034. vertexData.positions = [];
  23035. vertexData.normals = [];
  23036. vertexData.uvs = [];
  23037. var currentVertexDataIndex = 0;
  23038. var extractDecalVector3 = function (indexId) {
  23039. var vertexId = indices[indexId];
  23040. var result = new BABYLON.PositionNormalVertex();
  23041. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23042. // Send vector to decal local world
  23043. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23044. // Get normal
  23045. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23046. return result;
  23047. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23048. var clip = function (vertices, axis) {
  23049. if (vertices.length === 0) {
  23050. return vertices;
  23051. }
  23052. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23053. var clipVertices = function (v0, v1) {
  23054. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23055. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23056. };
  23057. var result = new Array();
  23058. for (var index = 0; index < vertices.length; index += 3) {
  23059. var v1Out;
  23060. var v2Out;
  23061. var v3Out;
  23062. var total = 0;
  23063. var nV1, nV2, nV3, nV4;
  23064. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23065. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23066. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23067. v1Out = d1 > 0;
  23068. v2Out = d2 > 0;
  23069. v3Out = d3 > 0;
  23070. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23071. switch (total) {
  23072. case 0:
  23073. result.push(vertices[index]);
  23074. result.push(vertices[index + 1]);
  23075. result.push(vertices[index + 2]);
  23076. break;
  23077. case 1:
  23078. if (v1Out) {
  23079. nV1 = vertices[index + 1];
  23080. nV2 = vertices[index + 2];
  23081. nV3 = clipVertices(vertices[index], nV1);
  23082. nV4 = clipVertices(vertices[index], nV2);
  23083. }
  23084. if (v2Out) {
  23085. nV1 = vertices[index];
  23086. nV2 = vertices[index + 2];
  23087. nV3 = clipVertices(vertices[index + 1], nV1);
  23088. nV4 = clipVertices(vertices[index + 1], nV2);
  23089. result.push(nV3);
  23090. result.push(nV2.clone());
  23091. result.push(nV1.clone());
  23092. result.push(nV2.clone());
  23093. result.push(nV3.clone());
  23094. result.push(nV4);
  23095. break;
  23096. }
  23097. if (v3Out) {
  23098. nV1 = vertices[index];
  23099. nV2 = vertices[index + 1];
  23100. nV3 = clipVertices(vertices[index + 2], nV1);
  23101. nV4 = clipVertices(vertices[index + 2], nV2);
  23102. }
  23103. result.push(nV1.clone());
  23104. result.push(nV2.clone());
  23105. result.push(nV3);
  23106. result.push(nV4);
  23107. result.push(nV3.clone());
  23108. result.push(nV2.clone());
  23109. break;
  23110. case 2:
  23111. if (!v1Out) {
  23112. nV1 = vertices[index].clone();
  23113. nV2 = clipVertices(nV1, vertices[index + 1]);
  23114. nV3 = clipVertices(nV1, vertices[index + 2]);
  23115. result.push(nV1);
  23116. result.push(nV2);
  23117. result.push(nV3);
  23118. }
  23119. if (!v2Out) {
  23120. nV1 = vertices[index + 1].clone();
  23121. nV2 = clipVertices(nV1, vertices[index + 2]);
  23122. nV3 = clipVertices(nV1, vertices[index]);
  23123. result.push(nV1);
  23124. result.push(nV2);
  23125. result.push(nV3);
  23126. }
  23127. if (!v3Out) {
  23128. nV1 = vertices[index + 2].clone();
  23129. nV2 = clipVertices(nV1, vertices[index]);
  23130. nV3 = clipVertices(nV1, vertices[index + 1]);
  23131. result.push(nV1);
  23132. result.push(nV2);
  23133. result.push(nV3);
  23134. }
  23135. break;
  23136. case 3:
  23137. break;
  23138. }
  23139. }
  23140. return result;
  23141. };
  23142. for (var index = 0; index < indices.length; index += 3) {
  23143. var faceVertices = new Array();
  23144. faceVertices.push(extractDecalVector3(index));
  23145. faceVertices.push(extractDecalVector3(index + 1));
  23146. faceVertices.push(extractDecalVector3(index + 2));
  23147. // Clip
  23148. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23149. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23150. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23151. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23152. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23153. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23154. if (faceVertices.length === 0) {
  23155. continue;
  23156. }
  23157. // Add UVs and get back to world
  23158. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23159. var vertex = faceVertices[vIndex];
  23160. //TODO check for Int32Array
  23161. vertexData.indices.push(currentVertexDataIndex);
  23162. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23163. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23164. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23165. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23166. currentVertexDataIndex++;
  23167. }
  23168. }
  23169. // Return mesh
  23170. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23171. vertexData.applyToMesh(decal);
  23172. decal.position = position.clone();
  23173. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23174. return decal;
  23175. };
  23176. // Privates
  23177. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23178. // extrusion geometry
  23179. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23180. var tangents = path3D.getTangents();
  23181. var normals = path3D.getNormals();
  23182. var binormals = path3D.getBinormals();
  23183. var distances = path3D.getDistances();
  23184. var angle = 0;
  23185. var returnScale = function () { return scale; };
  23186. var returnRotation = function () { return rotation; };
  23187. var rotate = custom ? rotateFunction : returnRotation;
  23188. var scl = custom ? scaleFunction : returnScale;
  23189. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23190. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23191. for (var i = 0; i < curve.length; i++) {
  23192. var shapePath = new Array();
  23193. var angleStep = rotate(i, distances[i]);
  23194. var scaleRatio = scl(i, distances[i]);
  23195. for (var p = 0; p < shape.length; p++) {
  23196. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23197. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23198. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23199. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23200. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23201. shapePath[p] = rotated;
  23202. }
  23203. shapePaths[index] = shapePath;
  23204. angle += angleStep;
  23205. index++;
  23206. }
  23207. // cap
  23208. var capPath = function (shapePath) {
  23209. var pointCap = Array();
  23210. var barycenter = BABYLON.Vector3.Zero();
  23211. var i;
  23212. for (i = 0; i < shapePath.length; i++) {
  23213. barycenter.addInPlace(shapePath[i]);
  23214. }
  23215. barycenter.scaleInPlace(1 / shapePath.length);
  23216. for (i = 0; i < shapePath.length; i++) {
  23217. pointCap.push(barycenter);
  23218. }
  23219. return pointCap;
  23220. };
  23221. switch (cap) {
  23222. case BABYLON.Mesh.NO_CAP:
  23223. break;
  23224. case BABYLON.Mesh.CAP_START:
  23225. shapePaths[0] = capPath(shapePaths[2]);
  23226. shapePaths[1] = shapePaths[2].slice(0);
  23227. break;
  23228. case BABYLON.Mesh.CAP_END:
  23229. shapePaths[index] = shapePaths[index - 1];
  23230. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23231. break;
  23232. case BABYLON.Mesh.CAP_ALL:
  23233. shapePaths[0] = capPath(shapePaths[2]);
  23234. shapePaths[1] = shapePaths[2].slice(0);
  23235. shapePaths[index] = shapePaths[index - 1];
  23236. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23237. break;
  23238. default:
  23239. break;
  23240. }
  23241. return shapePaths;
  23242. };
  23243. var path3D;
  23244. var pathArray;
  23245. if (instance) {
  23246. path3D = (instance.path3D).update(curve);
  23247. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23248. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23249. return instance;
  23250. }
  23251. // extruded shape creation
  23252. path3D = new BABYLON.Path3D(curve);
  23253. var newShapePaths = new Array();
  23254. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23255. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23256. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23257. extrudedGeneric.pathArray = pathArray;
  23258. extrudedGeneric.path3D = path3D;
  23259. extrudedGeneric.cap = cap;
  23260. return extrudedGeneric;
  23261. };
  23262. return MeshBuilder;
  23263. }());
  23264. BABYLON.MeshBuilder = MeshBuilder;
  23265. })(BABYLON || (BABYLON = {}));
  23266. //# sourceMappingURL=babylon.meshBuilder.js.map
  23267. var BABYLON;
  23268. (function (BABYLON) {
  23269. var BaseTexture = (function () {
  23270. function BaseTexture(scene) {
  23271. this.hasAlpha = false;
  23272. this.getAlphaFromRGB = false;
  23273. this.level = 1;
  23274. this.coordinatesIndex = 0;
  23275. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23276. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23277. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23278. this.anisotropicFilteringLevel = 4;
  23279. this.isCube = false;
  23280. this.isRenderTarget = false;
  23281. this.animations = new Array();
  23282. /**
  23283. * An event triggered when the texture is disposed.
  23284. * @type {BABYLON.Observable}
  23285. */
  23286. this.onDisposeObservable = new BABYLON.Observable();
  23287. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23288. this._scene = scene;
  23289. this._scene.textures.push(this);
  23290. this._uid = null;
  23291. }
  23292. Object.defineProperty(BaseTexture.prototype, "uid", {
  23293. get: function () {
  23294. if (!this._uid) {
  23295. this._uid = BABYLON.Tools.RandomId();
  23296. }
  23297. return this._uid;
  23298. },
  23299. enumerable: true,
  23300. configurable: true
  23301. });
  23302. BaseTexture.prototype.toString = function () {
  23303. return this.name;
  23304. };
  23305. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23306. set: function (callback) {
  23307. if (this._onDisposeObserver) {
  23308. this.onDisposeObservable.remove(this._onDisposeObserver);
  23309. }
  23310. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23311. },
  23312. enumerable: true,
  23313. configurable: true
  23314. });
  23315. BaseTexture.prototype.getScene = function () {
  23316. return this._scene;
  23317. };
  23318. BaseTexture.prototype.getTextureMatrix = function () {
  23319. return null;
  23320. };
  23321. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23322. return null;
  23323. };
  23324. BaseTexture.prototype.getInternalTexture = function () {
  23325. return this._texture;
  23326. };
  23327. BaseTexture.prototype.isReady = function () {
  23328. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23329. return true;
  23330. }
  23331. if (this._texture) {
  23332. return this._texture.isReady;
  23333. }
  23334. return false;
  23335. };
  23336. BaseTexture.prototype.getSize = function () {
  23337. if (this._texture._width) {
  23338. return new BABYLON.Size(this._texture._width, this._texture._height);
  23339. }
  23340. if (this._texture._size) {
  23341. return new BABYLON.Size(this._texture._size, this._texture._size);
  23342. }
  23343. return BABYLON.Size.Zero();
  23344. };
  23345. BaseTexture.prototype.getBaseSize = function () {
  23346. if (!this.isReady() || !this._texture)
  23347. return BABYLON.Size.Zero();
  23348. if (this._texture._size) {
  23349. return new BABYLON.Size(this._texture._size, this._texture._size);
  23350. }
  23351. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  23352. };
  23353. BaseTexture.prototype.scale = function (ratio) {
  23354. };
  23355. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23356. get: function () {
  23357. return false;
  23358. },
  23359. enumerable: true,
  23360. configurable: true
  23361. });
  23362. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  23363. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23364. for (var index = 0; index < texturesCache.length; index++) {
  23365. var texturesCacheEntry = texturesCache[index];
  23366. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23367. texturesCache.splice(index, 1);
  23368. return;
  23369. }
  23370. }
  23371. };
  23372. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23373. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23374. for (var index = 0; index < texturesCache.length; index++) {
  23375. var texturesCacheEntry = texturesCache[index];
  23376. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23377. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23378. texturesCacheEntry.references++;
  23379. return texturesCacheEntry;
  23380. }
  23381. }
  23382. }
  23383. return null;
  23384. };
  23385. BaseTexture.prototype.delayLoad = function () {
  23386. };
  23387. BaseTexture.prototype.clone = function () {
  23388. return null;
  23389. };
  23390. BaseTexture.prototype.releaseInternalTexture = function () {
  23391. if (this._texture) {
  23392. this._scene.getEngine().releaseInternalTexture(this._texture);
  23393. delete this._texture;
  23394. }
  23395. };
  23396. BaseTexture.prototype.dispose = function () {
  23397. // Animations
  23398. this.getScene().stopAnimation(this);
  23399. // Remove from scene
  23400. var index = this._scene.textures.indexOf(this);
  23401. if (index >= 0) {
  23402. this._scene.textures.splice(index, 1);
  23403. }
  23404. if (this._texture === undefined) {
  23405. return;
  23406. }
  23407. // Release
  23408. this.releaseInternalTexture();
  23409. // Callback
  23410. this.onDisposeObservable.notifyObservers(this);
  23411. this.onDisposeObservable.clear();
  23412. };
  23413. BaseTexture.prototype.serialize = function () {
  23414. if (!this.name) {
  23415. return null;
  23416. }
  23417. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23418. // Animations
  23419. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23420. return serializationObject;
  23421. };
  23422. __decorate([
  23423. BABYLON.serialize()
  23424. ], BaseTexture.prototype, "name", void 0);
  23425. __decorate([
  23426. BABYLON.serialize()
  23427. ], BaseTexture.prototype, "hasAlpha", void 0);
  23428. __decorate([
  23429. BABYLON.serialize()
  23430. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23431. __decorate([
  23432. BABYLON.serialize()
  23433. ], BaseTexture.prototype, "level", void 0);
  23434. __decorate([
  23435. BABYLON.serialize()
  23436. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23437. __decorate([
  23438. BABYLON.serialize()
  23439. ], BaseTexture.prototype, "coordinatesMode", void 0);
  23440. __decorate([
  23441. BABYLON.serialize()
  23442. ], BaseTexture.prototype, "wrapU", void 0);
  23443. __decorate([
  23444. BABYLON.serialize()
  23445. ], BaseTexture.prototype, "wrapV", void 0);
  23446. __decorate([
  23447. BABYLON.serialize()
  23448. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23449. __decorate([
  23450. BABYLON.serialize()
  23451. ], BaseTexture.prototype, "isCube", void 0);
  23452. __decorate([
  23453. BABYLON.serialize()
  23454. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23455. return BaseTexture;
  23456. }());
  23457. BABYLON.BaseTexture = BaseTexture;
  23458. })(BABYLON || (BABYLON = {}));
  23459. //# sourceMappingURL=babylon.baseTexture.js.map
  23460. var BABYLON;
  23461. (function (BABYLON) {
  23462. var Texture = (function (_super) {
  23463. __extends(Texture, _super);
  23464. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  23465. var _this = this;
  23466. if (noMipmap === void 0) { noMipmap = false; }
  23467. if (invertY === void 0) { invertY = true; }
  23468. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23469. if (onLoad === void 0) { onLoad = null; }
  23470. if (onError === void 0) { onError = null; }
  23471. if (buffer === void 0) { buffer = null; }
  23472. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23473. _super.call(this, scene);
  23474. this.uOffset = 0;
  23475. this.vOffset = 0;
  23476. this.uScale = 1.0;
  23477. this.vScale = 1.0;
  23478. this.uAng = 0;
  23479. this.vAng = 0;
  23480. this.wAng = 0;
  23481. this.name = url;
  23482. this.url = url;
  23483. this._noMipmap = noMipmap;
  23484. this._invertY = invertY;
  23485. this._samplingMode = samplingMode;
  23486. this._buffer = buffer;
  23487. this._deleteBuffer = deleteBuffer;
  23488. if (!url) {
  23489. return;
  23490. }
  23491. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  23492. var load = function () {
  23493. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23494. _this.onLoadObservable.notifyObservers(true);
  23495. }
  23496. if (onLoad) {
  23497. onLoad();
  23498. }
  23499. };
  23500. if (!this._texture) {
  23501. if (!scene.useDelayedTextureLoading) {
  23502. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  23503. if (deleteBuffer) {
  23504. delete this._buffer;
  23505. }
  23506. }
  23507. else {
  23508. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23509. this._delayedOnLoad = load;
  23510. this._delayedOnError = onError;
  23511. }
  23512. }
  23513. else {
  23514. if (this._texture.isReady) {
  23515. BABYLON.Tools.SetImmediate(function () { return load(); });
  23516. }
  23517. else {
  23518. this._texture.onLoadedCallbacks.push(load);
  23519. }
  23520. }
  23521. }
  23522. Object.defineProperty(Texture.prototype, "noMipmap", {
  23523. get: function () {
  23524. return this._noMipmap;
  23525. },
  23526. enumerable: true,
  23527. configurable: true
  23528. });
  23529. Texture.prototype.delayLoad = function () {
  23530. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23531. return;
  23532. }
  23533. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23534. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23535. if (!this._texture) {
  23536. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23537. if (this._deleteBuffer) {
  23538. delete this._buffer;
  23539. }
  23540. }
  23541. };
  23542. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23543. if (!this._texture) {
  23544. return;
  23545. }
  23546. this._samplingMode = samplingMode;
  23547. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23548. };
  23549. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23550. x *= this.uScale;
  23551. y *= this.vScale;
  23552. x -= 0.5 * this.uScale;
  23553. y -= 0.5 * this.vScale;
  23554. z -= 0.5;
  23555. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23556. t.x += 0.5 * this.uScale + this.uOffset;
  23557. t.y += 0.5 * this.vScale + this.vOffset;
  23558. t.z += 0.5;
  23559. };
  23560. Texture.prototype.getTextureMatrix = function () {
  23561. if (this.uOffset === this._cachedUOffset &&
  23562. this.vOffset === this._cachedVOffset &&
  23563. this.uScale === this._cachedUScale &&
  23564. this.vScale === this._cachedVScale &&
  23565. this.uAng === this._cachedUAng &&
  23566. this.vAng === this._cachedVAng &&
  23567. this.wAng === this._cachedWAng) {
  23568. return this._cachedTextureMatrix;
  23569. }
  23570. this._cachedUOffset = this.uOffset;
  23571. this._cachedVOffset = this.vOffset;
  23572. this._cachedUScale = this.uScale;
  23573. this._cachedVScale = this.vScale;
  23574. this._cachedUAng = this.uAng;
  23575. this._cachedVAng = this.vAng;
  23576. this._cachedWAng = this.wAng;
  23577. if (!this._cachedTextureMatrix) {
  23578. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23579. this._rowGenerationMatrix = new BABYLON.Matrix();
  23580. this._t0 = BABYLON.Vector3.Zero();
  23581. this._t1 = BABYLON.Vector3.Zero();
  23582. this._t2 = BABYLON.Vector3.Zero();
  23583. }
  23584. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23585. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23586. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23587. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23588. this._t1.subtractInPlace(this._t0);
  23589. this._t2.subtractInPlace(this._t0);
  23590. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23591. this._cachedTextureMatrix.m[0] = this._t1.x;
  23592. this._cachedTextureMatrix.m[1] = this._t1.y;
  23593. this._cachedTextureMatrix.m[2] = this._t1.z;
  23594. this._cachedTextureMatrix.m[4] = this._t2.x;
  23595. this._cachedTextureMatrix.m[5] = this._t2.y;
  23596. this._cachedTextureMatrix.m[6] = this._t2.z;
  23597. this._cachedTextureMatrix.m[8] = this._t0.x;
  23598. this._cachedTextureMatrix.m[9] = this._t0.y;
  23599. this._cachedTextureMatrix.m[10] = this._t0.z;
  23600. return this._cachedTextureMatrix;
  23601. };
  23602. Texture.prototype.getReflectionTextureMatrix = function () {
  23603. if (this.uOffset === this._cachedUOffset &&
  23604. this.vOffset === this._cachedVOffset &&
  23605. this.uScale === this._cachedUScale &&
  23606. this.vScale === this._cachedVScale &&
  23607. this.coordinatesMode === this._cachedCoordinatesMode) {
  23608. return this._cachedTextureMatrix;
  23609. }
  23610. if (!this._cachedTextureMatrix) {
  23611. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23612. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23613. }
  23614. this._cachedCoordinatesMode = this.coordinatesMode;
  23615. switch (this.coordinatesMode) {
  23616. case Texture.PLANAR_MODE:
  23617. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23618. this._cachedTextureMatrix[0] = this.uScale;
  23619. this._cachedTextureMatrix[5] = this.vScale;
  23620. this._cachedTextureMatrix[12] = this.uOffset;
  23621. this._cachedTextureMatrix[13] = this.vOffset;
  23622. break;
  23623. case Texture.PROJECTION_MODE:
  23624. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23625. this._projectionModeMatrix.m[0] = 0.5;
  23626. this._projectionModeMatrix.m[5] = -0.5;
  23627. this._projectionModeMatrix.m[10] = 0.0;
  23628. this._projectionModeMatrix.m[12] = 0.5;
  23629. this._projectionModeMatrix.m[13] = 0.5;
  23630. this._projectionModeMatrix.m[14] = 1.0;
  23631. this._projectionModeMatrix.m[15] = 1.0;
  23632. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23633. break;
  23634. default:
  23635. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23636. break;
  23637. }
  23638. return this._cachedTextureMatrix;
  23639. };
  23640. Texture.prototype.clone = function () {
  23641. var _this = this;
  23642. return BABYLON.SerializationHelper.Clone(function () {
  23643. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23644. }, this);
  23645. };
  23646. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23647. get: function () {
  23648. if (!this._onLoadObservarble) {
  23649. this._onLoadObservarble = new BABYLON.Observable();
  23650. }
  23651. return this._onLoadObservarble;
  23652. },
  23653. enumerable: true,
  23654. configurable: true
  23655. });
  23656. // Statics
  23657. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23658. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23659. if (onLoad === void 0) { onLoad = null; }
  23660. if (onError === void 0) { onError = null; }
  23661. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23662. };
  23663. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23664. if (parsedTexture.customType) {
  23665. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23666. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23667. }
  23668. if (parsedTexture.isCube) {
  23669. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23670. }
  23671. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23672. return null;
  23673. }
  23674. var texture = BABYLON.SerializationHelper.Parse(function () {
  23675. if (parsedTexture.mirrorPlane) {
  23676. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23677. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23678. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23679. return mirrorTexture;
  23680. }
  23681. else if (parsedTexture.isRenderTarget) {
  23682. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23683. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23684. return renderTargetTexture;
  23685. }
  23686. else {
  23687. var texture;
  23688. if (parsedTexture.base64String) {
  23689. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23690. }
  23691. else {
  23692. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23693. }
  23694. return texture;
  23695. }
  23696. }, parsedTexture, scene);
  23697. // Animations
  23698. if (parsedTexture.animations) {
  23699. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23700. var parsedAnimation = parsedTexture.animations[animationIndex];
  23701. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23702. }
  23703. }
  23704. return texture;
  23705. };
  23706. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  23707. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23708. if (noMipmap === void 0) { noMipmap = false; }
  23709. if (invertY === void 0) { invertY = true; }
  23710. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23711. if (onLoad === void 0) { onLoad = null; }
  23712. if (onError === void 0) { onError = null; }
  23713. if (name.substr(0, 5) !== "data:") {
  23714. name = "data:" + name;
  23715. }
  23716. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  23717. };
  23718. // Constants
  23719. Texture.NEAREST_SAMPLINGMODE = 1;
  23720. Texture.BILINEAR_SAMPLINGMODE = 2;
  23721. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23722. Texture.EXPLICIT_MODE = 0;
  23723. Texture.SPHERICAL_MODE = 1;
  23724. Texture.PLANAR_MODE = 2;
  23725. Texture.CUBIC_MODE = 3;
  23726. Texture.PROJECTION_MODE = 4;
  23727. Texture.SKYBOX_MODE = 5;
  23728. Texture.INVCUBIC_MODE = 6;
  23729. Texture.EQUIRECTANGULAR_MODE = 7;
  23730. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23731. Texture.CLAMP_ADDRESSMODE = 0;
  23732. Texture.WRAP_ADDRESSMODE = 1;
  23733. Texture.MIRROR_ADDRESSMODE = 2;
  23734. __decorate([
  23735. BABYLON.serialize()
  23736. ], Texture.prototype, "url", void 0);
  23737. __decorate([
  23738. BABYLON.serialize()
  23739. ], Texture.prototype, "uOffset", void 0);
  23740. __decorate([
  23741. BABYLON.serialize()
  23742. ], Texture.prototype, "vOffset", void 0);
  23743. __decorate([
  23744. BABYLON.serialize()
  23745. ], Texture.prototype, "uScale", void 0);
  23746. __decorate([
  23747. BABYLON.serialize()
  23748. ], Texture.prototype, "vScale", void 0);
  23749. __decorate([
  23750. BABYLON.serialize()
  23751. ], Texture.prototype, "uAng", void 0);
  23752. __decorate([
  23753. BABYLON.serialize()
  23754. ], Texture.prototype, "vAng", void 0);
  23755. __decorate([
  23756. BABYLON.serialize()
  23757. ], Texture.prototype, "wAng", void 0);
  23758. return Texture;
  23759. }(BABYLON.BaseTexture));
  23760. BABYLON.Texture = Texture;
  23761. })(BABYLON || (BABYLON = {}));
  23762. //# sourceMappingURL=babylon.texture.js.map
  23763. var BABYLON;
  23764. (function (BABYLON) {
  23765. var CubeTexture = (function (_super) {
  23766. __extends(CubeTexture, _super);
  23767. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23768. if (onLoad === void 0) { onLoad = null; }
  23769. if (onError === void 0) { onError = null; }
  23770. _super.call(this, scene);
  23771. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23772. this.name = rootUrl;
  23773. this.url = rootUrl;
  23774. this._noMipmap = noMipmap;
  23775. this.hasAlpha = false;
  23776. if (!rootUrl && !files) {
  23777. return;
  23778. }
  23779. this._texture = this._getFromCache(rootUrl, noMipmap);
  23780. if (!files) {
  23781. if (!extensions) {
  23782. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23783. }
  23784. files = [];
  23785. for (var index = 0; index < extensions.length; index++) {
  23786. files.push(rootUrl + extensions[index]);
  23787. }
  23788. this._extensions = extensions;
  23789. }
  23790. this._files = files;
  23791. if (!this._texture) {
  23792. if (!scene.useDelayedTextureLoading) {
  23793. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23794. }
  23795. else {
  23796. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23797. }
  23798. }
  23799. else if (onLoad) {
  23800. if (this._texture.isReady) {
  23801. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23802. }
  23803. else {
  23804. this._texture.onLoadedCallbacks.push(onLoad);
  23805. }
  23806. }
  23807. this.isCube = true;
  23808. this._textureMatrix = BABYLON.Matrix.Identity();
  23809. }
  23810. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23811. return new CubeTexture("", scene, null, noMipmap, files);
  23812. };
  23813. // Methods
  23814. CubeTexture.prototype.delayLoad = function () {
  23815. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23816. return;
  23817. }
  23818. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23819. this._texture = this._getFromCache(this.url, this._noMipmap);
  23820. if (!this._texture) {
  23821. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23822. }
  23823. };
  23824. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23825. return this._textureMatrix;
  23826. };
  23827. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23828. var texture = BABYLON.SerializationHelper.Parse(function () {
  23829. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23830. }, parsedTexture, scene);
  23831. // Animations
  23832. if (parsedTexture.animations) {
  23833. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23834. var parsedAnimation = parsedTexture.animations[animationIndex];
  23835. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23836. }
  23837. }
  23838. return texture;
  23839. };
  23840. CubeTexture.prototype.clone = function () {
  23841. var _this = this;
  23842. return BABYLON.SerializationHelper.Clone(function () {
  23843. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23844. }, this);
  23845. };
  23846. return CubeTexture;
  23847. }(BABYLON.BaseTexture));
  23848. BABYLON.CubeTexture = CubeTexture;
  23849. })(BABYLON || (BABYLON = {}));
  23850. //# sourceMappingURL=babylon.cubeTexture.js.map
  23851. var BABYLON;
  23852. (function (BABYLON) {
  23853. var RenderTargetTexture = (function (_super) {
  23854. __extends(RenderTargetTexture, _super);
  23855. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23856. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23857. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23858. if (isCube === void 0) { isCube = false; }
  23859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23860. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23861. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23862. _super.call(this, null, scene, !generateMipMaps);
  23863. this.isCube = isCube;
  23864. /**
  23865. * Use this list to define the list of mesh you want to render.
  23866. */
  23867. this.renderList = new Array();
  23868. this.renderParticles = true;
  23869. this.renderSprites = false;
  23870. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23871. // Events
  23872. /**
  23873. * An event triggered when the texture is unbind.
  23874. * @type {BABYLON.Observable}
  23875. */
  23876. this.onAfterUnbindObservable = new BABYLON.Observable();
  23877. /**
  23878. * An event triggered before rendering the texture
  23879. * @type {BABYLON.Observable}
  23880. */
  23881. this.onBeforeRenderObservable = new BABYLON.Observable();
  23882. /**
  23883. * An event triggered after rendering the texture
  23884. * @type {BABYLON.Observable}
  23885. */
  23886. this.onAfterRenderObservable = new BABYLON.Observable();
  23887. /**
  23888. * An event triggered after the texture clear
  23889. * @type {BABYLON.Observable}
  23890. */
  23891. this.onClearObservable = new BABYLON.Observable();
  23892. this._currentRefreshId = -1;
  23893. this._refreshRate = 1;
  23894. this.name = name;
  23895. this.isRenderTarget = true;
  23896. this._size = size;
  23897. this._generateMipMaps = generateMipMaps;
  23898. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23899. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23900. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23901. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23902. }
  23903. if (isCube) {
  23904. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23905. generateMipMaps: generateMipMaps,
  23906. samplingMode: samplingMode,
  23907. generateDepthBuffer: generateDepthBuffer,
  23908. generateStencilBuffer: generateStencilBuffer
  23909. });
  23910. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23911. this._textureMatrix = BABYLON.Matrix.Identity();
  23912. }
  23913. else {
  23914. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23915. generateMipMaps: generateMipMaps,
  23916. type: type,
  23917. samplingMode: samplingMode,
  23918. generateDepthBuffer: generateDepthBuffer,
  23919. generateStencilBuffer: generateStencilBuffer
  23920. });
  23921. }
  23922. // Rendering groups
  23923. this._renderingManager = new BABYLON.RenderingManager(scene);
  23924. }
  23925. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23926. get: function () {
  23927. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23928. },
  23929. enumerable: true,
  23930. configurable: true
  23931. });
  23932. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23933. get: function () {
  23934. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23935. },
  23936. enumerable: true,
  23937. configurable: true
  23938. });
  23939. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23940. get: function () {
  23941. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23942. },
  23943. enumerable: true,
  23944. configurable: true
  23945. });
  23946. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23947. set: function (callback) {
  23948. if (this._onAfterUnbindObserver) {
  23949. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23950. }
  23951. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23952. },
  23953. enumerable: true,
  23954. configurable: true
  23955. });
  23956. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23957. set: function (callback) {
  23958. if (this._onBeforeRenderObserver) {
  23959. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23960. }
  23961. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23962. },
  23963. enumerable: true,
  23964. configurable: true
  23965. });
  23966. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23967. set: function (callback) {
  23968. if (this._onAfterRenderObserver) {
  23969. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23970. }
  23971. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23972. },
  23973. enumerable: true,
  23974. configurable: true
  23975. });
  23976. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23977. set: function (callback) {
  23978. if (this._onClearObserver) {
  23979. this.onClearObservable.remove(this._onClearObserver);
  23980. }
  23981. this._onClearObserver = this.onClearObservable.add(callback);
  23982. },
  23983. enumerable: true,
  23984. configurable: true
  23985. });
  23986. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23987. this._currentRefreshId = -1;
  23988. };
  23989. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23990. get: function () {
  23991. return this._refreshRate;
  23992. },
  23993. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23994. set: function (value) {
  23995. this._refreshRate = value;
  23996. this.resetRefreshCounter();
  23997. },
  23998. enumerable: true,
  23999. configurable: true
  24000. });
  24001. RenderTargetTexture.prototype._shouldRender = function () {
  24002. if (this._currentRefreshId === -1) {
  24003. this._currentRefreshId = 1;
  24004. return true;
  24005. }
  24006. if (this.refreshRate === this._currentRefreshId) {
  24007. this._currentRefreshId = 1;
  24008. return true;
  24009. }
  24010. this._currentRefreshId++;
  24011. return false;
  24012. };
  24013. RenderTargetTexture.prototype.isReady = function () {
  24014. if (!this.getScene().renderTargetsEnabled) {
  24015. return false;
  24016. }
  24017. return _super.prototype.isReady.call(this);
  24018. };
  24019. RenderTargetTexture.prototype.getRenderSize = function () {
  24020. return this._size;
  24021. };
  24022. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24023. get: function () {
  24024. return true;
  24025. },
  24026. enumerable: true,
  24027. configurable: true
  24028. });
  24029. RenderTargetTexture.prototype.scale = function (ratio) {
  24030. var newSize = this._size * ratio;
  24031. this.resize(newSize, this._generateMipMaps);
  24032. };
  24033. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24034. if (this.isCube) {
  24035. return this._textureMatrix;
  24036. }
  24037. return _super.prototype.getReflectionTextureMatrix.call(this);
  24038. };
  24039. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  24040. this.releaseInternalTexture();
  24041. if (this.isCube) {
  24042. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  24043. }
  24044. else {
  24045. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24046. }
  24047. };
  24048. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24049. var scene = this.getScene();
  24050. var engine = scene.getEngine();
  24051. if (this.useCameraPostProcesses !== undefined) {
  24052. useCameraPostProcess = this.useCameraPostProcesses;
  24053. }
  24054. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24055. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24056. }
  24057. else {
  24058. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24059. }
  24060. if (this._waitingRenderList) {
  24061. this.renderList = [];
  24062. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24063. var id = this._waitingRenderList[index];
  24064. this.renderList.push(scene.getMeshByID(id));
  24065. }
  24066. delete this._waitingRenderList;
  24067. }
  24068. // Is predicate defined?
  24069. if (this.renderListPredicate) {
  24070. this.renderList.splice(0); // Clear previous renderList
  24071. var sceneMeshes = this.getScene().meshes;
  24072. for (var index = 0; index < sceneMeshes.length; index++) {
  24073. var mesh = sceneMeshes[index];
  24074. if (this.renderListPredicate(mesh)) {
  24075. this.renderList.push(mesh);
  24076. }
  24077. }
  24078. }
  24079. if (this.renderList && this.renderList.length === 0) {
  24080. return;
  24081. }
  24082. // Prepare renderingManager
  24083. this._renderingManager.reset();
  24084. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24085. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24086. var sceneRenderId = scene.getRenderId();
  24087. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24088. var mesh = currentRenderList[meshIndex];
  24089. if (mesh) {
  24090. if (!mesh.isReady()) {
  24091. // Reset _currentRefreshId
  24092. this.resetRefreshCounter();
  24093. continue;
  24094. }
  24095. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24096. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24097. mesh._activate(sceneRenderId);
  24098. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24099. var subMesh = mesh.subMeshes[subIndex];
  24100. scene._activeIndices.addCount(subMesh.indexCount, false);
  24101. this._renderingManager.dispatch(subMesh);
  24102. }
  24103. }
  24104. }
  24105. }
  24106. if (this.isCube) {
  24107. for (var face = 0; face < 6; face++) {
  24108. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24109. scene.incrementRenderId();
  24110. scene.resetCachedMaterial();
  24111. }
  24112. }
  24113. else {
  24114. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24115. }
  24116. this.onAfterUnbindObservable.notifyObservers(this);
  24117. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24118. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24119. }
  24120. engine.setViewport(scene.activeCamera.viewport);
  24121. scene.resetCachedMaterial();
  24122. };
  24123. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24124. var scene = this.getScene();
  24125. var engine = scene.getEngine();
  24126. // Bind
  24127. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24128. if (this.isCube) {
  24129. engine.bindFramebuffer(this._texture, faceIndex);
  24130. }
  24131. else {
  24132. engine.bindFramebuffer(this._texture);
  24133. }
  24134. }
  24135. if (this.activeCamera) {
  24136. engine.setViewport(this.activeCamera.viewport);
  24137. }
  24138. else {
  24139. engine.setViewport(scene.activeCamera.viewport);
  24140. }
  24141. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24142. // Clear
  24143. if (this.onClearObservable.hasObservers()) {
  24144. this.onClearObservable.notifyObservers(engine);
  24145. }
  24146. else {
  24147. engine.clear(scene.clearColor, true, true, true);
  24148. }
  24149. if (!this._doNotChangeAspectRatio) {
  24150. scene.updateTransformMatrix(true);
  24151. }
  24152. // Render
  24153. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24154. if (useCameraPostProcess) {
  24155. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24156. }
  24157. if (!this._doNotChangeAspectRatio) {
  24158. scene.updateTransformMatrix(true);
  24159. }
  24160. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24161. // Dump ?
  24162. if (dumpForDebug) {
  24163. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24164. }
  24165. // Unbind
  24166. if (!this.isCube || faceIndex === 5) {
  24167. if (this.isCube) {
  24168. if (faceIndex === 5) {
  24169. engine.generateMipMapsForCubemap(this._texture);
  24170. }
  24171. }
  24172. engine.unBindFramebuffer(this._texture, this.isCube);
  24173. }
  24174. };
  24175. /**
  24176. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24177. * This allowed control for front to back rendering or reversly depending of the special needs.
  24178. *
  24179. * @param renderingGroupId The rendering group id corresponding to its index
  24180. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24181. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24182. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24183. */
  24184. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24185. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24186. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24187. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24188. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24189. };
  24190. /**
  24191. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24192. *
  24193. * @param renderingGroupId The rendering group id corresponding to its index
  24194. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24195. */
  24196. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24197. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24198. };
  24199. RenderTargetTexture.prototype.clone = function () {
  24200. var textureSize = this.getSize();
  24201. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24202. // Base texture
  24203. newTexture.hasAlpha = this.hasAlpha;
  24204. newTexture.level = this.level;
  24205. // RenderTarget Texture
  24206. newTexture.coordinatesMode = this.coordinatesMode;
  24207. newTexture.renderList = this.renderList.slice(0);
  24208. return newTexture;
  24209. };
  24210. RenderTargetTexture.prototype.serialize = function () {
  24211. if (!this.name) {
  24212. return null;
  24213. }
  24214. var serializationObject = _super.prototype.serialize.call(this);
  24215. serializationObject.renderTargetSize = this.getRenderSize();
  24216. serializationObject.renderList = [];
  24217. for (var index = 0; index < this.renderList.length; index++) {
  24218. serializationObject.renderList.push(this.renderList[index].id);
  24219. }
  24220. return serializationObject;
  24221. };
  24222. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24223. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24224. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24225. return RenderTargetTexture;
  24226. }(BABYLON.Texture));
  24227. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24228. })(BABYLON || (BABYLON = {}));
  24229. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  24230. var BABYLON;
  24231. (function (BABYLON) {
  24232. var ProceduralTexture = (function (_super) {
  24233. __extends(ProceduralTexture, _super);
  24234. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24235. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24236. if (isCube === void 0) { isCube = false; }
  24237. _super.call(this, null, scene, !generateMipMaps);
  24238. this.isCube = isCube;
  24239. this.isEnabled = true;
  24240. this._currentRefreshId = -1;
  24241. this._refreshRate = 1;
  24242. this._vertexBuffers = {};
  24243. this._uniforms = new Array();
  24244. this._samplers = new Array();
  24245. this._textures = new Array();
  24246. this._floats = new Array();
  24247. this._floatsArrays = {};
  24248. this._colors3 = new Array();
  24249. this._colors4 = new Array();
  24250. this._vectors2 = new Array();
  24251. this._vectors3 = new Array();
  24252. this._matrices = new Array();
  24253. this._fallbackTextureUsed = false;
  24254. scene._proceduralTextures.push(this);
  24255. this.name = name;
  24256. this.isRenderTarget = true;
  24257. this._size = size;
  24258. this._generateMipMaps = generateMipMaps;
  24259. this.setFragment(fragment);
  24260. this._fallbackTexture = fallbackTexture;
  24261. var engine = scene.getEngine();
  24262. if (isCube) {
  24263. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24264. this.setFloat("face", 0);
  24265. }
  24266. else {
  24267. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24268. }
  24269. // VBO
  24270. var vertices = [];
  24271. vertices.push(1, 1);
  24272. vertices.push(-1, 1);
  24273. vertices.push(-1, -1);
  24274. vertices.push(1, -1);
  24275. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24276. // Indices
  24277. var indices = [];
  24278. indices.push(0);
  24279. indices.push(1);
  24280. indices.push(2);
  24281. indices.push(0);
  24282. indices.push(2);
  24283. indices.push(3);
  24284. this._indexBuffer = engine.createIndexBuffer(indices);
  24285. }
  24286. ProceduralTexture.prototype.reset = function () {
  24287. if (this._effect === undefined) {
  24288. return;
  24289. }
  24290. var engine = this.getScene().getEngine();
  24291. engine._releaseEffect(this._effect);
  24292. };
  24293. ProceduralTexture.prototype.isReady = function () {
  24294. var _this = this;
  24295. var engine = this.getScene().getEngine();
  24296. var shaders;
  24297. if (!this._fragment) {
  24298. return false;
  24299. }
  24300. if (this._fallbackTextureUsed) {
  24301. return true;
  24302. }
  24303. if (this._fragment.fragmentElement !== undefined) {
  24304. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24305. }
  24306. else {
  24307. shaders = { vertex: "procedural", fragment: this._fragment };
  24308. }
  24309. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24310. _this.releaseInternalTexture();
  24311. if (_this._fallbackTexture) {
  24312. _this._texture = _this._fallbackTexture._texture;
  24313. _this._texture.references++;
  24314. }
  24315. _this._fallbackTextureUsed = true;
  24316. });
  24317. return this._effect.isReady();
  24318. };
  24319. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24320. this._currentRefreshId = -1;
  24321. };
  24322. ProceduralTexture.prototype.setFragment = function (fragment) {
  24323. this._fragment = fragment;
  24324. };
  24325. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24326. get: function () {
  24327. return this._refreshRate;
  24328. },
  24329. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24330. set: function (value) {
  24331. this._refreshRate = value;
  24332. this.resetRefreshCounter();
  24333. },
  24334. enumerable: true,
  24335. configurable: true
  24336. });
  24337. ProceduralTexture.prototype._shouldRender = function () {
  24338. if (!this.isEnabled || !this.isReady() || !this._texture) {
  24339. return false;
  24340. }
  24341. if (this._fallbackTextureUsed) {
  24342. return false;
  24343. }
  24344. if (this._currentRefreshId === -1) {
  24345. this._currentRefreshId = 1;
  24346. return true;
  24347. }
  24348. if (this.refreshRate === this._currentRefreshId) {
  24349. this._currentRefreshId = 1;
  24350. return true;
  24351. }
  24352. this._currentRefreshId++;
  24353. return false;
  24354. };
  24355. ProceduralTexture.prototype.getRenderSize = function () {
  24356. return this._size;
  24357. };
  24358. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  24359. if (this._fallbackTextureUsed) {
  24360. return;
  24361. }
  24362. this.releaseInternalTexture();
  24363. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24364. };
  24365. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  24366. if (this._uniforms.indexOf(uniformName) === -1) {
  24367. this._uniforms.push(uniformName);
  24368. }
  24369. };
  24370. ProceduralTexture.prototype.setTexture = function (name, texture) {
  24371. if (this._samplers.indexOf(name) === -1) {
  24372. this._samplers.push(name);
  24373. }
  24374. this._textures[name] = texture;
  24375. return this;
  24376. };
  24377. ProceduralTexture.prototype.setFloat = function (name, value) {
  24378. this._checkUniform(name);
  24379. this._floats[name] = value;
  24380. return this;
  24381. };
  24382. ProceduralTexture.prototype.setFloats = function (name, value) {
  24383. this._checkUniform(name);
  24384. this._floatsArrays[name] = value;
  24385. return this;
  24386. };
  24387. ProceduralTexture.prototype.setColor3 = function (name, value) {
  24388. this._checkUniform(name);
  24389. this._colors3[name] = value;
  24390. return this;
  24391. };
  24392. ProceduralTexture.prototype.setColor4 = function (name, value) {
  24393. this._checkUniform(name);
  24394. this._colors4[name] = value;
  24395. return this;
  24396. };
  24397. ProceduralTexture.prototype.setVector2 = function (name, value) {
  24398. this._checkUniform(name);
  24399. this._vectors2[name] = value;
  24400. return this;
  24401. };
  24402. ProceduralTexture.prototype.setVector3 = function (name, value) {
  24403. this._checkUniform(name);
  24404. this._vectors3[name] = value;
  24405. return this;
  24406. };
  24407. ProceduralTexture.prototype.setMatrix = function (name, value) {
  24408. this._checkUniform(name);
  24409. this._matrices[name] = value;
  24410. return this;
  24411. };
  24412. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24413. var scene = this.getScene();
  24414. var engine = scene.getEngine();
  24415. // Render
  24416. engine.enableEffect(this._effect);
  24417. engine.setState(false);
  24418. // Texture
  24419. for (var name in this._textures) {
  24420. this._effect.setTexture(name, this._textures[name]);
  24421. }
  24422. // Float
  24423. for (name in this._floats) {
  24424. this._effect.setFloat(name, this._floats[name]);
  24425. }
  24426. // Floats
  24427. for (name in this._floatsArrays) {
  24428. this._effect.setArray(name, this._floatsArrays[name]);
  24429. }
  24430. // Color3
  24431. for (name in this._colors3) {
  24432. this._effect.setColor3(name, this._colors3[name]);
  24433. }
  24434. // Color4
  24435. for (name in this._colors4) {
  24436. var color = this._colors4[name];
  24437. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24438. }
  24439. // Vector2
  24440. for (name in this._vectors2) {
  24441. this._effect.setVector2(name, this._vectors2[name]);
  24442. }
  24443. // Vector3
  24444. for (name in this._vectors3) {
  24445. this._effect.setVector3(name, this._vectors3[name]);
  24446. }
  24447. // Matrix
  24448. for (name in this._matrices) {
  24449. this._effect.setMatrix(name, this._matrices[name]);
  24450. }
  24451. // VBOs
  24452. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  24453. if (this.isCube) {
  24454. for (var face = 0; face < 6; face++) {
  24455. engine.bindFramebuffer(this._texture, face);
  24456. this._effect.setFloat("face", face);
  24457. // Clear
  24458. engine.clear(scene.clearColor, true, true, true);
  24459. // Draw order
  24460. engine.draw(true, 0, 6);
  24461. // Mipmaps
  24462. if (face === 5) {
  24463. engine.generateMipMapsForCubemap(this._texture);
  24464. }
  24465. }
  24466. }
  24467. else {
  24468. engine.bindFramebuffer(this._texture);
  24469. // Clear
  24470. engine.clear(scene.clearColor, true, true, true);
  24471. // Draw order
  24472. engine.draw(true, 0, 6);
  24473. }
  24474. // Unbind
  24475. engine.unBindFramebuffer(this._texture, this.isCube);
  24476. if (this.onGenerated) {
  24477. this.onGenerated();
  24478. }
  24479. };
  24480. ProceduralTexture.prototype.clone = function () {
  24481. var textureSize = this.getSize();
  24482. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  24483. // Base texture
  24484. newTexture.hasAlpha = this.hasAlpha;
  24485. newTexture.level = this.level;
  24486. // RenderTarget Texture
  24487. newTexture.coordinatesMode = this.coordinatesMode;
  24488. return newTexture;
  24489. };
  24490. ProceduralTexture.prototype.dispose = function () {
  24491. var index = this.getScene()._proceduralTextures.indexOf(this);
  24492. if (index >= 0) {
  24493. this.getScene()._proceduralTextures.splice(index, 1);
  24494. }
  24495. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  24496. if (vertexBuffer) {
  24497. vertexBuffer.dispose();
  24498. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  24499. }
  24500. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  24501. this._indexBuffer = null;
  24502. }
  24503. _super.prototype.dispose.call(this);
  24504. };
  24505. return ProceduralTexture;
  24506. }(BABYLON.Texture));
  24507. BABYLON.ProceduralTexture = ProceduralTexture;
  24508. })(BABYLON || (BABYLON = {}));
  24509. //# sourceMappingURL=babylon.proceduralTexture.js.map
  24510. var BABYLON;
  24511. (function (BABYLON) {
  24512. var MirrorTexture = (function (_super) {
  24513. __extends(MirrorTexture, _super);
  24514. function MirrorTexture(name, size, scene, generateMipMaps) {
  24515. var _this = this;
  24516. _super.call(this, name, size, scene, generateMipMaps, true);
  24517. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24518. this._transformMatrix = BABYLON.Matrix.Zero();
  24519. this._mirrorMatrix = BABYLON.Matrix.Zero();
  24520. this.onBeforeRenderObservable.add(function () {
  24521. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24522. _this._savedViewMatrix = scene.getViewMatrix();
  24523. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24524. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24525. scene.clipPlane = _this.mirrorPlane;
  24526. scene.getEngine().cullBackFaces = false;
  24527. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24528. });
  24529. this.onAfterRenderObservable.add(function () {
  24530. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24531. scene.getEngine().cullBackFaces = true;
  24532. scene._mirroredCameraPosition = null;
  24533. delete scene.clipPlane;
  24534. });
  24535. }
  24536. MirrorTexture.prototype.clone = function () {
  24537. var textureSize = this.getSize();
  24538. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24539. // Base texture
  24540. newTexture.hasAlpha = this.hasAlpha;
  24541. newTexture.level = this.level;
  24542. // Mirror Texture
  24543. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24544. newTexture.renderList = this.renderList.slice(0);
  24545. return newTexture;
  24546. };
  24547. MirrorTexture.prototype.serialize = function () {
  24548. if (!this.name) {
  24549. return null;
  24550. }
  24551. var serializationObject = _super.prototype.serialize.call(this);
  24552. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24553. return serializationObject;
  24554. };
  24555. return MirrorTexture;
  24556. }(BABYLON.RenderTargetTexture));
  24557. BABYLON.MirrorTexture = MirrorTexture;
  24558. })(BABYLON || (BABYLON = {}));
  24559. //# sourceMappingURL=babylon.mirrorTexture.js.map
  24560. var BABYLON;
  24561. (function (BABYLON) {
  24562. /**
  24563. * Creates a refraction texture used by refraction channel of the standard material.
  24564. * @param name the texture name
  24565. * @param size size of the underlying texture
  24566. * @param scene root scene
  24567. */
  24568. var RefractionTexture = (function (_super) {
  24569. __extends(RefractionTexture, _super);
  24570. function RefractionTexture(name, size, scene, generateMipMaps) {
  24571. var _this = this;
  24572. _super.call(this, name, size, scene, generateMipMaps, true);
  24573. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24574. this.depth = 2.0;
  24575. this.onBeforeRenderObservable.add(function () {
  24576. scene.clipPlane = _this.refractionPlane;
  24577. });
  24578. this.onAfterRenderObservable.add(function () {
  24579. delete scene.clipPlane;
  24580. });
  24581. }
  24582. RefractionTexture.prototype.clone = function () {
  24583. var textureSize = this.getSize();
  24584. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24585. // Base texture
  24586. newTexture.hasAlpha = this.hasAlpha;
  24587. newTexture.level = this.level;
  24588. // Refraction Texture
  24589. newTexture.refractionPlane = this.refractionPlane.clone();
  24590. newTexture.renderList = this.renderList.slice(0);
  24591. newTexture.depth = this.depth;
  24592. return newTexture;
  24593. };
  24594. RefractionTexture.prototype.serialize = function () {
  24595. if (!this.name) {
  24596. return null;
  24597. }
  24598. var serializationObject = _super.prototype.serialize.call(this);
  24599. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24600. serializationObject.depth = this.depth;
  24601. return serializationObject;
  24602. };
  24603. return RefractionTexture;
  24604. }(BABYLON.RenderTargetTexture));
  24605. BABYLON.RefractionTexture = RefractionTexture;
  24606. })(BABYLON || (BABYLON = {}));
  24607. //# sourceMappingURL=babylon.refractionTexture.js.map
  24608. var BABYLON;
  24609. (function (BABYLON) {
  24610. var DynamicTexture = (function (_super) {
  24611. __extends(DynamicTexture, _super);
  24612. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24614. _super.call(this, null, scene, !generateMipMaps);
  24615. this.name = name;
  24616. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24617. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24618. this._generateMipMaps = generateMipMaps;
  24619. if (options.getContext) {
  24620. this._canvas = options;
  24621. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24622. }
  24623. else {
  24624. this._canvas = document.createElement("canvas");
  24625. if (options.width) {
  24626. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24627. }
  24628. else {
  24629. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24630. }
  24631. }
  24632. var textureSize = this.getSize();
  24633. this._canvas.width = textureSize.width;
  24634. this._canvas.height = textureSize.height;
  24635. this._context = this._canvas.getContext("2d");
  24636. }
  24637. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24638. get: function () {
  24639. return true;
  24640. },
  24641. enumerable: true,
  24642. configurable: true
  24643. });
  24644. DynamicTexture.prototype.scale = function (ratio) {
  24645. var textureSize = this.getSize();
  24646. textureSize.width *= ratio;
  24647. textureSize.height *= ratio;
  24648. this._canvas.width = textureSize.width;
  24649. this._canvas.height = textureSize.height;
  24650. this.releaseInternalTexture();
  24651. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24652. };
  24653. DynamicTexture.prototype.getContext = function () {
  24654. return this._context;
  24655. };
  24656. DynamicTexture.prototype.clear = function () {
  24657. var size = this.getSize();
  24658. this._context.fillRect(0, 0, size.width, size.height);
  24659. };
  24660. DynamicTexture.prototype.update = function (invertY) {
  24661. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24662. };
  24663. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24664. if (update === void 0) { update = true; }
  24665. var size = this.getSize();
  24666. if (clearColor) {
  24667. this._context.fillStyle = clearColor;
  24668. this._context.fillRect(0, 0, size.width, size.height);
  24669. }
  24670. this._context.font = font;
  24671. if (x === null) {
  24672. var textSize = this._context.measureText(text);
  24673. x = (size.width - textSize.width) / 2;
  24674. }
  24675. this._context.fillStyle = color;
  24676. this._context.fillText(text, x, y);
  24677. if (update) {
  24678. this.update(invertY);
  24679. }
  24680. };
  24681. DynamicTexture.prototype.clone = function () {
  24682. var textureSize = this.getSize();
  24683. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24684. // Base texture
  24685. newTexture.hasAlpha = this.hasAlpha;
  24686. newTexture.level = this.level;
  24687. // Dynamic Texture
  24688. newTexture.wrapU = this.wrapU;
  24689. newTexture.wrapV = this.wrapV;
  24690. return newTexture;
  24691. };
  24692. return DynamicTexture;
  24693. }(BABYLON.Texture));
  24694. BABYLON.DynamicTexture = DynamicTexture;
  24695. })(BABYLON || (BABYLON = {}));
  24696. //# sourceMappingURL=babylon.dynamicTexture.js.map
  24697. var BABYLON;
  24698. (function (BABYLON) {
  24699. var VideoTexture = (function (_super) {
  24700. __extends(VideoTexture, _super);
  24701. /**
  24702. * Creates a video texture.
  24703. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24704. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24705. * @param {BABYLON.Scene} scene is obviously the current scene.
  24706. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24707. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24708. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24709. */
  24710. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24711. var _this = this;
  24712. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24713. if (invertY === void 0) { invertY = false; }
  24714. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24715. _super.call(this, null, scene, !generateMipMaps, invertY);
  24716. this._autoLaunch = true;
  24717. var urls;
  24718. this.name = name;
  24719. if (urlsOrVideo instanceof HTMLVideoElement) {
  24720. this.video = urlsOrVideo;
  24721. }
  24722. else {
  24723. urls = urlsOrVideo;
  24724. this.video = document.createElement("video");
  24725. this.video.autoplay = false;
  24726. this.video.loop = true;
  24727. }
  24728. this._generateMipMaps = generateMipMaps;
  24729. this._samplingMode = samplingMode;
  24730. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  24731. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24732. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24733. }
  24734. else {
  24735. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24736. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24737. this._generateMipMaps = false;
  24738. }
  24739. if (urls) {
  24740. this.video.addEventListener("canplaythrough", function () {
  24741. _this._createTexture();
  24742. });
  24743. urls.forEach(function (url) {
  24744. var source = document.createElement("source");
  24745. source.src = url;
  24746. _this.video.appendChild(source);
  24747. });
  24748. }
  24749. else {
  24750. this._createTexture();
  24751. }
  24752. this._lastUpdate = BABYLON.Tools.Now;
  24753. }
  24754. VideoTexture.prototype._createTexture = function () {
  24755. if (this.video.videoWidth === 0 || this.video.videoHeight === 0) {
  24756. return;
  24757. }
  24758. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24759. this._texture.isReady = true;
  24760. };
  24761. VideoTexture.prototype.update = function () {
  24762. if (this._autoLaunch) {
  24763. this._autoLaunch = false;
  24764. this.video.play();
  24765. }
  24766. var now = BABYLON.Tools.Now;
  24767. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24768. return false;
  24769. }
  24770. this._lastUpdate = now;
  24771. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24772. return true;
  24773. };
  24774. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  24775. var video = document.createElement("video");
  24776. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  24777. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  24778. if (navigator.getUserMedia) {
  24779. navigator.getUserMedia({
  24780. video: {
  24781. width: {
  24782. min: (constraints && constraints.minWidth) || 256,
  24783. max: (constraints && constraints.maxWidth) || 640
  24784. },
  24785. height: {
  24786. min: (constraints && constraints.minHeight) || 256,
  24787. max: (constraints && constraints.maxHeight) || 480
  24788. }
  24789. }
  24790. }, function (stream) {
  24791. if (video.mozSrcObject !== undefined) {
  24792. video.mozSrcObject = stream;
  24793. }
  24794. else {
  24795. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  24796. }
  24797. video.play();
  24798. if (onReady) {
  24799. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  24800. }
  24801. }, function (e) {
  24802. BABYLON.Tools.Error(e.name);
  24803. });
  24804. }
  24805. };
  24806. return VideoTexture;
  24807. }(BABYLON.Texture));
  24808. BABYLON.VideoTexture = VideoTexture;
  24809. })(BABYLON || (BABYLON = {}));
  24810. //# sourceMappingURL=babylon.videoTexture.js.map
  24811. var BABYLON;
  24812. (function (BABYLON) {
  24813. var CustomProceduralTexture = (function (_super) {
  24814. __extends(CustomProceduralTexture, _super);
  24815. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24816. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24817. this._animate = true;
  24818. this._time = 0;
  24819. this._texturePath = texturePath;
  24820. //Try to load json
  24821. this.loadJson(texturePath);
  24822. this.refreshRate = 1;
  24823. }
  24824. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24825. var _this = this;
  24826. var that = this;
  24827. function noConfigFile() {
  24828. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24829. try {
  24830. that.setFragment(that._texturePath);
  24831. }
  24832. catch (ex) {
  24833. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24834. }
  24835. }
  24836. var configFileUrl = jsonUrl + "/config.json";
  24837. var xhr = new XMLHttpRequest();
  24838. xhr.open("GET", configFileUrl, true);
  24839. xhr.addEventListener("load", function () {
  24840. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24841. try {
  24842. _this._config = JSON.parse(xhr.response);
  24843. _this.updateShaderUniforms();
  24844. _this.updateTextures();
  24845. _this.setFragment(_this._texturePath + "/custom");
  24846. _this._animate = _this._config.animate;
  24847. _this.refreshRate = _this._config.refreshrate;
  24848. }
  24849. catch (ex) {
  24850. noConfigFile();
  24851. }
  24852. }
  24853. else {
  24854. noConfigFile();
  24855. }
  24856. }, false);
  24857. xhr.addEventListener("error", function () {
  24858. noConfigFile();
  24859. }, false);
  24860. try {
  24861. xhr.send();
  24862. }
  24863. catch (ex) {
  24864. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24865. }
  24866. };
  24867. CustomProceduralTexture.prototype.isReady = function () {
  24868. if (!_super.prototype.isReady.call(this)) {
  24869. return false;
  24870. }
  24871. for (var name in this._textures) {
  24872. var texture = this._textures[name];
  24873. if (!texture.isReady()) {
  24874. return false;
  24875. }
  24876. }
  24877. return true;
  24878. };
  24879. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24880. if (this._animate) {
  24881. this._time += this.getScene().getAnimationRatio() * 0.03;
  24882. this.updateShaderUniforms();
  24883. }
  24884. _super.prototype.render.call(this, useCameraPostProcess);
  24885. };
  24886. CustomProceduralTexture.prototype.updateTextures = function () {
  24887. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24888. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24889. }
  24890. };
  24891. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24892. if (this._config) {
  24893. for (var j = 0; j < this._config.uniforms.length; j++) {
  24894. var uniform = this._config.uniforms[j];
  24895. switch (uniform.type) {
  24896. case "float":
  24897. this.setFloat(uniform.name, uniform.value);
  24898. break;
  24899. case "color3":
  24900. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24901. break;
  24902. case "color4":
  24903. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24904. break;
  24905. case "vector2":
  24906. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24907. break;
  24908. case "vector3":
  24909. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24910. break;
  24911. }
  24912. }
  24913. }
  24914. this.setFloat("time", this._time);
  24915. };
  24916. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24917. get: function () {
  24918. return this._animate;
  24919. },
  24920. set: function (value) {
  24921. this._animate = value;
  24922. },
  24923. enumerable: true,
  24924. configurable: true
  24925. });
  24926. return CustomProceduralTexture;
  24927. }(BABYLON.ProceduralTexture));
  24928. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24929. })(BABYLON || (BABYLON = {}));
  24930. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  24931. var BABYLON;
  24932. (function (BABYLON) {
  24933. var EffectFallbacks = (function () {
  24934. function EffectFallbacks() {
  24935. this._defines = {};
  24936. this._currentRank = 32;
  24937. this._maxRank = -1;
  24938. }
  24939. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24940. if (!this._defines[rank]) {
  24941. if (rank < this._currentRank) {
  24942. this._currentRank = rank;
  24943. }
  24944. if (rank > this._maxRank) {
  24945. this._maxRank = rank;
  24946. }
  24947. this._defines[rank] = new Array();
  24948. }
  24949. this._defines[rank].push(define);
  24950. };
  24951. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24952. this._meshRank = rank;
  24953. this._mesh = mesh;
  24954. if (rank > this._maxRank) {
  24955. this._maxRank = rank;
  24956. }
  24957. };
  24958. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24959. get: function () {
  24960. return this._currentRank <= this._maxRank;
  24961. },
  24962. enumerable: true,
  24963. configurable: true
  24964. });
  24965. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24966. var currentFallbacks = this._defines[this._currentRank];
  24967. for (var index = 0; index < currentFallbacks.length; index++) {
  24968. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24969. }
  24970. if (this._mesh && this._currentRank === this._meshRank) {
  24971. this._mesh.computeBonesUsingShaders = false;
  24972. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24973. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24974. }
  24975. this._currentRank++;
  24976. return currentDefines;
  24977. };
  24978. return EffectFallbacks;
  24979. }());
  24980. BABYLON.EffectFallbacks = EffectFallbacks;
  24981. var Effect = (function () {
  24982. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24983. var _this = this;
  24984. this._isReady = false;
  24985. this._compilationError = "";
  24986. this._valueCache = {};
  24987. this._engine = engine;
  24988. this.name = baseName;
  24989. this.defines = defines;
  24990. this._uniformsNames = uniformsNames.concat(samplers);
  24991. this._samplers = samplers;
  24992. this._attributesNames = attributesNames;
  24993. this.onError = onError;
  24994. this.onCompiled = onCompiled;
  24995. this._indexParameters = indexParameters;
  24996. var vertexSource;
  24997. var fragmentSource;
  24998. if (baseName.vertexElement) {
  24999. vertexSource = document.getElementById(baseName.vertexElement);
  25000. if (!vertexSource) {
  25001. vertexSource = baseName.vertexElement;
  25002. }
  25003. }
  25004. else {
  25005. vertexSource = baseName.vertex || baseName;
  25006. }
  25007. if (baseName.fragmentElement) {
  25008. fragmentSource = document.getElementById(baseName.fragmentElement);
  25009. if (!fragmentSource) {
  25010. fragmentSource = baseName.fragmentElement;
  25011. }
  25012. }
  25013. else {
  25014. fragmentSource = baseName.fragment || baseName;
  25015. }
  25016. this._loadVertexShader(vertexSource, function (vertexCode) {
  25017. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25018. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25019. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25020. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  25021. });
  25022. });
  25023. });
  25024. });
  25025. }
  25026. // Properties
  25027. Effect.prototype.isReady = function () {
  25028. return this._isReady;
  25029. };
  25030. Effect.prototype.getProgram = function () {
  25031. return this._program;
  25032. };
  25033. Effect.prototype.getAttributesNames = function () {
  25034. return this._attributesNames;
  25035. };
  25036. Effect.prototype.getAttributeLocation = function (index) {
  25037. return this._attributes[index];
  25038. };
  25039. Effect.prototype.getAttributeLocationByName = function (name) {
  25040. var index = this._attributesNames.indexOf(name);
  25041. return this._attributes[index];
  25042. };
  25043. Effect.prototype.getAttributesCount = function () {
  25044. return this._attributes.length;
  25045. };
  25046. Effect.prototype.getUniformIndex = function (uniformName) {
  25047. return this._uniformsNames.indexOf(uniformName);
  25048. };
  25049. Effect.prototype.getUniform = function (uniformName) {
  25050. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25051. };
  25052. Effect.prototype.getSamplers = function () {
  25053. return this._samplers;
  25054. };
  25055. Effect.prototype.getCompilationError = function () {
  25056. return this._compilationError;
  25057. };
  25058. Effect.prototype.getVertexShaderSource = function () {
  25059. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  25060. };
  25061. Effect.prototype.getFragmentShaderSource = function () {
  25062. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  25063. };
  25064. // Methods
  25065. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25066. // DOM element ?
  25067. if (vertex instanceof HTMLElement) {
  25068. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25069. callback(vertexCode);
  25070. return;
  25071. }
  25072. // Base64 encoded ?
  25073. if (vertex.substr(0, 7) === "base64:") {
  25074. var vertexBinary = window.atob(vertex.substr(7));
  25075. callback(vertexBinary);
  25076. return;
  25077. }
  25078. // Is in local store ?
  25079. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25080. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25081. return;
  25082. }
  25083. var vertexShaderUrl;
  25084. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25085. vertexShaderUrl = vertex;
  25086. }
  25087. else {
  25088. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25089. }
  25090. // Vertex shader
  25091. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25092. };
  25093. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25094. // DOM element ?
  25095. if (fragment instanceof HTMLElement) {
  25096. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25097. callback(fragmentCode);
  25098. return;
  25099. }
  25100. // Base64 encoded ?
  25101. if (fragment.substr(0, 7) === "base64:") {
  25102. var fragmentBinary = window.atob(fragment.substr(7));
  25103. callback(fragmentBinary);
  25104. return;
  25105. }
  25106. // Is in local store ?
  25107. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25108. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25109. return;
  25110. }
  25111. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25112. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25113. return;
  25114. }
  25115. var fragmentShaderUrl;
  25116. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25117. fragmentShaderUrl = fragment;
  25118. }
  25119. else {
  25120. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25121. }
  25122. // Fragment shader
  25123. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25124. };
  25125. Effect.prototype._dumpShadersName = function () {
  25126. if (this.name.vertexElement) {
  25127. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25128. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25129. }
  25130. else if (this.name.vertex) {
  25131. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25132. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25133. }
  25134. else {
  25135. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25136. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25137. }
  25138. };
  25139. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25140. var _this = this;
  25141. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25142. var match = regex.exec(sourceCode);
  25143. var returnValue = new String(sourceCode);
  25144. while (match != null) {
  25145. var includeFile = match[1];
  25146. if (Effect.IncludesShadersStore[includeFile]) {
  25147. // Substitution
  25148. var includeContent = Effect.IncludesShadersStore[includeFile];
  25149. if (match[2]) {
  25150. var splits = match[3].split(",");
  25151. for (var index = 0; index < splits.length; index += 2) {
  25152. var source = new RegExp(splits[index], "g");
  25153. var dest = splits[index + 1];
  25154. includeContent = includeContent.replace(source, dest);
  25155. }
  25156. }
  25157. if (match[4]) {
  25158. var indexString = match[5];
  25159. if (indexString.indexOf("..") !== -1) {
  25160. var indexSplits = indexString.split("..");
  25161. var minIndex = parseInt(indexSplits[0]);
  25162. var maxIndex = parseInt(indexSplits[1]);
  25163. var sourceIncludeContent = includeContent.slice(0);
  25164. includeContent = "";
  25165. if (isNaN(maxIndex)) {
  25166. maxIndex = this._indexParameters[indexSplits[1]];
  25167. }
  25168. for (var i = minIndex; i <= maxIndex; i++) {
  25169. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  25170. }
  25171. }
  25172. else {
  25173. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25174. }
  25175. }
  25176. // Replace
  25177. returnValue = returnValue.replace(match[0], includeContent);
  25178. }
  25179. else {
  25180. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25181. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25182. Effect.IncludesShadersStore[includeFile] = fileContent;
  25183. _this._processIncludes(returnValue, callback);
  25184. });
  25185. return;
  25186. }
  25187. match = regex.exec(sourceCode);
  25188. }
  25189. callback(returnValue);
  25190. };
  25191. Effect.prototype._processPrecision = function (source) {
  25192. if (source.indexOf("precision highp float") === -1) {
  25193. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25194. source = "precision mediump float;\n" + source;
  25195. }
  25196. else {
  25197. source = "precision highp float;\n" + source;
  25198. }
  25199. }
  25200. else {
  25201. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25202. source = source.replace("precision highp float", "precision mediump float");
  25203. }
  25204. }
  25205. return source;
  25206. };
  25207. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  25208. try {
  25209. var engine = this._engine;
  25210. // Precision
  25211. vertexSourceCode = this._processPrecision(vertexSourceCode);
  25212. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  25213. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  25214. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25215. this._attributes = engine.getAttributes(this._program, attributesNames);
  25216. var index;
  25217. for (index = 0; index < this._samplers.length; index++) {
  25218. var sampler = this.getUniform(this._samplers[index]);
  25219. if (sampler == null) {
  25220. this._samplers.splice(index, 1);
  25221. index--;
  25222. }
  25223. }
  25224. engine.bindSamplers(this);
  25225. this._compilationError = "";
  25226. this._isReady = true;
  25227. if (this.onCompiled) {
  25228. this.onCompiled(this);
  25229. }
  25230. }
  25231. catch (e) {
  25232. this._compilationError = e.message;
  25233. // Let's go through fallbacks then
  25234. BABYLON.Tools.Error("Unable to compile effect: ");
  25235. BABYLON.Tools.Error("Defines: " + defines);
  25236. BABYLON.Tools.Error("Error: " + this._compilationError);
  25237. this._dumpShadersName();
  25238. if (fallbacks && fallbacks.isMoreFallbacks) {
  25239. BABYLON.Tools.Error("Trying next fallback.");
  25240. defines = fallbacks.reduce(defines);
  25241. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25242. }
  25243. else {
  25244. if (this.onError) {
  25245. this.onError(this, this._compilationError);
  25246. }
  25247. }
  25248. }
  25249. };
  25250. Object.defineProperty(Effect.prototype, "isSupported", {
  25251. get: function () {
  25252. return this._compilationError === "";
  25253. },
  25254. enumerable: true,
  25255. configurable: true
  25256. });
  25257. Effect.prototype._bindTexture = function (channel, texture) {
  25258. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25259. };
  25260. Effect.prototype.setTexture = function (channel, texture) {
  25261. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25262. };
  25263. Effect.prototype.setTextureArray = function (channel, textures) {
  25264. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25265. var initialPos = this._samplers.indexOf(channel);
  25266. for (var index = 1; index < textures.length; index++) {
  25267. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25268. }
  25269. }
  25270. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25271. };
  25272. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25273. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25274. };
  25275. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25276. var changed = false;
  25277. var cache = this._valueCache[uniformName];
  25278. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25279. changed = true;
  25280. cache = new BABYLON.Matrix();
  25281. }
  25282. var tm = cache.m;
  25283. var om = matrix.m;
  25284. for (var index = 0; index < 16; index++) {
  25285. if (tm[index] !== om[index]) {
  25286. tm[index] = om[index];
  25287. changed = true;
  25288. }
  25289. }
  25290. this._valueCache[uniformName] = cache;
  25291. return changed;
  25292. };
  25293. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25294. var cache = this._valueCache[uniformName];
  25295. if (!cache) {
  25296. cache = [x, y];
  25297. this._valueCache[uniformName] = cache;
  25298. return true;
  25299. }
  25300. var changed = false;
  25301. if (cache[0] !== x) {
  25302. cache[0] = x;
  25303. changed = true;
  25304. }
  25305. if (cache[1] !== y) {
  25306. cache[1] = y;
  25307. changed = true;
  25308. }
  25309. return changed;
  25310. };
  25311. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25312. var cache = this._valueCache[uniformName];
  25313. if (!cache) {
  25314. cache = [x, y, z];
  25315. this._valueCache[uniformName] = cache;
  25316. return true;
  25317. }
  25318. var changed = false;
  25319. if (cache[0] !== x) {
  25320. cache[0] = x;
  25321. changed = true;
  25322. }
  25323. if (cache[1] !== y) {
  25324. cache[1] = y;
  25325. changed = true;
  25326. }
  25327. if (cache[2] !== z) {
  25328. cache[2] = z;
  25329. changed = true;
  25330. }
  25331. return changed;
  25332. };
  25333. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25334. var cache = this._valueCache[uniformName];
  25335. if (!cache) {
  25336. cache = [x, y, z, w];
  25337. this._valueCache[uniformName] = cache;
  25338. return true;
  25339. }
  25340. var changed = false;
  25341. if (cache[0] !== x) {
  25342. cache[0] = x;
  25343. changed = true;
  25344. }
  25345. if (cache[1] !== y) {
  25346. cache[1] = y;
  25347. changed = true;
  25348. }
  25349. if (cache[2] !== z) {
  25350. cache[2] = z;
  25351. changed = true;
  25352. }
  25353. if (cache[3] !== w) {
  25354. cache[3] = w;
  25355. changed = true;
  25356. }
  25357. return changed;
  25358. };
  25359. Effect.prototype.setIntArray = function (uniformName, array) {
  25360. this._valueCache[uniformName] = null;
  25361. this._engine.setIntArray(this.getUniform(uniformName), array);
  25362. return this;
  25363. };
  25364. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25365. this._valueCache[uniformName] = null;
  25366. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25367. return this;
  25368. };
  25369. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25370. this._valueCache[uniformName] = null;
  25371. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25372. return this;
  25373. };
  25374. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25375. this._valueCache[uniformName] = null;
  25376. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25377. return this;
  25378. };
  25379. Effect.prototype.setFloatArray = function (uniformName, array) {
  25380. this._valueCache[uniformName] = null;
  25381. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25382. return this;
  25383. };
  25384. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25385. this._valueCache[uniformName] = null;
  25386. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25387. return this;
  25388. };
  25389. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25390. this._valueCache[uniformName] = null;
  25391. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25392. return this;
  25393. };
  25394. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25395. this._valueCache[uniformName] = null;
  25396. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25397. return this;
  25398. };
  25399. Effect.prototype.setArray = function (uniformName, array) {
  25400. this._valueCache[uniformName] = null;
  25401. this._engine.setArray(this.getUniform(uniformName), array);
  25402. return this;
  25403. };
  25404. Effect.prototype.setArray2 = function (uniformName, array) {
  25405. this._valueCache[uniformName] = null;
  25406. this._engine.setArray2(this.getUniform(uniformName), array);
  25407. return this;
  25408. };
  25409. Effect.prototype.setArray3 = function (uniformName, array) {
  25410. this._valueCache[uniformName] = null;
  25411. this._engine.setArray3(this.getUniform(uniformName), array);
  25412. return this;
  25413. };
  25414. Effect.prototype.setArray4 = function (uniformName, array) {
  25415. this._valueCache[uniformName] = null;
  25416. this._engine.setArray4(this.getUniform(uniformName), array);
  25417. return this;
  25418. };
  25419. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25420. this._valueCache[uniformName] = null;
  25421. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25422. return this;
  25423. };
  25424. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25425. if (this._cacheMatrix(uniformName, matrix)) {
  25426. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25427. }
  25428. return this;
  25429. };
  25430. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25431. this._valueCache[uniformName] = null;
  25432. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25433. return this;
  25434. };
  25435. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25436. this._valueCache[uniformName] = null;
  25437. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25438. return this;
  25439. };
  25440. Effect.prototype.setFloat = function (uniformName, value) {
  25441. var cache = this._valueCache[uniformName];
  25442. if (cache !== undefined && cache === value)
  25443. return this;
  25444. this._valueCache[uniformName] = value;
  25445. this._engine.setFloat(this.getUniform(uniformName), value);
  25446. return this;
  25447. };
  25448. Effect.prototype.setBool = function (uniformName, bool) {
  25449. var cache = this._valueCache[uniformName];
  25450. if (cache !== undefined && cache === bool)
  25451. return this;
  25452. this._valueCache[uniformName] = bool;
  25453. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25454. return this;
  25455. };
  25456. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25457. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25458. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25459. }
  25460. return this;
  25461. };
  25462. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25463. if (this._cacheFloat2(uniformName, x, y)) {
  25464. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25465. }
  25466. return this;
  25467. };
  25468. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25469. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25470. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25471. }
  25472. return this;
  25473. };
  25474. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25475. if (this._cacheFloat3(uniformName, x, y, z)) {
  25476. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25477. }
  25478. return this;
  25479. };
  25480. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25481. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25482. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25483. }
  25484. return this;
  25485. };
  25486. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25487. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25488. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25489. }
  25490. return this;
  25491. };
  25492. Effect.prototype.setColor3 = function (uniformName, color3) {
  25493. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25494. this._engine.setColor3(this.getUniform(uniformName), color3);
  25495. }
  25496. return this;
  25497. };
  25498. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25499. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25500. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25501. }
  25502. return this;
  25503. };
  25504. Effect.prototype._recombineShader = function (node) {
  25505. if (node.define) {
  25506. if (node.condition) {
  25507. var defineIndex = this.defines.indexOf("#define " + node.define);
  25508. if (defineIndex === -1) {
  25509. return null;
  25510. }
  25511. var nextComma = this.defines.indexOf("\n", defineIndex);
  25512. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  25513. var condition = defineValue + node.condition;
  25514. if (!eval(condition)) {
  25515. return null;
  25516. }
  25517. }
  25518. else if (node.ndef) {
  25519. if (this.defines.indexOf("#define " + node.define) !== -1) {
  25520. return null;
  25521. }
  25522. }
  25523. else if (this.defines.indexOf("#define " + node.define) === -1) {
  25524. return null;
  25525. }
  25526. }
  25527. var result = "";
  25528. for (var index = 0; index < node.children.length; index++) {
  25529. var line = node.children[index];
  25530. if (line.children) {
  25531. var combined = this._recombineShader(line);
  25532. if (combined !== null) {
  25533. result += combined + "\r\n";
  25534. }
  25535. continue;
  25536. }
  25537. if (line.length > 0) {
  25538. result += line + "\r\n";
  25539. }
  25540. }
  25541. return result;
  25542. };
  25543. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  25544. var root = {
  25545. children: []
  25546. };
  25547. var currentNode = root;
  25548. var lines = shaderString.split("\n");
  25549. for (var index = 0; index < lines.length; index++) {
  25550. var line = lines[index].trim();
  25551. // #ifdef
  25552. var pos = line.indexOf("#ifdef ");
  25553. if (pos !== -1) {
  25554. var define = line.substr(pos + 7);
  25555. var newNode = {
  25556. condition: null,
  25557. ndef: false,
  25558. define: define,
  25559. children: [],
  25560. parent: currentNode
  25561. };
  25562. currentNode.children.push(newNode);
  25563. currentNode = newNode;
  25564. continue;
  25565. }
  25566. // #ifndef
  25567. var pos = line.indexOf("#ifndef ");
  25568. if (pos !== -1) {
  25569. var define = line.substr(pos + 8);
  25570. newNode = {
  25571. condition: null,
  25572. define: define,
  25573. ndef: true,
  25574. children: [],
  25575. parent: currentNode
  25576. };
  25577. currentNode.children.push(newNode);
  25578. currentNode = newNode;
  25579. continue;
  25580. }
  25581. // #if
  25582. var pos = line.indexOf("#if ");
  25583. if (pos !== -1) {
  25584. var define = line.substr(pos + 4).trim();
  25585. var conditionPos = define.indexOf(" ");
  25586. newNode = {
  25587. condition: define.substr(conditionPos + 1),
  25588. define: define.substr(0, conditionPos),
  25589. ndef: false,
  25590. children: [],
  25591. parent: currentNode
  25592. };
  25593. currentNode.children.push(newNode);
  25594. currentNode = newNode;
  25595. continue;
  25596. }
  25597. // #endif
  25598. pos = line.indexOf("#endif");
  25599. if (pos !== -1) {
  25600. currentNode = currentNode.parent;
  25601. continue;
  25602. }
  25603. currentNode.children.push(line);
  25604. }
  25605. // Recombine
  25606. return this._recombineShader(root);
  25607. };
  25608. // Statics
  25609. Effect.ShadersStore = {};
  25610. Effect.IncludesShadersStore = {};
  25611. return Effect;
  25612. }());
  25613. BABYLON.Effect = Effect;
  25614. })(BABYLON || (BABYLON = {}));
  25615. //# sourceMappingURL=babylon.effect.js.map
  25616. var BABYLON;
  25617. (function (BABYLON) {
  25618. var MaterialHelper = (function () {
  25619. function MaterialHelper() {
  25620. }
  25621. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25622. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25623. var lightIndex = 0;
  25624. var needNormals = false;
  25625. var needRebuild = false;
  25626. var needShadows = false;
  25627. var lightmapMode = false;
  25628. for (var index = 0; index < scene.lights.length; index++) {
  25629. var light = scene.lights[index];
  25630. if (!light.isEnabled()) {
  25631. continue;
  25632. }
  25633. // Excluded check
  25634. if (light._excludedMeshesIds.length > 0) {
  25635. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25636. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25637. if (excludedMesh) {
  25638. light.excludedMeshes.push(excludedMesh);
  25639. }
  25640. }
  25641. light._excludedMeshesIds = [];
  25642. }
  25643. // Included check
  25644. if (light._includedOnlyMeshesIds.length > 0) {
  25645. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25646. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25647. if (includedOnlyMesh) {
  25648. light.includedOnlyMeshes.push(includedOnlyMesh);
  25649. }
  25650. }
  25651. light._includedOnlyMeshesIds = [];
  25652. }
  25653. if (!light.canAffectMesh(mesh)) {
  25654. continue;
  25655. }
  25656. needNormals = true;
  25657. if (defines["LIGHT" + lightIndex] === undefined) {
  25658. needRebuild = true;
  25659. }
  25660. defines["LIGHT" + lightIndex] = true;
  25661. var type;
  25662. if (light instanceof BABYLON.SpotLight) {
  25663. type = "SPOTLIGHT" + lightIndex;
  25664. }
  25665. else if (light instanceof BABYLON.HemisphericLight) {
  25666. type = "HEMILIGHT" + lightIndex;
  25667. }
  25668. else if (light instanceof BABYLON.PointLight) {
  25669. type = "POINTLIGHT" + lightIndex;
  25670. }
  25671. else {
  25672. type = "DIRLIGHT" + lightIndex;
  25673. }
  25674. if (defines[type] === undefined) {
  25675. needRebuild = true;
  25676. }
  25677. defines[type] = true;
  25678. // Specular
  25679. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25680. defines["SPECULARTERM"] = true;
  25681. }
  25682. // Shadows
  25683. if (scene.shadowsEnabled) {
  25684. var shadowGenerator = light.getShadowGenerator();
  25685. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25686. if (defines["SHADOW" + lightIndex] === undefined) {
  25687. needRebuild = true;
  25688. }
  25689. defines["SHADOW" + lightIndex] = true;
  25690. defines["SHADOWS"] = true;
  25691. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25692. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25693. needRebuild = true;
  25694. }
  25695. defines["SHADOWVSM" + lightIndex] = true;
  25696. }
  25697. if (shadowGenerator.usePoissonSampling) {
  25698. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25699. needRebuild = true;
  25700. }
  25701. defines["SHADOWPCF" + lightIndex] = true;
  25702. }
  25703. needShadows = true;
  25704. }
  25705. }
  25706. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25707. lightmapMode = true;
  25708. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25709. needRebuild = true;
  25710. }
  25711. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25712. needRebuild = true;
  25713. }
  25714. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25715. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25716. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25717. }
  25718. }
  25719. lightIndex++;
  25720. if (lightIndex === maxSimultaneousLights)
  25721. break;
  25722. }
  25723. var caps = scene.getEngine().getCaps();
  25724. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25725. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25726. needRebuild = true;
  25727. }
  25728. defines["SHADOWFULLFLOAT"] = true;
  25729. }
  25730. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25731. needRebuild = true;
  25732. }
  25733. if (lightmapMode) {
  25734. defines["LIGHTMAPEXCLUDED"] = true;
  25735. }
  25736. if (needRebuild) {
  25737. defines.rebuild();
  25738. }
  25739. return needNormals;
  25740. };
  25741. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25742. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25743. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25744. if (!defines["LIGHT" + lightIndex]) {
  25745. break;
  25746. }
  25747. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25748. samplersList.push("shadowSampler" + lightIndex);
  25749. }
  25750. };
  25751. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25752. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25753. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25754. if (!defines["LIGHT" + lightIndex]) {
  25755. break;
  25756. }
  25757. if (lightIndex > 0) {
  25758. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25759. }
  25760. if (defines["SHADOW" + lightIndex]) {
  25761. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25762. }
  25763. if (defines["SHADOWPCF" + lightIndex]) {
  25764. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25765. }
  25766. if (defines["SHADOWVSM" + lightIndex]) {
  25767. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25768. }
  25769. }
  25770. };
  25771. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25772. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25773. fallbacks.addCPUSkinningFallback(0, mesh);
  25774. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25775. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25776. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25777. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25778. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25779. }
  25780. }
  25781. };
  25782. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25783. if (defines["INSTANCES"]) {
  25784. attribs.push("world0");
  25785. attribs.push("world1");
  25786. attribs.push("world2");
  25787. attribs.push("world3");
  25788. }
  25789. };
  25790. // Bindings
  25791. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25792. var shadowGenerator = light.getShadowGenerator();
  25793. if (mesh.receiveShadows && shadowGenerator) {
  25794. if (!light.needCube()) {
  25795. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25796. }
  25797. else {
  25798. if (!depthValuesAlreadySet) {
  25799. depthValuesAlreadySet = true;
  25800. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25801. }
  25802. }
  25803. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25804. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25805. }
  25806. return depthValuesAlreadySet;
  25807. };
  25808. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25809. if (light instanceof BABYLON.PointLight) {
  25810. // Point Light
  25811. light.transferToEffect(effect, "vLightData" + lightIndex);
  25812. }
  25813. else if (light instanceof BABYLON.DirectionalLight) {
  25814. // Directional Light
  25815. light.transferToEffect(effect, "vLightData" + lightIndex);
  25816. }
  25817. else if (light instanceof BABYLON.SpotLight) {
  25818. // Spot Light
  25819. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25820. }
  25821. else if (light instanceof BABYLON.HemisphericLight) {
  25822. // Hemispheric Light
  25823. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25824. }
  25825. };
  25826. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25827. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25828. var lightIndex = 0;
  25829. var depthValuesAlreadySet = false;
  25830. for (var index = 0; index < scene.lights.length; index++) {
  25831. var light = scene.lights[index];
  25832. if (!light.isEnabled()) {
  25833. continue;
  25834. }
  25835. if (!light.canAffectMesh(mesh)) {
  25836. continue;
  25837. }
  25838. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25839. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25840. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25841. if (defines["SPECULARTERM"]) {
  25842. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25843. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25844. }
  25845. // Shadows
  25846. if (scene.shadowsEnabled) {
  25847. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25848. }
  25849. lightIndex++;
  25850. if (lightIndex === maxSimultaneousLights)
  25851. break;
  25852. }
  25853. };
  25854. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25855. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25856. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25857. effect.setColor3("vFogColor", scene.fogColor);
  25858. }
  25859. };
  25860. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25861. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25862. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25863. if (matrices) {
  25864. effect.setMatrices("mBones", matrices);
  25865. }
  25866. }
  25867. };
  25868. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25869. if (defines["LOGARITHMICDEPTH"]) {
  25870. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25871. }
  25872. };
  25873. MaterialHelper.BindClipPlane = function (effect, scene) {
  25874. if (scene.clipPlane) {
  25875. var clipPlane = scene.clipPlane;
  25876. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25877. }
  25878. };
  25879. return MaterialHelper;
  25880. }());
  25881. BABYLON.MaterialHelper = MaterialHelper;
  25882. })(BABYLON || (BABYLON = {}));
  25883. //# sourceMappingURL=babylon.materialHelper.js.map
  25884. var BABYLON;
  25885. (function (BABYLON) {
  25886. var FresnelParameters = (function () {
  25887. function FresnelParameters() {
  25888. this.isEnabled = true;
  25889. this.leftColor = BABYLON.Color3.White();
  25890. this.rightColor = BABYLON.Color3.Black();
  25891. this.bias = 0;
  25892. this.power = 1;
  25893. }
  25894. FresnelParameters.prototype.clone = function () {
  25895. var newFresnelParameters = new FresnelParameters();
  25896. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25897. return newFresnelParameters;
  25898. };
  25899. FresnelParameters.prototype.serialize = function () {
  25900. var serializationObject = {};
  25901. serializationObject.isEnabled = this.isEnabled;
  25902. serializationObject.leftColor = this.leftColor;
  25903. serializationObject.rightColor = this.rightColor;
  25904. serializationObject.bias = this.bias;
  25905. serializationObject.power = this.power;
  25906. return serializationObject;
  25907. };
  25908. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25909. var fresnelParameters = new FresnelParameters();
  25910. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25911. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25912. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25913. fresnelParameters.bias = parsedFresnelParameters.bias;
  25914. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25915. return fresnelParameters;
  25916. };
  25917. return FresnelParameters;
  25918. }());
  25919. BABYLON.FresnelParameters = FresnelParameters;
  25920. })(BABYLON || (BABYLON = {}));
  25921. //# sourceMappingURL=babylon.fresnelParameters.js.map
  25922. var BABYLON;
  25923. (function (BABYLON) {
  25924. var MaterialDefines = (function () {
  25925. function MaterialDefines() {
  25926. }
  25927. MaterialDefines.prototype.rebuild = function () {
  25928. if (this._keys) {
  25929. delete this._keys;
  25930. }
  25931. this._keys = Object.keys(this);
  25932. };
  25933. MaterialDefines.prototype.isEqual = function (other) {
  25934. if (this._keys.length !== other._keys.length) {
  25935. return false;
  25936. }
  25937. for (var index = 0; index < this._keys.length; index++) {
  25938. var prop = this._keys[index];
  25939. if (this[prop] !== other[prop]) {
  25940. return false;
  25941. }
  25942. }
  25943. return true;
  25944. };
  25945. MaterialDefines.prototype.cloneTo = function (other) {
  25946. if (this._keys.length !== other._keys.length) {
  25947. other._keys = this._keys.slice(0);
  25948. }
  25949. for (var index = 0; index < this._keys.length; index++) {
  25950. var prop = this._keys[index];
  25951. other[prop] = this[prop];
  25952. }
  25953. };
  25954. MaterialDefines.prototype.reset = function () {
  25955. for (var index = 0; index < this._keys.length; index++) {
  25956. var prop = this._keys[index];
  25957. if (typeof (this[prop]) === "number") {
  25958. this[prop] = 0;
  25959. }
  25960. else {
  25961. this[prop] = false;
  25962. }
  25963. }
  25964. };
  25965. MaterialDefines.prototype.toString = function () {
  25966. var result = "";
  25967. for (var index = 0; index < this._keys.length; index++) {
  25968. var prop = this._keys[index];
  25969. if (typeof (this[prop]) === "number") {
  25970. result += "#define " + prop + " " + this[prop] + "\n";
  25971. }
  25972. else if (this[prop]) {
  25973. result += "#define " + prop + "\n";
  25974. }
  25975. }
  25976. return result;
  25977. };
  25978. return MaterialDefines;
  25979. }());
  25980. BABYLON.MaterialDefines = MaterialDefines;
  25981. var Material = (function () {
  25982. function Material(name, scene, doNotAdd) {
  25983. this.checkReadyOnEveryCall = false;
  25984. this.checkReadyOnlyOnce = false;
  25985. this.state = "";
  25986. this.alpha = 1.0;
  25987. this.backFaceCulling = true;
  25988. this.doNotSerialize = false;
  25989. /**
  25990. * An event triggered when the material is disposed.
  25991. * @type {BABYLON.Observable}
  25992. */
  25993. this.onDisposeObservable = new BABYLON.Observable();
  25994. /**
  25995. * An event triggered when the material is bound.
  25996. * @type {BABYLON.Observable}
  25997. */
  25998. this.onBindObservable = new BABYLON.Observable();
  25999. /**
  26000. * An event triggered when the material is unbound.
  26001. * @type {BABYLON.Observable}
  26002. */
  26003. this.onUnBindObservable = new BABYLON.Observable();
  26004. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26005. this.disableDepthWrite = false;
  26006. this.fogEnabled = true;
  26007. this.pointSize = 1.0;
  26008. this.zOffset = 0;
  26009. this._wasPreviouslyReady = false;
  26010. this._fillMode = Material.TriangleFillMode;
  26011. this.name = name;
  26012. this.id = name;
  26013. this._scene = scene;
  26014. if (scene.useRightHandedSystem) {
  26015. this.sideOrientation = Material.ClockWiseSideOrientation;
  26016. }
  26017. else {
  26018. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26019. }
  26020. if (!doNotAdd) {
  26021. scene.materials.push(this);
  26022. }
  26023. }
  26024. Object.defineProperty(Material, "TriangleFillMode", {
  26025. get: function () {
  26026. return Material._TriangleFillMode;
  26027. },
  26028. enumerable: true,
  26029. configurable: true
  26030. });
  26031. Object.defineProperty(Material, "WireFrameFillMode", {
  26032. get: function () {
  26033. return Material._WireFrameFillMode;
  26034. },
  26035. enumerable: true,
  26036. configurable: true
  26037. });
  26038. Object.defineProperty(Material, "PointFillMode", {
  26039. get: function () {
  26040. return Material._PointFillMode;
  26041. },
  26042. enumerable: true,
  26043. configurable: true
  26044. });
  26045. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26046. get: function () {
  26047. return Material._ClockWiseSideOrientation;
  26048. },
  26049. enumerable: true,
  26050. configurable: true
  26051. });
  26052. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26053. get: function () {
  26054. return Material._CounterClockWiseSideOrientation;
  26055. },
  26056. enumerable: true,
  26057. configurable: true
  26058. });
  26059. Object.defineProperty(Material.prototype, "onDispose", {
  26060. set: function (callback) {
  26061. if (this._onDisposeObserver) {
  26062. this.onDisposeObservable.remove(this._onDisposeObserver);
  26063. }
  26064. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26065. },
  26066. enumerable: true,
  26067. configurable: true
  26068. });
  26069. Object.defineProperty(Material.prototype, "onBind", {
  26070. set: function (callback) {
  26071. if (this._onBindObserver) {
  26072. this.onBindObservable.remove(this._onBindObserver);
  26073. }
  26074. this._onBindObserver = this.onBindObservable.add(callback);
  26075. },
  26076. enumerable: true,
  26077. configurable: true
  26078. });
  26079. Object.defineProperty(Material.prototype, "wireframe", {
  26080. get: function () {
  26081. return this._fillMode === Material.WireFrameFillMode;
  26082. },
  26083. set: function (value) {
  26084. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26085. },
  26086. enumerable: true,
  26087. configurable: true
  26088. });
  26089. Object.defineProperty(Material.prototype, "pointsCloud", {
  26090. get: function () {
  26091. return this._fillMode === Material.PointFillMode;
  26092. },
  26093. set: function (value) {
  26094. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26095. },
  26096. enumerable: true,
  26097. configurable: true
  26098. });
  26099. Object.defineProperty(Material.prototype, "fillMode", {
  26100. get: function () {
  26101. return this._fillMode;
  26102. },
  26103. set: function (value) {
  26104. this._fillMode = value;
  26105. },
  26106. enumerable: true,
  26107. configurable: true
  26108. });
  26109. /**
  26110. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26111. * subclasses should override adding information pertainent to themselves
  26112. */
  26113. Material.prototype.toString = function (fullDetails) {
  26114. var ret = "Name: " + this.name;
  26115. if (fullDetails) {
  26116. }
  26117. return ret;
  26118. };
  26119. Material.prototype.getClassName = function () {
  26120. return "Material";
  26121. };
  26122. Object.defineProperty(Material.prototype, "isFrozen", {
  26123. get: function () {
  26124. return this.checkReadyOnlyOnce;
  26125. },
  26126. enumerable: true,
  26127. configurable: true
  26128. });
  26129. Material.prototype.freeze = function () {
  26130. this.checkReadyOnlyOnce = true;
  26131. };
  26132. Material.prototype.unfreeze = function () {
  26133. this.checkReadyOnlyOnce = false;
  26134. };
  26135. Material.prototype.isReady = function (mesh, useInstances) {
  26136. return true;
  26137. };
  26138. Material.prototype.getEffect = function () {
  26139. return this._effect;
  26140. };
  26141. Material.prototype.getScene = function () {
  26142. return this._scene;
  26143. };
  26144. Material.prototype.needAlphaBlending = function () {
  26145. return (this.alpha < 1.0);
  26146. };
  26147. Material.prototype.needAlphaTesting = function () {
  26148. return false;
  26149. };
  26150. Material.prototype.getAlphaTestTexture = function () {
  26151. return null;
  26152. };
  26153. Material.prototype.markDirty = function () {
  26154. this._wasPreviouslyReady = false;
  26155. };
  26156. Material.prototype._preBind = function () {
  26157. var engine = this._scene.getEngine();
  26158. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26159. engine.enableEffect(this._effect);
  26160. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26161. };
  26162. Material.prototype.bind = function (world, mesh) {
  26163. this._scene._cachedMaterial = this;
  26164. this.onBindObservable.notifyObservers(mesh);
  26165. if (this.disableDepthWrite) {
  26166. var engine = this._scene.getEngine();
  26167. this._cachedDepthWriteState = engine.getDepthWrite();
  26168. engine.setDepthWrite(false);
  26169. }
  26170. };
  26171. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26172. };
  26173. Material.prototype.unbind = function () {
  26174. this.onUnBindObservable.notifyObservers(this);
  26175. if (this.disableDepthWrite) {
  26176. var engine = this._scene.getEngine();
  26177. engine.setDepthWrite(this._cachedDepthWriteState);
  26178. }
  26179. };
  26180. Material.prototype.clone = function (name) {
  26181. return null;
  26182. };
  26183. Material.prototype.getBindedMeshes = function () {
  26184. var result = new Array();
  26185. for (var index = 0; index < this._scene.meshes.length; index++) {
  26186. var mesh = this._scene.meshes[index];
  26187. if (mesh.material === this) {
  26188. result.push(mesh);
  26189. }
  26190. }
  26191. return result;
  26192. };
  26193. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26194. // Animations
  26195. this.getScene().stopAnimation(this);
  26196. // Remove from scene
  26197. var index = this._scene.materials.indexOf(this);
  26198. if (index >= 0) {
  26199. this._scene.materials.splice(index, 1);
  26200. }
  26201. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26202. if (forceDisposeEffect && this._effect) {
  26203. this._scene.getEngine()._releaseEffect(this._effect);
  26204. this._effect = null;
  26205. }
  26206. // Remove from meshes
  26207. for (index = 0; index < this._scene.meshes.length; index++) {
  26208. var mesh = this._scene.meshes[index];
  26209. if (mesh.material === this) {
  26210. mesh.material = null;
  26211. }
  26212. }
  26213. // Callback
  26214. this.onDisposeObservable.notifyObservers(this);
  26215. this.onDisposeObservable.clear();
  26216. this.onBindObservable.clear();
  26217. this.onUnBindObservable.clear();
  26218. };
  26219. Material.prototype.serialize = function () {
  26220. return BABYLON.SerializationHelper.Serialize(this);
  26221. };
  26222. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26223. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26224. multiMaterial.id = parsedMultiMaterial.id;
  26225. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26226. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26227. var subMatId = parsedMultiMaterial.materials[matIndex];
  26228. if (subMatId) {
  26229. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26230. }
  26231. else {
  26232. multiMaterial.subMaterials.push(null);
  26233. }
  26234. }
  26235. return multiMaterial;
  26236. };
  26237. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26238. if (!parsedMaterial.customType) {
  26239. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26240. }
  26241. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26242. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26243. ;
  26244. };
  26245. Material._TriangleFillMode = 0;
  26246. Material._WireFrameFillMode = 1;
  26247. Material._PointFillMode = 2;
  26248. Material._ClockWiseSideOrientation = 0;
  26249. Material._CounterClockWiseSideOrientation = 1;
  26250. __decorate([
  26251. BABYLON.serialize()
  26252. ], Material.prototype, "id", void 0);
  26253. __decorate([
  26254. BABYLON.serialize()
  26255. ], Material.prototype, "name", void 0);
  26256. __decorate([
  26257. BABYLON.serialize()
  26258. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26259. __decorate([
  26260. BABYLON.serialize()
  26261. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26262. __decorate([
  26263. BABYLON.serialize()
  26264. ], Material.prototype, "state", void 0);
  26265. __decorate([
  26266. BABYLON.serialize()
  26267. ], Material.prototype, "alpha", void 0);
  26268. __decorate([
  26269. BABYLON.serialize()
  26270. ], Material.prototype, "backFaceCulling", void 0);
  26271. __decorate([
  26272. BABYLON.serialize()
  26273. ], Material.prototype, "sideOrientation", void 0);
  26274. __decorate([
  26275. BABYLON.serialize()
  26276. ], Material.prototype, "alphaMode", void 0);
  26277. __decorate([
  26278. BABYLON.serialize()
  26279. ], Material.prototype, "disableDepthWrite", void 0);
  26280. __decorate([
  26281. BABYLON.serialize()
  26282. ], Material.prototype, "fogEnabled", void 0);
  26283. __decorate([
  26284. BABYLON.serialize()
  26285. ], Material.prototype, "pointSize", void 0);
  26286. __decorate([
  26287. BABYLON.serialize()
  26288. ], Material.prototype, "zOffset", void 0);
  26289. __decorate([
  26290. BABYLON.serialize()
  26291. ], Material.prototype, "wireframe", null);
  26292. __decorate([
  26293. BABYLON.serialize()
  26294. ], Material.prototype, "pointsCloud", null);
  26295. __decorate([
  26296. BABYLON.serialize()
  26297. ], Material.prototype, "fillMode", null);
  26298. return Material;
  26299. }());
  26300. BABYLON.Material = Material;
  26301. })(BABYLON || (BABYLON = {}));
  26302. //# sourceMappingURL=babylon.material.js.map
  26303. var BABYLON;
  26304. (function (BABYLON) {
  26305. var StandardMaterialDefines = (function (_super) {
  26306. __extends(StandardMaterialDefines, _super);
  26307. function StandardMaterialDefines() {
  26308. _super.call(this);
  26309. this.DIFFUSE = false;
  26310. this.AMBIENT = false;
  26311. this.OPACITY = false;
  26312. this.OPACITYRGB = false;
  26313. this.REFLECTION = false;
  26314. this.EMISSIVE = false;
  26315. this.SPECULAR = false;
  26316. this.BUMP = false;
  26317. this.PARALLAX = false;
  26318. this.PARALLAXOCCLUSION = false;
  26319. this.SPECULAROVERALPHA = false;
  26320. this.CLIPPLANE = false;
  26321. this.ALPHATEST = false;
  26322. this.ALPHAFROMDIFFUSE = false;
  26323. this.POINTSIZE = false;
  26324. this.FOG = false;
  26325. this.SPECULARTERM = false;
  26326. this.DIFFUSEFRESNEL = false;
  26327. this.OPACITYFRESNEL = false;
  26328. this.REFLECTIONFRESNEL = false;
  26329. this.REFRACTIONFRESNEL = false;
  26330. this.EMISSIVEFRESNEL = false;
  26331. this.FRESNEL = false;
  26332. this.NORMAL = false;
  26333. this.UV1 = false;
  26334. this.UV2 = false;
  26335. this.VERTEXCOLOR = false;
  26336. this.VERTEXALPHA = false;
  26337. this.NUM_BONE_INFLUENCERS = 0;
  26338. this.BonesPerMesh = 0;
  26339. this.INSTANCES = false;
  26340. this.GLOSSINESS = false;
  26341. this.ROUGHNESS = false;
  26342. this.EMISSIVEASILLUMINATION = false;
  26343. this.LINKEMISSIVEWITHDIFFUSE = false;
  26344. this.REFLECTIONFRESNELFROMSPECULAR = false;
  26345. this.LIGHTMAP = false;
  26346. this.USELIGHTMAPASSHADOWMAP = false;
  26347. this.REFLECTIONMAP_3D = false;
  26348. this.REFLECTIONMAP_SPHERICAL = false;
  26349. this.REFLECTIONMAP_PLANAR = false;
  26350. this.REFLECTIONMAP_CUBIC = false;
  26351. this.REFLECTIONMAP_PROJECTION = false;
  26352. this.REFLECTIONMAP_SKYBOX = false;
  26353. this.REFLECTIONMAP_EXPLICIT = false;
  26354. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26355. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26356. this.INVERTCUBICMAP = false;
  26357. this.LOGARITHMICDEPTH = false;
  26358. this.REFRACTION = false;
  26359. this.REFRACTIONMAP_3D = false;
  26360. this.REFLECTIONOVERALPHA = false;
  26361. this.INVERTNORMALMAPX = false;
  26362. this.INVERTNORMALMAPY = false;
  26363. this.SHADOWFULLFLOAT = false;
  26364. this.CAMERACOLORGRADING = false;
  26365. this.CAMERACOLORCURVES = false;
  26366. this.rebuild();
  26367. }
  26368. return StandardMaterialDefines;
  26369. }(BABYLON.MaterialDefines));
  26370. var StandardMaterial = (function (_super) {
  26371. __extends(StandardMaterial, _super);
  26372. function StandardMaterial(name, scene) {
  26373. var _this = this;
  26374. _super.call(this, name, scene);
  26375. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26376. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26377. this.specularColor = new BABYLON.Color3(1, 1, 1);
  26378. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26379. this.specularPower = 64;
  26380. this.useAlphaFromDiffuseTexture = false;
  26381. this.useEmissiveAsIllumination = false;
  26382. this.linkEmissiveWithDiffuse = false;
  26383. this.useReflectionFresnelFromSpecular = false;
  26384. this.useSpecularOverAlpha = false;
  26385. this.useReflectionOverAlpha = false;
  26386. this.disableLighting = false;
  26387. this.useParallax = false;
  26388. this.useParallaxOcclusion = false;
  26389. this.parallaxScaleBias = 0.05;
  26390. this.roughness = 0;
  26391. this.indexOfRefraction = 0.98;
  26392. this.invertRefractionY = true;
  26393. this.useLightmapAsShadowmap = false;
  26394. this.useGlossinessFromSpecularMapAlpha = false;
  26395. this.maxSimultaneousLights = 4;
  26396. /**
  26397. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26398. */
  26399. this.invertNormalMapX = false;
  26400. /**
  26401. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26402. */
  26403. this.invertNormalMapY = false;
  26404. /**
  26405. * Color Grading 2D Lookup Texture.
  26406. * This allows special effects like sepia, black and white to sixties rendering style.
  26407. */
  26408. this.cameraColorGradingTexture = null;
  26409. /**
  26410. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26411. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26412. * 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;
  26413. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26414. */
  26415. this.cameraColorCurves = null;
  26416. this._renderTargets = new BABYLON.SmartArray(16);
  26417. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26418. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26419. this._defines = new StandardMaterialDefines();
  26420. this._cachedDefines = new StandardMaterialDefines();
  26421. this._cachedDefines.BonesPerMesh = -1;
  26422. this.getRenderTargetTextures = function () {
  26423. _this._renderTargets.reset();
  26424. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  26425. _this._renderTargets.push(_this.reflectionTexture);
  26426. }
  26427. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  26428. _this._renderTargets.push(_this.refractionTexture);
  26429. }
  26430. return _this._renderTargets;
  26431. };
  26432. }
  26433. StandardMaterial.prototype.getClassName = function () {
  26434. return "StandardMaterial";
  26435. };
  26436. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26437. get: function () {
  26438. return this._useLogarithmicDepth;
  26439. },
  26440. set: function (value) {
  26441. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26442. },
  26443. enumerable: true,
  26444. configurable: true
  26445. });
  26446. StandardMaterial.prototype.needAlphaBlending = function () {
  26447. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  26448. };
  26449. StandardMaterial.prototype.needAlphaTesting = function () {
  26450. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  26451. };
  26452. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26453. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  26454. };
  26455. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26456. return this.diffuseTexture;
  26457. };
  26458. // Methods
  26459. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  26460. if (!mesh) {
  26461. return true;
  26462. }
  26463. if (this._defines.INSTANCES !== useInstances) {
  26464. return false;
  26465. }
  26466. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  26467. return true;
  26468. }
  26469. return false;
  26470. };
  26471. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  26472. if (this.isFrozen) {
  26473. if (this._wasPreviouslyReady) {
  26474. return true;
  26475. }
  26476. }
  26477. var scene = this.getScene();
  26478. var engine = scene.getEngine();
  26479. var needUVs = false;
  26480. var needNormals = false;
  26481. this._defines.reset();
  26482. // Lights
  26483. if (scene.lightsEnabled && !this.disableLighting) {
  26484. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26485. }
  26486. if (!this.checkReadyOnEveryCall) {
  26487. if (this._renderId === scene.getRenderId()) {
  26488. if (this._checkCache(scene, mesh, useInstances)) {
  26489. return true;
  26490. }
  26491. }
  26492. }
  26493. // Textures
  26494. if (scene.texturesEnabled) {
  26495. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26496. if (!this.diffuseTexture.isReady()) {
  26497. return false;
  26498. }
  26499. else {
  26500. needUVs = true;
  26501. this._defines.DIFFUSE = true;
  26502. }
  26503. }
  26504. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26505. if (!this.ambientTexture.isReady()) {
  26506. return false;
  26507. }
  26508. else {
  26509. needUVs = true;
  26510. this._defines.AMBIENT = true;
  26511. }
  26512. }
  26513. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26514. if (!this.opacityTexture.isReady()) {
  26515. return false;
  26516. }
  26517. else {
  26518. needUVs = true;
  26519. this._defines.OPACITY = true;
  26520. if (this.opacityTexture.getAlphaFromRGB) {
  26521. this._defines.OPACITYRGB = true;
  26522. }
  26523. }
  26524. }
  26525. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26526. if (!this.reflectionTexture.isReady()) {
  26527. return false;
  26528. }
  26529. else {
  26530. needNormals = true;
  26531. this._defines.REFLECTION = true;
  26532. if (this.roughness > 0) {
  26533. this._defines.ROUGHNESS = true;
  26534. }
  26535. if (this.useReflectionOverAlpha) {
  26536. this._defines.REFLECTIONOVERALPHA = true;
  26537. }
  26538. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  26539. this._defines.INVERTCUBICMAP = true;
  26540. }
  26541. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  26542. switch (this.reflectionTexture.coordinatesMode) {
  26543. case BABYLON.Texture.CUBIC_MODE:
  26544. case BABYLON.Texture.INVCUBIC_MODE:
  26545. this._defines.REFLECTIONMAP_CUBIC = true;
  26546. break;
  26547. case BABYLON.Texture.EXPLICIT_MODE:
  26548. this._defines.REFLECTIONMAP_EXPLICIT = true;
  26549. break;
  26550. case BABYLON.Texture.PLANAR_MODE:
  26551. this._defines.REFLECTIONMAP_PLANAR = true;
  26552. break;
  26553. case BABYLON.Texture.PROJECTION_MODE:
  26554. this._defines.REFLECTIONMAP_PROJECTION = true;
  26555. break;
  26556. case BABYLON.Texture.SKYBOX_MODE:
  26557. this._defines.REFLECTIONMAP_SKYBOX = true;
  26558. break;
  26559. case BABYLON.Texture.SPHERICAL_MODE:
  26560. this._defines.REFLECTIONMAP_SPHERICAL = true;
  26561. break;
  26562. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26563. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  26564. break;
  26565. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26566. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  26567. break;
  26568. }
  26569. }
  26570. }
  26571. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26572. if (!this.emissiveTexture.isReady()) {
  26573. return false;
  26574. }
  26575. else {
  26576. needUVs = true;
  26577. this._defines.EMISSIVE = true;
  26578. }
  26579. }
  26580. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26581. if (!this.lightmapTexture.isReady()) {
  26582. return false;
  26583. }
  26584. else {
  26585. needUVs = true;
  26586. this._defines.LIGHTMAP = true;
  26587. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  26588. }
  26589. }
  26590. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26591. if (!this.specularTexture.isReady()) {
  26592. return false;
  26593. }
  26594. else {
  26595. needUVs = true;
  26596. this._defines.SPECULAR = true;
  26597. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  26598. }
  26599. }
  26600. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26601. if (!this.bumpTexture.isReady()) {
  26602. return false;
  26603. }
  26604. else {
  26605. needUVs = true;
  26606. this._defines.BUMP = true;
  26607. if (this.useParallax) {
  26608. this._defines.PARALLAX = true;
  26609. if (this.useParallaxOcclusion) {
  26610. this._defines.PARALLAXOCCLUSION = true;
  26611. }
  26612. }
  26613. if (this.invertNormalMapX) {
  26614. this._defines.INVERTNORMALMAPX = true;
  26615. }
  26616. if (this.invertNormalMapY) {
  26617. this._defines.INVERTNORMALMAPY = true;
  26618. }
  26619. }
  26620. }
  26621. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26622. if (!this.refractionTexture.isReady()) {
  26623. return false;
  26624. }
  26625. else {
  26626. needUVs = true;
  26627. this._defines.REFRACTION = true;
  26628. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26629. }
  26630. }
  26631. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26632. if (!this.cameraColorGradingTexture.isReady()) {
  26633. return false;
  26634. }
  26635. else {
  26636. this._defines.CAMERACOLORGRADING = true;
  26637. }
  26638. }
  26639. }
  26640. // Effect
  26641. if (scene.clipPlane) {
  26642. this._defines.CLIPPLANE = true;
  26643. }
  26644. if (engine.getAlphaTesting()) {
  26645. this._defines.ALPHATEST = true;
  26646. }
  26647. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26648. this._defines.ALPHAFROMDIFFUSE = true;
  26649. }
  26650. if (this.useEmissiveAsIllumination) {
  26651. this._defines.EMISSIVEASILLUMINATION = true;
  26652. }
  26653. if (this.linkEmissiveWithDiffuse) {
  26654. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26655. }
  26656. if (this.useLogarithmicDepth) {
  26657. this._defines.LOGARITHMICDEPTH = true;
  26658. }
  26659. if (this.cameraColorCurves) {
  26660. this._defines.CAMERACOLORCURVES = true;
  26661. }
  26662. // Point size
  26663. if (this.pointsCloud || scene.forcePointsCloud) {
  26664. this._defines.POINTSIZE = true;
  26665. }
  26666. // Fog
  26667. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26668. this._defines.FOG = true;
  26669. }
  26670. if (StandardMaterial.FresnelEnabled) {
  26671. // Fresnel
  26672. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26673. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26674. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26675. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26676. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26677. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26678. this._defines.DIFFUSEFRESNEL = true;
  26679. }
  26680. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26681. this._defines.OPACITYFRESNEL = true;
  26682. }
  26683. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26684. this._defines.REFLECTIONFRESNEL = true;
  26685. if (this.useReflectionFresnelFromSpecular) {
  26686. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26687. }
  26688. }
  26689. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26690. this._defines.REFRACTIONFRESNEL = true;
  26691. }
  26692. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26693. this._defines.EMISSIVEFRESNEL = true;
  26694. }
  26695. needNormals = true;
  26696. this._defines.FRESNEL = true;
  26697. }
  26698. }
  26699. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26700. this._defines.SPECULAROVERALPHA = true;
  26701. }
  26702. // Attribs
  26703. if (mesh) {
  26704. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26705. this._defines.NORMAL = true;
  26706. }
  26707. if (needUVs) {
  26708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26709. this._defines.UV1 = true;
  26710. }
  26711. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26712. this._defines.UV2 = true;
  26713. }
  26714. }
  26715. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26716. this._defines.VERTEXCOLOR = true;
  26717. if (mesh.hasVertexAlpha) {
  26718. this._defines.VERTEXALPHA = true;
  26719. }
  26720. }
  26721. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26722. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26723. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26724. }
  26725. // Instances
  26726. if (useInstances) {
  26727. this._defines.INSTANCES = true;
  26728. }
  26729. }
  26730. // Get correct effect
  26731. if (!this._defines.isEqual(this._cachedDefines)) {
  26732. this._defines.cloneTo(this._cachedDefines);
  26733. scene.resetCachedMaterial();
  26734. // Fallbacks
  26735. var fallbacks = new BABYLON.EffectFallbacks();
  26736. if (this._defines.REFLECTION) {
  26737. fallbacks.addFallback(0, "REFLECTION");
  26738. }
  26739. if (this._defines.SPECULAR) {
  26740. fallbacks.addFallback(0, "SPECULAR");
  26741. }
  26742. if (this._defines.BUMP) {
  26743. fallbacks.addFallback(0, "BUMP");
  26744. }
  26745. if (this._defines.PARALLAX) {
  26746. fallbacks.addFallback(1, "PARALLAX");
  26747. }
  26748. if (this._defines.PARALLAXOCCLUSION) {
  26749. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26750. }
  26751. if (this._defines.SPECULAROVERALPHA) {
  26752. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26753. }
  26754. if (this._defines.FOG) {
  26755. fallbacks.addFallback(1, "FOG");
  26756. }
  26757. if (this._defines.POINTSIZE) {
  26758. fallbacks.addFallback(0, "POINTSIZE");
  26759. }
  26760. if (this._defines.LOGARITHMICDEPTH) {
  26761. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26762. }
  26763. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26764. if (this._defines.SPECULARTERM) {
  26765. fallbacks.addFallback(0, "SPECULARTERM");
  26766. }
  26767. if (this._defines.DIFFUSEFRESNEL) {
  26768. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26769. }
  26770. if (this._defines.OPACITYFRESNEL) {
  26771. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26772. }
  26773. if (this._defines.REFLECTIONFRESNEL) {
  26774. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26775. }
  26776. if (this._defines.EMISSIVEFRESNEL) {
  26777. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26778. }
  26779. if (this._defines.FRESNEL) {
  26780. fallbacks.addFallback(4, "FRESNEL");
  26781. }
  26782. //Attributes
  26783. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26784. if (this._defines.NORMAL) {
  26785. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26786. }
  26787. if (this._defines.UV1) {
  26788. attribs.push(BABYLON.VertexBuffer.UVKind);
  26789. }
  26790. if (this._defines.UV2) {
  26791. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26792. }
  26793. if (this._defines.VERTEXCOLOR) {
  26794. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26795. }
  26796. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26797. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26798. var shaderName = "default";
  26799. var join = this._defines.toString();
  26800. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26801. "vFogInfos", "vFogColor", "pointSize",
  26802. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26803. "mBones",
  26804. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26805. "depthValues",
  26806. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26807. "logarithmicDepthConstant"
  26808. ];
  26809. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26810. if (this._defines.CAMERACOLORCURVES) {
  26811. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26812. }
  26813. if (this._defines.CAMERACOLORGRADING) {
  26814. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26815. }
  26816. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26817. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26818. }
  26819. if (!this._effect.isReady()) {
  26820. return false;
  26821. }
  26822. this._renderId = scene.getRenderId();
  26823. this._wasPreviouslyReady = true;
  26824. if (mesh) {
  26825. if (!mesh._materialDefines) {
  26826. mesh._materialDefines = new StandardMaterialDefines();
  26827. }
  26828. this._defines.cloneTo(mesh._materialDefines);
  26829. }
  26830. return true;
  26831. };
  26832. StandardMaterial.prototype.unbind = function () {
  26833. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26834. this._effect.setTexture("reflection2DSampler", null);
  26835. }
  26836. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26837. this._effect.setTexture("refraction2DSampler", null);
  26838. }
  26839. _super.prototype.unbind.call(this);
  26840. };
  26841. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26842. this._effect.setMatrix("world", world);
  26843. };
  26844. StandardMaterial.prototype.bind = function (world, mesh) {
  26845. var scene = this.getScene();
  26846. // Matrices
  26847. this.bindOnlyWorldMatrix(world);
  26848. // Bones
  26849. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26850. if (scene.getCachedMaterial() !== this) {
  26851. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26852. if (StandardMaterial.FresnelEnabled) {
  26853. // Fresnel
  26854. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26855. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26856. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26857. }
  26858. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26859. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26860. }
  26861. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26862. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26863. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26864. }
  26865. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26866. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26867. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26868. }
  26869. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26870. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26871. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26872. }
  26873. }
  26874. // Textures
  26875. if (scene.texturesEnabled) {
  26876. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26877. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26878. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26879. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26880. }
  26881. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26882. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26883. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26884. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26885. }
  26886. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26887. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26888. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26889. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26890. }
  26891. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26892. if (this.reflectionTexture.isCube) {
  26893. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26894. }
  26895. else {
  26896. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26897. }
  26898. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26899. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26900. }
  26901. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26902. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26903. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26904. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26905. }
  26906. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26907. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26908. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26909. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26910. }
  26911. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26912. this._effect.setTexture("specularSampler", this.specularTexture);
  26913. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26914. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26915. }
  26916. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26917. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26918. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26919. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26920. }
  26921. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26922. var depth = 1.0;
  26923. if (this.refractionTexture.isCube) {
  26924. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26925. }
  26926. else {
  26927. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26928. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26929. if (this.refractionTexture.depth) {
  26930. depth = this.refractionTexture.depth;
  26931. }
  26932. }
  26933. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26934. }
  26935. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26936. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26937. }
  26938. }
  26939. // Clip plane
  26940. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26941. // Point size
  26942. if (this.pointsCloud) {
  26943. this._effect.setFloat("pointSize", this.pointSize);
  26944. }
  26945. // Colors
  26946. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26947. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26948. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26949. if (this._defines.SPECULARTERM) {
  26950. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26951. }
  26952. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26953. }
  26954. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26955. // Diffuse
  26956. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26957. // Lights
  26958. if (scene.lightsEnabled && !this.disableLighting) {
  26959. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26960. }
  26961. // View
  26962. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26963. this._effect.setMatrix("view", scene.getViewMatrix());
  26964. }
  26965. // Fog
  26966. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26967. // Log. depth
  26968. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26969. // Color Curves
  26970. if (this.cameraColorCurves) {
  26971. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26972. }
  26973. }
  26974. _super.prototype.bind.call(this, world, mesh);
  26975. };
  26976. StandardMaterial.prototype.getAnimatables = function () {
  26977. var results = [];
  26978. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26979. results.push(this.diffuseTexture);
  26980. }
  26981. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26982. results.push(this.ambientTexture);
  26983. }
  26984. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26985. results.push(this.opacityTexture);
  26986. }
  26987. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26988. results.push(this.reflectionTexture);
  26989. }
  26990. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26991. results.push(this.emissiveTexture);
  26992. }
  26993. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26994. results.push(this.specularTexture);
  26995. }
  26996. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26997. results.push(this.bumpTexture);
  26998. }
  26999. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  27000. results.push(this.lightmapTexture);
  27001. }
  27002. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  27003. results.push(this.refractionTexture);
  27004. }
  27005. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  27006. results.push(this.cameraColorGradingTexture);
  27007. }
  27008. return results;
  27009. };
  27010. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27011. if (forceDisposeTextures) {
  27012. if (this.diffuseTexture) {
  27013. this.diffuseTexture.dispose();
  27014. }
  27015. if (this.ambientTexture) {
  27016. this.ambientTexture.dispose();
  27017. }
  27018. if (this.opacityTexture) {
  27019. this.opacityTexture.dispose();
  27020. }
  27021. if (this.reflectionTexture) {
  27022. this.reflectionTexture.dispose();
  27023. }
  27024. if (this.emissiveTexture) {
  27025. this.emissiveTexture.dispose();
  27026. }
  27027. if (this.specularTexture) {
  27028. this.specularTexture.dispose();
  27029. }
  27030. if (this.bumpTexture) {
  27031. this.bumpTexture.dispose();
  27032. }
  27033. if (this.lightmapTexture) {
  27034. this.lightmapTexture.dispose();
  27035. }
  27036. if (this.refractionTexture) {
  27037. this.refractionTexture.dispose();
  27038. }
  27039. if (this.cameraColorGradingTexture) {
  27040. this.cameraColorGradingTexture.dispose();
  27041. }
  27042. }
  27043. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27044. };
  27045. StandardMaterial.prototype.clone = function (name) {
  27046. var _this = this;
  27047. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27048. };
  27049. StandardMaterial.prototype.serialize = function () {
  27050. return BABYLON.SerializationHelper.Serialize(this);
  27051. };
  27052. // Statics
  27053. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27054. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27055. };
  27056. // Flags used to enable or disable a type of texture for all Standard Materials
  27057. StandardMaterial.DiffuseTextureEnabled = true;
  27058. StandardMaterial.AmbientTextureEnabled = true;
  27059. StandardMaterial.OpacityTextureEnabled = true;
  27060. StandardMaterial.ReflectionTextureEnabled = true;
  27061. StandardMaterial.EmissiveTextureEnabled = true;
  27062. StandardMaterial.SpecularTextureEnabled = true;
  27063. StandardMaterial.BumpTextureEnabled = true;
  27064. StandardMaterial.FresnelEnabled = true;
  27065. StandardMaterial.LightmapTextureEnabled = true;
  27066. StandardMaterial.RefractionTextureEnabled = true;
  27067. StandardMaterial.ColorGradingTextureEnabled = true;
  27068. __decorate([
  27069. BABYLON.serializeAsTexture()
  27070. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27071. __decorate([
  27072. BABYLON.serializeAsTexture()
  27073. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27074. __decorate([
  27075. BABYLON.serializeAsTexture()
  27076. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27077. __decorate([
  27078. BABYLON.serializeAsTexture()
  27079. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27080. __decorate([
  27081. BABYLON.serializeAsTexture()
  27082. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27083. __decorate([
  27084. BABYLON.serializeAsTexture()
  27085. ], StandardMaterial.prototype, "specularTexture", void 0);
  27086. __decorate([
  27087. BABYLON.serializeAsTexture()
  27088. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27089. __decorate([
  27090. BABYLON.serializeAsTexture()
  27091. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27092. __decorate([
  27093. BABYLON.serializeAsTexture()
  27094. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27095. __decorate([
  27096. BABYLON.serializeAsColor3("ambient")
  27097. ], StandardMaterial.prototype, "ambientColor", void 0);
  27098. __decorate([
  27099. BABYLON.serializeAsColor3("diffuse")
  27100. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27101. __decorate([
  27102. BABYLON.serializeAsColor3("specular")
  27103. ], StandardMaterial.prototype, "specularColor", void 0);
  27104. __decorate([
  27105. BABYLON.serializeAsColor3("emissive")
  27106. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27107. __decorate([
  27108. BABYLON.serialize()
  27109. ], StandardMaterial.prototype, "specularPower", void 0);
  27110. __decorate([
  27111. BABYLON.serialize()
  27112. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27113. __decorate([
  27114. BABYLON.serialize()
  27115. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27116. __decorate([
  27117. BABYLON.serialize()
  27118. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27119. __decorate([
  27120. BABYLON.serialize()
  27121. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27122. __decorate([
  27123. BABYLON.serialize()
  27124. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27125. __decorate([
  27126. BABYLON.serialize()
  27127. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27128. __decorate([
  27129. BABYLON.serialize()
  27130. ], StandardMaterial.prototype, "disableLighting", void 0);
  27131. __decorate([
  27132. BABYLON.serialize()
  27133. ], StandardMaterial.prototype, "useParallax", void 0);
  27134. __decorate([
  27135. BABYLON.serialize()
  27136. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27137. __decorate([
  27138. BABYLON.serialize()
  27139. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27140. __decorate([
  27141. BABYLON.serialize()
  27142. ], StandardMaterial.prototype, "roughness", void 0);
  27143. __decorate([
  27144. BABYLON.serialize()
  27145. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27146. __decorate([
  27147. BABYLON.serialize()
  27148. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27149. __decorate([
  27150. BABYLON.serialize()
  27151. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27152. __decorate([
  27153. BABYLON.serializeAsFresnelParameters()
  27154. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27155. __decorate([
  27156. BABYLON.serializeAsFresnelParameters()
  27157. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27158. __decorate([
  27159. BABYLON.serializeAsFresnelParameters()
  27160. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27161. __decorate([
  27162. BABYLON.serializeAsFresnelParameters()
  27163. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27164. __decorate([
  27165. BABYLON.serializeAsFresnelParameters()
  27166. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27167. __decorate([
  27168. BABYLON.serialize()
  27169. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27170. __decorate([
  27171. BABYLON.serialize()
  27172. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27173. __decorate([
  27174. BABYLON.serialize()
  27175. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27176. __decorate([
  27177. BABYLON.serialize()
  27178. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27179. __decorate([
  27180. BABYLON.serializeAsTexture()
  27181. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27182. __decorate([
  27183. BABYLON.serializeAsColorCurves()
  27184. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27185. __decorate([
  27186. BABYLON.serialize()
  27187. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27188. return StandardMaterial;
  27189. }(BABYLON.Material));
  27190. BABYLON.StandardMaterial = StandardMaterial;
  27191. })(BABYLON || (BABYLON = {}));
  27192. //# sourceMappingURL=babylon.standardMaterial.js.map
  27193. var BABYLON;
  27194. (function (BABYLON) {
  27195. var MultiMaterial = (function (_super) {
  27196. __extends(MultiMaterial, _super);
  27197. function MultiMaterial(name, scene) {
  27198. _super.call(this, name, scene, true);
  27199. this.subMaterials = new Array();
  27200. scene.multiMaterials.push(this);
  27201. }
  27202. // Properties
  27203. MultiMaterial.prototype.getSubMaterial = function (index) {
  27204. if (index < 0 || index >= this.subMaterials.length) {
  27205. return this.getScene().defaultMaterial;
  27206. }
  27207. return this.subMaterials[index];
  27208. };
  27209. // Methods
  27210. MultiMaterial.prototype.getClassName = function () {
  27211. return "MultiMaterial";
  27212. };
  27213. MultiMaterial.prototype.isReady = function (mesh) {
  27214. for (var index = 0; index < this.subMaterials.length; index++) {
  27215. var subMaterial = this.subMaterials[index];
  27216. if (subMaterial) {
  27217. if (!this.subMaterials[index].isReady(mesh)) {
  27218. return false;
  27219. }
  27220. }
  27221. }
  27222. return true;
  27223. };
  27224. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27225. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27226. for (var index = 0; index < this.subMaterials.length; index++) {
  27227. var subMaterial = null;
  27228. if (cloneChildren) {
  27229. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27230. }
  27231. else {
  27232. subMaterial = this.subMaterials[index];
  27233. }
  27234. newMultiMaterial.subMaterials.push(subMaterial);
  27235. }
  27236. return newMultiMaterial;
  27237. };
  27238. MultiMaterial.prototype.serialize = function () {
  27239. var serializationObject = {};
  27240. serializationObject.name = this.name;
  27241. serializationObject.id = this.id;
  27242. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27243. serializationObject.materials = [];
  27244. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27245. var subMat = this.subMaterials[matIndex];
  27246. if (subMat) {
  27247. serializationObject.materials.push(subMat.id);
  27248. }
  27249. else {
  27250. serializationObject.materials.push(null);
  27251. }
  27252. }
  27253. return serializationObject;
  27254. };
  27255. return MultiMaterial;
  27256. }(BABYLON.Material));
  27257. BABYLON.MultiMaterial = MultiMaterial;
  27258. })(BABYLON || (BABYLON = {}));
  27259. //# sourceMappingURL=babylon.multiMaterial.js.map
  27260. var BABYLON;
  27261. (function (BABYLON) {
  27262. var SceneLoader = (function () {
  27263. function SceneLoader() {
  27264. }
  27265. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27266. get: function () {
  27267. return 0;
  27268. },
  27269. enumerable: true,
  27270. configurable: true
  27271. });
  27272. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27273. get: function () {
  27274. return 1;
  27275. },
  27276. enumerable: true,
  27277. configurable: true
  27278. });
  27279. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  27280. get: function () {
  27281. return 2;
  27282. },
  27283. enumerable: true,
  27284. configurable: true
  27285. });
  27286. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  27287. get: function () {
  27288. return 3;
  27289. },
  27290. enumerable: true,
  27291. configurable: true
  27292. });
  27293. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  27294. get: function () {
  27295. return SceneLoader._ForceFullSceneLoadingForIncremental;
  27296. },
  27297. set: function (value) {
  27298. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  27299. },
  27300. enumerable: true,
  27301. configurable: true
  27302. });
  27303. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  27304. get: function () {
  27305. return SceneLoader._ShowLoadingScreen;
  27306. },
  27307. set: function (value) {
  27308. SceneLoader._ShowLoadingScreen = value;
  27309. },
  27310. enumerable: true,
  27311. configurable: true
  27312. });
  27313. Object.defineProperty(SceneLoader, "loggingLevel", {
  27314. get: function () {
  27315. return SceneLoader._loggingLevel;
  27316. },
  27317. set: function (value) {
  27318. SceneLoader._loggingLevel = value;
  27319. },
  27320. enumerable: true,
  27321. configurable: true
  27322. });
  27323. SceneLoader._getDefaultPlugin = function () {
  27324. return SceneLoader._registeredPlugins[".babylon"];
  27325. };
  27326. SceneLoader._getPluginForExtension = function (extension) {
  27327. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  27328. if (registeredPlugin) {
  27329. return registeredPlugin;
  27330. }
  27331. return SceneLoader._getDefaultPlugin();
  27332. };
  27333. SceneLoader._getPluginForFilename = function (sceneFilename) {
  27334. if (sceneFilename.name) {
  27335. sceneFilename = sceneFilename.name;
  27336. }
  27337. var dotPosition = sceneFilename.lastIndexOf(".");
  27338. var queryStringPosition = sceneFilename.indexOf("?");
  27339. if (queryStringPosition === -1) {
  27340. queryStringPosition = sceneFilename.length;
  27341. }
  27342. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  27343. return SceneLoader._getPluginForExtension(extension);
  27344. };
  27345. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  27346. SceneLoader._getDirectLoad = function (sceneFilename) {
  27347. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  27348. return sceneFilename.substr(5);
  27349. }
  27350. return null;
  27351. };
  27352. // Public functions
  27353. SceneLoader.GetPluginForExtension = function (extension) {
  27354. return SceneLoader._getPluginForExtension(extension).plugin;
  27355. };
  27356. SceneLoader.RegisterPlugin = function (plugin) {
  27357. if (typeof plugin.extensions === "string") {
  27358. var extension = plugin.extensions;
  27359. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27360. plugin: plugin,
  27361. isBinary: false
  27362. };
  27363. }
  27364. else {
  27365. var extensions = plugin.extensions;
  27366. Object.keys(extensions).forEach(function (extension) {
  27367. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27368. plugin: plugin,
  27369. isBinary: extensions[extension].isBinary
  27370. };
  27371. });
  27372. }
  27373. };
  27374. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27375. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27376. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27377. return;
  27378. }
  27379. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27380. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27381. return;
  27382. }
  27383. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27384. var loadingToken = {};
  27385. scene._addPendingData(loadingToken);
  27386. var manifestChecked = function (success) {
  27387. scene.database = database;
  27388. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27389. var plugin = registeredPlugin.plugin;
  27390. var useArrayBuffer = registeredPlugin.isBinary;
  27391. var importMeshFromData = function (data) {
  27392. var meshes = [];
  27393. var particleSystems = [];
  27394. var skeletons = [];
  27395. try {
  27396. if (plugin.importMesh) {
  27397. var syncedPlugin = plugin;
  27398. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  27399. if (onerror) {
  27400. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27401. }
  27402. scene._removePendingData(loadingToken);
  27403. return;
  27404. }
  27405. if (onsuccess) {
  27406. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27407. onsuccess(meshes, particleSystems, skeletons);
  27408. scene._removePendingData(loadingToken);
  27409. }
  27410. }
  27411. else {
  27412. var asyncedPlugin = plugin;
  27413. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  27414. if (onsuccess) {
  27415. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27416. onsuccess(meshes, particleSystems, skeletons);
  27417. scene._removePendingData(loadingToken);
  27418. }
  27419. }, function () {
  27420. if (onerror) {
  27421. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27422. }
  27423. scene._removePendingData(loadingToken);
  27424. });
  27425. }
  27426. }
  27427. catch (e) {
  27428. if (onerror) {
  27429. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  27430. }
  27431. scene._removePendingData(loadingToken);
  27432. }
  27433. };
  27434. if (directLoad) {
  27435. importMeshFromData(directLoad);
  27436. return;
  27437. }
  27438. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  27439. importMeshFromData(data);
  27440. }, progressCallBack, database, useArrayBuffer);
  27441. };
  27442. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  27443. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27444. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27445. }
  27446. else {
  27447. // If the scene is a data stream or offline support is not enabled, it's a direct load
  27448. manifestChecked(true);
  27449. }
  27450. };
  27451. /**
  27452. * Load a scene
  27453. * @param rootUrl a string that defines the root url for scene and resources
  27454. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27455. * @param engine is the instance of BABYLON.Engine to use to create the scene
  27456. */
  27457. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  27458. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  27459. };
  27460. /**
  27461. * Append a scene
  27462. * @param rootUrl a string that defines the root url for scene and resources
  27463. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27464. * @param scene is the instance of BABYLON.Scene to append to
  27465. */
  27466. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27467. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27468. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27469. return;
  27470. }
  27471. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27472. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27473. var plugin = registeredPlugin.plugin;
  27474. var useArrayBuffer = registeredPlugin.isBinary;
  27475. var database;
  27476. var loadingToken = {};
  27477. scene._addPendingData(loadingToken);
  27478. if (SceneLoader.ShowLoadingScreen) {
  27479. scene.getEngine().displayLoadingUI();
  27480. }
  27481. var loadSceneFromData = function (data) {
  27482. scene.database = database;
  27483. if (plugin.load) {
  27484. var syncedPlugin = plugin;
  27485. if (!syncedPlugin.load(scene, data, rootUrl)) {
  27486. if (onerror) {
  27487. onerror(scene);
  27488. }
  27489. scene._removePendingData(loadingToken);
  27490. scene.getEngine().hideLoadingUI();
  27491. return;
  27492. }
  27493. if (onsuccess) {
  27494. onsuccess(scene);
  27495. }
  27496. scene._removePendingData(loadingToken);
  27497. }
  27498. else {
  27499. var asyncedPlugin = plugin;
  27500. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  27501. if (onsuccess) {
  27502. onsuccess(scene);
  27503. }
  27504. scene._removePendingData(loadingToken);
  27505. }, function () {
  27506. if (onerror) {
  27507. onerror(scene);
  27508. }
  27509. scene._removePendingData(loadingToken);
  27510. scene.getEngine().hideLoadingUI();
  27511. });
  27512. }
  27513. if (SceneLoader.ShowLoadingScreen) {
  27514. scene.executeWhenReady(function () {
  27515. scene.getEngine().hideLoadingUI();
  27516. });
  27517. }
  27518. };
  27519. var manifestChecked = function (success) {
  27520. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  27521. };
  27522. if (directLoad) {
  27523. loadSceneFromData(directLoad);
  27524. return;
  27525. }
  27526. if (rootUrl.indexOf("file:") === -1) {
  27527. if (scene.getEngine().enableOfflineSupport) {
  27528. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27529. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27530. }
  27531. else {
  27532. manifestChecked(true);
  27533. }
  27534. }
  27535. else {
  27536. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  27537. }
  27538. };
  27539. // Flags
  27540. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  27541. SceneLoader._ShowLoadingScreen = true;
  27542. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  27543. // Members
  27544. SceneLoader._registeredPlugins = {};
  27545. return SceneLoader;
  27546. }());
  27547. BABYLON.SceneLoader = SceneLoader;
  27548. ;
  27549. })(BABYLON || (BABYLON = {}));
  27550. //# sourceMappingURL=babylon.sceneLoader.js.map
  27551. var BABYLON;
  27552. (function (BABYLON) {
  27553. var Internals;
  27554. (function (Internals) {
  27555. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  27556. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27557. var parsedMaterial = parsedData.materials[index];
  27558. if (parsedMaterial.id === id) {
  27559. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27560. }
  27561. }
  27562. return null;
  27563. };
  27564. var isDescendantOf = function (mesh, names, hierarchyIds) {
  27565. names = (names instanceof Array) ? names : [names];
  27566. for (var i in names) {
  27567. if (mesh.name === names[i]) {
  27568. hierarchyIds.push(mesh.id);
  27569. return true;
  27570. }
  27571. }
  27572. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  27573. hierarchyIds.push(mesh.id);
  27574. return true;
  27575. }
  27576. return false;
  27577. };
  27578. var logOperation = function (operation, producer) {
  27579. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  27580. };
  27581. BABYLON.SceneLoader.RegisterPlugin({
  27582. extensions: ".babylon",
  27583. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  27584. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27585. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27586. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27587. // and avoid problems with multiple concurrent .babylon loads.
  27588. var log = "importMesh has failed JSON parse";
  27589. try {
  27590. var parsedData = JSON.parse(data);
  27591. log = "";
  27592. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27593. var loadedSkeletonsIds = [];
  27594. var loadedMaterialsIds = [];
  27595. var hierarchyIds = [];
  27596. var index;
  27597. var cache;
  27598. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27599. var parsedMesh = parsedData.meshes[index];
  27600. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  27601. if (meshesNames instanceof Array) {
  27602. // Remove found mesh name from list.
  27603. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  27604. }
  27605. //Geometry?
  27606. if (parsedMesh.geometryId) {
  27607. //does the file contain geometries?
  27608. if (parsedData.geometries) {
  27609. //find the correct geometry and add it to the scene
  27610. var found = false;
  27611. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  27612. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  27613. return;
  27614. }
  27615. else {
  27616. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  27617. if (parsedGeometryData.id === parsedMesh.geometryId) {
  27618. switch (geometryType) {
  27619. case "boxes":
  27620. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  27621. break;
  27622. case "spheres":
  27623. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  27624. break;
  27625. case "cylinders":
  27626. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27627. break;
  27628. case "toruses":
  27629. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27630. break;
  27631. case "grounds":
  27632. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27633. break;
  27634. case "planes":
  27635. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27636. break;
  27637. case "torusKnots":
  27638. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27639. break;
  27640. case "vertexData":
  27641. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27642. break;
  27643. }
  27644. found = true;
  27645. }
  27646. });
  27647. }
  27648. });
  27649. if (!found) {
  27650. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27651. }
  27652. }
  27653. }
  27654. // Material ?
  27655. if (parsedMesh.materialId) {
  27656. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27657. if (!materialFound && parsedData.multiMaterials) {
  27658. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27659. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27660. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27661. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27662. var subMatId = parsedMultiMaterial.materials[matIndex];
  27663. loadedMaterialsIds.push(subMatId);
  27664. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27665. log += "\n\tMaterial " + mat.toString(fullDetails);
  27666. }
  27667. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27668. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27669. materialFound = true;
  27670. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27671. break;
  27672. }
  27673. }
  27674. }
  27675. if (!materialFound) {
  27676. loadedMaterialsIds.push(parsedMesh.materialId);
  27677. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27678. if (!mat) {
  27679. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27680. }
  27681. else {
  27682. log += "\n\tMaterial " + mat.toString(fullDetails);
  27683. }
  27684. }
  27685. }
  27686. // Skeleton ?
  27687. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27688. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27689. if (!skeletonAlreadyLoaded) {
  27690. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27691. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27692. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27693. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27694. skeletons.push(skeleton);
  27695. loadedSkeletonsIds.push(parsedSkeleton.id);
  27696. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27697. }
  27698. }
  27699. }
  27700. }
  27701. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27702. meshes.push(mesh);
  27703. log += "\n\tMesh " + mesh.toString(fullDetails);
  27704. }
  27705. }
  27706. // Connecting parents
  27707. var currentMesh;
  27708. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27709. currentMesh = scene.meshes[index];
  27710. if (currentMesh._waitingParentId) {
  27711. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27712. currentMesh._waitingParentId = undefined;
  27713. }
  27714. }
  27715. // freeze and compute world matrix application
  27716. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27717. currentMesh = scene.meshes[index];
  27718. if (currentMesh._waitingFreezeWorldMatrix) {
  27719. currentMesh.freezeWorldMatrix();
  27720. currentMesh._waitingFreezeWorldMatrix = undefined;
  27721. }
  27722. else {
  27723. currentMesh.computeWorldMatrix(true);
  27724. }
  27725. }
  27726. // Particles
  27727. if (parsedData.particleSystems) {
  27728. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27729. var parsedParticleSystem = parsedData.particleSystems[index];
  27730. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27731. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27732. }
  27733. }
  27734. }
  27735. return true;
  27736. }
  27737. catch (err) {
  27738. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27739. log = null;
  27740. throw err;
  27741. }
  27742. finally {
  27743. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27744. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27745. }
  27746. }
  27747. },
  27748. load: function (scene, data, rootUrl) {
  27749. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27750. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27751. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27752. // and avoid problems with multiple concurrent .babylon loads.
  27753. var log = "importScene has failed JSON parse";
  27754. try {
  27755. var parsedData = JSON.parse(data);
  27756. log = "";
  27757. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27758. // Scene
  27759. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27760. scene.autoClear = parsedData.autoClear;
  27761. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27762. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27763. if (parsedData.gravity) {
  27764. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27765. }
  27766. // Fog
  27767. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27768. scene.fogMode = parsedData.fogMode;
  27769. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27770. scene.fogStart = parsedData.fogStart;
  27771. scene.fogEnd = parsedData.fogEnd;
  27772. scene.fogDensity = parsedData.fogDensity;
  27773. log += "\tFog mode for scene: ";
  27774. switch (scene.fogMode) {
  27775. // getters not compiling, so using hardcoded
  27776. case 1:
  27777. log += "exp\n";
  27778. break;
  27779. case 2:
  27780. log += "exp2\n";
  27781. break;
  27782. case 3:
  27783. log += "linear\n";
  27784. break;
  27785. }
  27786. }
  27787. //Physics
  27788. if (parsedData.physicsEnabled) {
  27789. var physicsPlugin;
  27790. if (parsedData.physicsEngine === "cannon") {
  27791. physicsPlugin = new BABYLON.CannonJSPlugin();
  27792. }
  27793. else if (parsedData.physicsEngine === "oimo") {
  27794. physicsPlugin = new BABYLON.OimoJSPlugin();
  27795. }
  27796. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27797. //else - default engine, which is currently oimo
  27798. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27799. scene.enablePhysics(physicsGravity, physicsPlugin);
  27800. }
  27801. // Metadata
  27802. if (parsedData.metadata !== undefined) {
  27803. scene.metadata = parsedData.metadata;
  27804. }
  27805. //collisions, if defined. otherwise, default is true
  27806. if (parsedData.collisionsEnabled != undefined) {
  27807. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27808. }
  27809. scene.workerCollisions = !!parsedData.workerCollisions;
  27810. var index;
  27811. var cache;
  27812. // Lights
  27813. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27814. var parsedLight = parsedData.lights[index];
  27815. var light = BABYLON.Light.Parse(parsedLight, scene);
  27816. log += (index === 0 ? "\n\tLights:" : "");
  27817. log += "\n\t\t" + light.toString(fullDetails);
  27818. }
  27819. // Animations
  27820. if (parsedData.animations) {
  27821. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27822. var parsedAnimation = parsedData.animations[index];
  27823. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27824. scene.animations.push(animation);
  27825. log += (index === 0 ? "\n\tAnimations:" : "");
  27826. log += "\n\t\t" + animation.toString(fullDetails);
  27827. }
  27828. }
  27829. if (parsedData.autoAnimate) {
  27830. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27831. }
  27832. // Materials
  27833. if (parsedData.materials) {
  27834. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27835. var parsedMaterial = parsedData.materials[index];
  27836. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27837. log += (index === 0 ? "\n\tMaterials:" : "");
  27838. log += "\n\t\t" + mat.toString(fullDetails);
  27839. }
  27840. }
  27841. if (parsedData.multiMaterials) {
  27842. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27843. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27844. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27845. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27846. log += "\n\t\t" + mmat.toString(fullDetails);
  27847. }
  27848. }
  27849. // Skeletons
  27850. if (parsedData.skeletons) {
  27851. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27852. var parsedSkeleton = parsedData.skeletons[index];
  27853. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27854. log += (index === 0 ? "\n\tSkeletons:" : "");
  27855. log += "\n\t\t" + skeleton.toString(fullDetails);
  27856. }
  27857. }
  27858. // Geometries
  27859. var geometries = parsedData.geometries;
  27860. if (geometries) {
  27861. // Boxes
  27862. var boxes = geometries.boxes;
  27863. if (boxes) {
  27864. for (index = 0, cache = boxes.length; index < cache; index++) {
  27865. var parsedBox = boxes[index];
  27866. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27867. }
  27868. }
  27869. // Spheres
  27870. var spheres = geometries.spheres;
  27871. if (spheres) {
  27872. for (index = 0, cache = spheres.length; index < cache; index++) {
  27873. var parsedSphere = spheres[index];
  27874. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27875. }
  27876. }
  27877. // Cylinders
  27878. var cylinders = geometries.cylinders;
  27879. if (cylinders) {
  27880. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27881. var parsedCylinder = cylinders[index];
  27882. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27883. }
  27884. }
  27885. // Toruses
  27886. var toruses = geometries.toruses;
  27887. if (toruses) {
  27888. for (index = 0, cache = toruses.length; index < cache; index++) {
  27889. var parsedTorus = toruses[index];
  27890. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27891. }
  27892. }
  27893. // Grounds
  27894. var grounds = geometries.grounds;
  27895. if (grounds) {
  27896. for (index = 0, cache = grounds.length; index < cache; index++) {
  27897. var parsedGround = grounds[index];
  27898. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27899. }
  27900. }
  27901. // Planes
  27902. var planes = geometries.planes;
  27903. if (planes) {
  27904. for (index = 0, cache = planes.length; index < cache; index++) {
  27905. var parsedPlane = planes[index];
  27906. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27907. }
  27908. }
  27909. // TorusKnots
  27910. var torusKnots = geometries.torusKnots;
  27911. if (torusKnots) {
  27912. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27913. var parsedTorusKnot = torusKnots[index];
  27914. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27915. }
  27916. }
  27917. // VertexData
  27918. var vertexData = geometries.vertexData;
  27919. if (vertexData) {
  27920. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27921. var parsedVertexData = vertexData[index];
  27922. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27923. }
  27924. }
  27925. }
  27926. // Meshes
  27927. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27928. var parsedMesh = parsedData.meshes[index];
  27929. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27930. log += (index === 0 ? "\n\tMeshes:" : "");
  27931. log += "\n\t\t" + mesh.toString(fullDetails);
  27932. }
  27933. // Cameras
  27934. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27935. var parsedCamera = parsedData.cameras[index];
  27936. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27937. log += (index === 0 ? "\n\tCameras:" : "");
  27938. log += "\n\t\t" + camera.toString(fullDetails);
  27939. }
  27940. if (parsedData.activeCameraID) {
  27941. scene.setActiveCameraByID(parsedData.activeCameraID);
  27942. }
  27943. // Browsing all the graph to connect the dots
  27944. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27945. var camera = scene.cameras[index];
  27946. if (camera._waitingParentId) {
  27947. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27948. camera._waitingParentId = undefined;
  27949. }
  27950. }
  27951. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27952. var light = scene.lights[index];
  27953. if (light._waitingParentId) {
  27954. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27955. light._waitingParentId = undefined;
  27956. }
  27957. }
  27958. // Sounds
  27959. var loadedSounds = [];
  27960. var loadedSound;
  27961. if (BABYLON.AudioEngine && parsedData.sounds) {
  27962. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27963. var parsedSound = parsedData.sounds[index];
  27964. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27965. if (!parsedSound.url)
  27966. parsedSound.url = parsedSound.name;
  27967. if (!loadedSounds[parsedSound.url]) {
  27968. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27969. loadedSounds[parsedSound.url] = loadedSound;
  27970. }
  27971. else {
  27972. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27973. }
  27974. }
  27975. else {
  27976. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27977. }
  27978. }
  27979. }
  27980. loadedSounds = [];
  27981. // Connect parents & children and parse actions
  27982. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27983. var mesh = scene.meshes[index];
  27984. if (mesh._waitingParentId) {
  27985. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27986. mesh._waitingParentId = undefined;
  27987. }
  27988. if (mesh._waitingActions) {
  27989. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27990. mesh._waitingActions = undefined;
  27991. }
  27992. }
  27993. // freeze world matrix application
  27994. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27995. var currentMesh = scene.meshes[index];
  27996. if (currentMesh._waitingFreezeWorldMatrix) {
  27997. currentMesh.freezeWorldMatrix();
  27998. currentMesh._waitingFreezeWorldMatrix = undefined;
  27999. }
  28000. else {
  28001. currentMesh.computeWorldMatrix(true);
  28002. }
  28003. }
  28004. // Particles Systems
  28005. if (parsedData.particleSystems) {
  28006. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28007. var parsedParticleSystem = parsedData.particleSystems[index];
  28008. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  28009. }
  28010. }
  28011. // Lens flares
  28012. if (parsedData.lensFlareSystems) {
  28013. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  28014. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  28015. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  28016. }
  28017. }
  28018. // Shadows
  28019. if (parsedData.shadowGenerators) {
  28020. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  28021. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  28022. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  28023. }
  28024. }
  28025. // Actions (scene)
  28026. if (parsedData.actions) {
  28027. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  28028. }
  28029. // Finish
  28030. return true;
  28031. }
  28032. catch (err) {
  28033. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  28034. log = null;
  28035. throw err;
  28036. }
  28037. finally {
  28038. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28039. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28040. }
  28041. }
  28042. }
  28043. });
  28044. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28045. })(BABYLON || (BABYLON = {}));
  28046. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28047. var BABYLON;
  28048. (function (BABYLON) {
  28049. var SpriteManager = (function () {
  28050. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28051. if (epsilon === void 0) { epsilon = 0.01; }
  28052. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28053. this.name = name;
  28054. this.sprites = new Array();
  28055. this.renderingGroupId = 0;
  28056. this.layerMask = 0x0FFFFFFF;
  28057. this.fogEnabled = true;
  28058. this.isPickable = false;
  28059. /**
  28060. * An event triggered when the manager is disposed.
  28061. * @type {BABYLON.Observable}
  28062. */
  28063. this.onDisposeObservable = new BABYLON.Observable();
  28064. this._vertexBuffers = {};
  28065. this._capacity = capacity;
  28066. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28067. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28068. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28069. if (cellSize.width && cellSize.height) {
  28070. this.cellWidth = cellSize.width;
  28071. this.cellHeight = cellSize.height;
  28072. }
  28073. else if (cellSize !== undefined) {
  28074. this.cellWidth = cellSize;
  28075. this.cellHeight = cellSize;
  28076. }
  28077. else {
  28078. return;
  28079. }
  28080. this._epsilon = epsilon;
  28081. this._scene = scene;
  28082. this._scene.spriteManagers.push(this);
  28083. var indices = [];
  28084. var index = 0;
  28085. for (var count = 0; count < capacity; count++) {
  28086. indices.push(index);
  28087. indices.push(index + 1);
  28088. indices.push(index + 2);
  28089. indices.push(index);
  28090. indices.push(index + 2);
  28091. indices.push(index + 3);
  28092. index += 4;
  28093. }
  28094. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28095. // VBO
  28096. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28097. this._vertexData = new Float32Array(capacity * 16 * 4);
  28098. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28099. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28100. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28101. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28102. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28103. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28104. this._vertexBuffers["options"] = options;
  28105. this._vertexBuffers["cellInfo"] = cellInfo;
  28106. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28107. // Effects
  28108. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28109. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28110. }
  28111. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28112. set: function (callback) {
  28113. if (this._onDisposeObserver) {
  28114. this.onDisposeObservable.remove(this._onDisposeObserver);
  28115. }
  28116. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28117. },
  28118. enumerable: true,
  28119. configurable: true
  28120. });
  28121. Object.defineProperty(SpriteManager.prototype, "texture", {
  28122. get: function () {
  28123. return this._spriteTexture;
  28124. },
  28125. set: function (value) {
  28126. this._spriteTexture = value;
  28127. },
  28128. enumerable: true,
  28129. configurable: true
  28130. });
  28131. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28132. var arrayOffset = index * 16;
  28133. if (offsetX === 0)
  28134. offsetX = this._epsilon;
  28135. else if (offsetX === 1)
  28136. offsetX = 1 - this._epsilon;
  28137. if (offsetY === 0)
  28138. offsetY = this._epsilon;
  28139. else if (offsetY === 1)
  28140. offsetY = 1 - this._epsilon;
  28141. this._vertexData[arrayOffset] = sprite.position.x;
  28142. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28143. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28144. this._vertexData[arrayOffset + 3] = sprite.angle;
  28145. this._vertexData[arrayOffset + 4] = sprite.width;
  28146. this._vertexData[arrayOffset + 5] = sprite.height;
  28147. this._vertexData[arrayOffset + 6] = offsetX;
  28148. this._vertexData[arrayOffset + 7] = offsetY;
  28149. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28150. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28151. var offset = (sprite.cellIndex / rowSize) >> 0;
  28152. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28153. this._vertexData[arrayOffset + 11] = offset;
  28154. // Color
  28155. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28156. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28157. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28158. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28159. };
  28160. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28161. var count = Math.min(this._capacity, this.sprites.length);
  28162. var min = BABYLON.Vector3.Zero();
  28163. var max = BABYLON.Vector3.Zero();
  28164. var distance = Number.MAX_VALUE;
  28165. var currentSprite;
  28166. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28167. var cameraView = camera.getViewMatrix();
  28168. for (var index = 0; index < count; index++) {
  28169. var sprite = this.sprites[index];
  28170. if (!sprite) {
  28171. continue;
  28172. }
  28173. if (predicate) {
  28174. if (!predicate(sprite)) {
  28175. continue;
  28176. }
  28177. }
  28178. else if (!sprite.isPickable) {
  28179. continue;
  28180. }
  28181. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28182. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28183. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28184. if (ray.intersectsBoxMinMax(min, max)) {
  28185. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28186. if (distance > currentDistance) {
  28187. distance = currentDistance;
  28188. currentSprite = sprite;
  28189. if (fastCheck) {
  28190. break;
  28191. }
  28192. }
  28193. }
  28194. }
  28195. if (currentSprite) {
  28196. var result = new BABYLON.PickingInfo();
  28197. result.hit = true;
  28198. result.pickedSprite = currentSprite;
  28199. result.distance = distance;
  28200. return result;
  28201. }
  28202. return null;
  28203. };
  28204. SpriteManager.prototype.render = function () {
  28205. // Check
  28206. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28207. return;
  28208. var engine = this._scene.getEngine();
  28209. var baseSize = this._spriteTexture.getBaseSize();
  28210. // Sprites
  28211. var deltaTime = engine.getDeltaTime();
  28212. var max = Math.min(this._capacity, this.sprites.length);
  28213. var rowSize = baseSize.width / this.cellWidth;
  28214. var offset = 0;
  28215. for (var index = 0; index < max; index++) {
  28216. var sprite = this.sprites[index];
  28217. if (!sprite) {
  28218. continue;
  28219. }
  28220. sprite._animate(deltaTime);
  28221. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28222. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28223. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28224. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28225. }
  28226. this._buffer.update(this._vertexData);
  28227. // Render
  28228. var effect = this._effectBase;
  28229. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28230. effect = this._effectFog;
  28231. }
  28232. engine.enableEffect(effect);
  28233. var viewMatrix = this._scene.getViewMatrix();
  28234. effect.setTexture("diffuseSampler", this._spriteTexture);
  28235. effect.setMatrix("view", viewMatrix);
  28236. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28237. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28238. // Fog
  28239. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28240. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28241. effect.setColor3("vFogColor", this._scene.fogColor);
  28242. }
  28243. // VBOs
  28244. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28245. // Draw order
  28246. engine.setDepthFunctionToLessOrEqual();
  28247. effect.setBool("alphaTest", true);
  28248. engine.setColorWrite(false);
  28249. engine.draw(true, 0, max * 6);
  28250. engine.setColorWrite(true);
  28251. effect.setBool("alphaTest", false);
  28252. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28253. engine.draw(true, 0, max * 6);
  28254. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28255. };
  28256. SpriteManager.prototype.dispose = function () {
  28257. if (this._buffer) {
  28258. this._buffer.dispose();
  28259. this._buffer = null;
  28260. }
  28261. if (this._indexBuffer) {
  28262. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28263. this._indexBuffer = null;
  28264. }
  28265. if (this._spriteTexture) {
  28266. this._spriteTexture.dispose();
  28267. this._spriteTexture = null;
  28268. }
  28269. // Remove from scene
  28270. var index = this._scene.spriteManagers.indexOf(this);
  28271. this._scene.spriteManagers.splice(index, 1);
  28272. // Callback
  28273. this.onDisposeObservable.notifyObservers(this);
  28274. this.onDisposeObservable.clear();
  28275. };
  28276. return SpriteManager;
  28277. }());
  28278. BABYLON.SpriteManager = SpriteManager;
  28279. })(BABYLON || (BABYLON = {}));
  28280. //# sourceMappingURL=babylon.spriteManager.js.map
  28281. var BABYLON;
  28282. (function (BABYLON) {
  28283. var Sprite = (function () {
  28284. function Sprite(name, manager) {
  28285. this.name = name;
  28286. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28287. this.width = 1.0;
  28288. this.height = 1.0;
  28289. this.angle = 0;
  28290. this.cellIndex = 0;
  28291. this.invertU = 0;
  28292. this.invertV = 0;
  28293. this.animations = new Array();
  28294. this.isPickable = false;
  28295. this._animationStarted = false;
  28296. this._loopAnimation = false;
  28297. this._fromIndex = 0;
  28298. this._toIndex = 0;
  28299. this._delay = 0;
  28300. this._direction = 1;
  28301. this._frameCount = 0;
  28302. this._time = 0;
  28303. this._manager = manager;
  28304. this._manager.sprites.push(this);
  28305. this.position = BABYLON.Vector3.Zero();
  28306. }
  28307. Object.defineProperty(Sprite.prototype, "size", {
  28308. get: function () {
  28309. return this.width;
  28310. },
  28311. set: function (value) {
  28312. this.width = value;
  28313. this.height = value;
  28314. },
  28315. enumerable: true,
  28316. configurable: true
  28317. });
  28318. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  28319. this._fromIndex = from;
  28320. this._toIndex = to;
  28321. this._loopAnimation = loop;
  28322. this._delay = delay;
  28323. this._animationStarted = true;
  28324. this._direction = from < to ? 1 : -1;
  28325. this.cellIndex = from;
  28326. this._time = 0;
  28327. this._onAnimationEnd = onAnimationEnd;
  28328. };
  28329. Sprite.prototype.stopAnimation = function () {
  28330. this._animationStarted = false;
  28331. };
  28332. Sprite.prototype._animate = function (deltaTime) {
  28333. if (!this._animationStarted)
  28334. return;
  28335. this._time += deltaTime;
  28336. if (this._time > this._delay) {
  28337. this._time = this._time % this._delay;
  28338. this.cellIndex += this._direction;
  28339. if (this.cellIndex === this._toIndex) {
  28340. if (this._loopAnimation) {
  28341. this.cellIndex = this._fromIndex;
  28342. }
  28343. else {
  28344. this._animationStarted = false;
  28345. if (this._onAnimationEnd) {
  28346. this._onAnimationEnd();
  28347. }
  28348. if (this.disposeWhenFinishedAnimating) {
  28349. this.dispose();
  28350. }
  28351. }
  28352. }
  28353. }
  28354. };
  28355. Sprite.prototype.dispose = function () {
  28356. for (var i = 0; i < this._manager.sprites.length; i++) {
  28357. if (this._manager.sprites[i] == this) {
  28358. this._manager.sprites.splice(i, 1);
  28359. }
  28360. }
  28361. };
  28362. return Sprite;
  28363. }());
  28364. BABYLON.Sprite = Sprite;
  28365. })(BABYLON || (BABYLON = {}));
  28366. //# sourceMappingURL=babylon.sprite.js.map
  28367. var BABYLON;
  28368. (function (BABYLON) {
  28369. var Layer = (function () {
  28370. function Layer(name, imgUrl, scene, isBackground, color) {
  28371. this.name = name;
  28372. this.scale = new BABYLON.Vector2(1, 1);
  28373. this.offset = new BABYLON.Vector2(0, 0);
  28374. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  28375. this._vertexBuffers = {};
  28376. // Events
  28377. /**
  28378. * An event triggered when the layer is disposed.
  28379. * @type {BABYLON.Observable}
  28380. */
  28381. this.onDisposeObservable = new BABYLON.Observable();
  28382. /**
  28383. * An event triggered before rendering the scene
  28384. * @type {BABYLON.Observable}
  28385. */
  28386. this.onBeforeRenderObservable = new BABYLON.Observable();
  28387. /**
  28388. * An event triggered after rendering the scene
  28389. * @type {BABYLON.Observable}
  28390. */
  28391. this.onAfterRenderObservable = new BABYLON.Observable();
  28392. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  28393. this.isBackground = isBackground === undefined ? true : isBackground;
  28394. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  28395. this._scene = scene;
  28396. this._scene.layers.push(this);
  28397. var engine = scene.getEngine();
  28398. // VBO
  28399. var vertices = [];
  28400. vertices.push(1, 1);
  28401. vertices.push(-1, 1);
  28402. vertices.push(-1, -1);
  28403. vertices.push(1, -1);
  28404. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28405. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  28406. // Indices
  28407. var indices = [];
  28408. indices.push(0);
  28409. indices.push(1);
  28410. indices.push(2);
  28411. indices.push(0);
  28412. indices.push(2);
  28413. indices.push(3);
  28414. this._indexBuffer = engine.createIndexBuffer(indices);
  28415. // Effects
  28416. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  28417. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  28418. }
  28419. Object.defineProperty(Layer.prototype, "onDispose", {
  28420. set: function (callback) {
  28421. if (this._onDisposeObserver) {
  28422. this.onDisposeObservable.remove(this._onDisposeObserver);
  28423. }
  28424. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28425. },
  28426. enumerable: true,
  28427. configurable: true
  28428. });
  28429. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  28430. set: function (callback) {
  28431. if (this._onBeforeRenderObserver) {
  28432. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28433. }
  28434. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28435. },
  28436. enumerable: true,
  28437. configurable: true
  28438. });
  28439. Object.defineProperty(Layer.prototype, "onAfterRender", {
  28440. set: function (callback) {
  28441. if (this._onAfterRenderObserver) {
  28442. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28443. }
  28444. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28445. },
  28446. enumerable: true,
  28447. configurable: true
  28448. });
  28449. Layer.prototype.render = function () {
  28450. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  28451. // Check
  28452. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  28453. return;
  28454. var engine = this._scene.getEngine();
  28455. this.onBeforeRenderObservable.notifyObservers(this);
  28456. // Render
  28457. engine.enableEffect(currentEffect);
  28458. engine.setState(false);
  28459. // Texture
  28460. currentEffect.setTexture("textureSampler", this.texture);
  28461. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  28462. // Color
  28463. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  28464. // Scale / offset
  28465. currentEffect.setVector2("offset", this.offset);
  28466. currentEffect.setVector2("scale", this.scale);
  28467. // VBOs
  28468. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  28469. // Draw order
  28470. if (!this.alphaTest) {
  28471. engine.setAlphaMode(this.alphaBlendingMode);
  28472. engine.draw(true, 0, 6);
  28473. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28474. }
  28475. else {
  28476. engine.draw(true, 0, 6);
  28477. }
  28478. this.onAfterRenderObservable.notifyObservers(this);
  28479. };
  28480. Layer.prototype.dispose = function () {
  28481. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28482. if (vertexBuffer) {
  28483. vertexBuffer.dispose();
  28484. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28485. }
  28486. if (this._indexBuffer) {
  28487. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28488. this._indexBuffer = null;
  28489. }
  28490. if (this.texture) {
  28491. this.texture.dispose();
  28492. this.texture = null;
  28493. }
  28494. // Remove from scene
  28495. var index = this._scene.layers.indexOf(this);
  28496. this._scene.layers.splice(index, 1);
  28497. // Callback
  28498. this.onDisposeObservable.notifyObservers(this);
  28499. this.onDisposeObservable.clear();
  28500. this.onAfterRenderObservable.clear();
  28501. this.onBeforeRenderObservable.clear();
  28502. };
  28503. return Layer;
  28504. }());
  28505. BABYLON.Layer = Layer;
  28506. })(BABYLON || (BABYLON = {}));
  28507. //# sourceMappingURL=babylon.layer.js.map
  28508. var BABYLON;
  28509. (function (BABYLON) {
  28510. var Particle = (function () {
  28511. function Particle() {
  28512. this.position = BABYLON.Vector3.Zero();
  28513. this.direction = BABYLON.Vector3.Zero();
  28514. this.color = new BABYLON.Color4(0, 0, 0, 0);
  28515. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  28516. this.lifeTime = 1.0;
  28517. this.age = 0;
  28518. this.size = 0;
  28519. this.angle = 0;
  28520. this.angularSpeed = 0;
  28521. }
  28522. Particle.prototype.copyTo = function (other) {
  28523. other.position.copyFrom(this.position);
  28524. other.direction.copyFrom(this.direction);
  28525. other.color.copyFrom(this.color);
  28526. other.colorStep.copyFrom(this.colorStep);
  28527. other.lifeTime = this.lifeTime;
  28528. other.age = this.age;
  28529. other.size = this.size;
  28530. other.angle = this.angle;
  28531. other.angularSpeed = this.angularSpeed;
  28532. };
  28533. return Particle;
  28534. }());
  28535. BABYLON.Particle = Particle;
  28536. })(BABYLON || (BABYLON = {}));
  28537. //# sourceMappingURL=babylon.particle.js.map
  28538. var BABYLON;
  28539. (function (BABYLON) {
  28540. var randomNumber = function (min, max) {
  28541. if (min === max) {
  28542. return (min);
  28543. }
  28544. var random = Math.random();
  28545. return ((random * (max - min)) + min);
  28546. };
  28547. var ParticleSystem = (function () {
  28548. function ParticleSystem(name, capacity, scene, customEffect) {
  28549. var _this = this;
  28550. this.name = name;
  28551. // Members
  28552. this.animations = [];
  28553. this.renderingGroupId = 0;
  28554. this.emitter = null;
  28555. this.emitRate = 10;
  28556. this.manualEmitCount = -1;
  28557. this.updateSpeed = 0.01;
  28558. this.targetStopDuration = 0;
  28559. this.disposeOnStop = false;
  28560. this.minEmitPower = 1;
  28561. this.maxEmitPower = 1;
  28562. this.minLifeTime = 1;
  28563. this.maxLifeTime = 1;
  28564. this.minSize = 1;
  28565. this.maxSize = 1;
  28566. this.minAngularSpeed = 0;
  28567. this.maxAngularSpeed = 0;
  28568. this.layerMask = 0x0FFFFFFF;
  28569. /**
  28570. * An event triggered when the system is disposed.
  28571. * @type {BABYLON.Observable}
  28572. */
  28573. this.onDisposeObservable = new BABYLON.Observable();
  28574. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  28575. this.forceDepthWrite = false;
  28576. this.gravity = BABYLON.Vector3.Zero();
  28577. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  28578. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  28579. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  28580. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  28581. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28582. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28583. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  28584. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28585. this.particles = new Array();
  28586. this._stockParticles = new Array();
  28587. this._newPartsExcess = 0;
  28588. this._vertexBuffers = {};
  28589. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  28590. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  28591. this._scaledDirection = BABYLON.Vector3.Zero();
  28592. this._scaledGravity = BABYLON.Vector3.Zero();
  28593. this._currentRenderId = -1;
  28594. this._started = false;
  28595. this._stopped = false;
  28596. this._actualFrame = 0;
  28597. this.id = name;
  28598. this._capacity = capacity;
  28599. this._scene = scene;
  28600. this._customEffect = customEffect;
  28601. scene.particleSystems.push(this);
  28602. var indices = [];
  28603. var index = 0;
  28604. for (var count = 0; count < capacity; count++) {
  28605. indices.push(index);
  28606. indices.push(index + 1);
  28607. indices.push(index + 2);
  28608. indices.push(index);
  28609. indices.push(index + 2);
  28610. indices.push(index + 3);
  28611. index += 4;
  28612. }
  28613. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28614. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  28615. this._vertexData = new Float32Array(capacity * 11 * 4);
  28616. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  28617. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  28618. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  28619. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  28620. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28621. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28622. this._vertexBuffers["options"] = options;
  28623. // Default behaviors
  28624. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  28625. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  28626. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  28627. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  28628. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  28629. };
  28630. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  28631. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  28632. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  28633. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  28634. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  28635. };
  28636. this.updateFunction = function (particles) {
  28637. for (var index = 0; index < particles.length; index++) {
  28638. var particle = particles[index];
  28639. particle.age += _this._scaledUpdateSpeed;
  28640. if (particle.age >= particle.lifeTime) {
  28641. _this.recycleParticle(particle);
  28642. index--;
  28643. continue;
  28644. }
  28645. else {
  28646. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28647. particle.color.addInPlace(_this._scaledColorStep);
  28648. if (particle.color.a < 0)
  28649. particle.color.a = 0;
  28650. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28651. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28652. particle.position.addInPlace(_this._scaledDirection);
  28653. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28654. particle.direction.addInPlace(_this._scaledGravity);
  28655. }
  28656. }
  28657. };
  28658. }
  28659. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28660. set: function (callback) {
  28661. if (this._onDisposeObserver) {
  28662. this.onDisposeObservable.remove(this._onDisposeObserver);
  28663. }
  28664. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28665. },
  28666. enumerable: true,
  28667. configurable: true
  28668. });
  28669. ParticleSystem.prototype.recycleParticle = function (particle) {
  28670. var lastParticle = this.particles.pop();
  28671. if (lastParticle !== particle) {
  28672. lastParticle.copyTo(particle);
  28673. this._stockParticles.push(lastParticle);
  28674. }
  28675. };
  28676. ParticleSystem.prototype.getCapacity = function () {
  28677. return this._capacity;
  28678. };
  28679. ParticleSystem.prototype.isAlive = function () {
  28680. return this._alive;
  28681. };
  28682. ParticleSystem.prototype.isStarted = function () {
  28683. return this._started;
  28684. };
  28685. ParticleSystem.prototype.start = function () {
  28686. this._started = true;
  28687. this._stopped = false;
  28688. this._actualFrame = 0;
  28689. };
  28690. ParticleSystem.prototype.stop = function () {
  28691. this._stopped = true;
  28692. };
  28693. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28694. var offset = index * 11;
  28695. this._vertexData[offset] = particle.position.x;
  28696. this._vertexData[offset + 1] = particle.position.y;
  28697. this._vertexData[offset + 2] = particle.position.z;
  28698. this._vertexData[offset + 3] = particle.color.r;
  28699. this._vertexData[offset + 4] = particle.color.g;
  28700. this._vertexData[offset + 5] = particle.color.b;
  28701. this._vertexData[offset + 6] = particle.color.a;
  28702. this._vertexData[offset + 7] = particle.angle;
  28703. this._vertexData[offset + 8] = particle.size;
  28704. this._vertexData[offset + 9] = offsetX;
  28705. this._vertexData[offset + 10] = offsetY;
  28706. };
  28707. ParticleSystem.prototype._update = function (newParticles) {
  28708. // Update current
  28709. this._alive = this.particles.length > 0;
  28710. this.updateFunction(this.particles);
  28711. // Add new ones
  28712. var worldMatrix;
  28713. if (this.emitter.position) {
  28714. worldMatrix = this.emitter.getWorldMatrix();
  28715. }
  28716. else {
  28717. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28718. }
  28719. var particle;
  28720. for (var index = 0; index < newParticles; index++) {
  28721. if (this.particles.length === this._capacity) {
  28722. break;
  28723. }
  28724. if (this._stockParticles.length !== 0) {
  28725. particle = this._stockParticles.pop();
  28726. particle.age = 0;
  28727. }
  28728. else {
  28729. particle = new BABYLON.Particle();
  28730. }
  28731. this.particles.push(particle);
  28732. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28733. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28734. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28735. particle.size = randomNumber(this.minSize, this.maxSize);
  28736. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28737. this.startPositionFunction(worldMatrix, particle.position, particle);
  28738. var step = randomNumber(0, 1.0);
  28739. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28740. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28741. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28742. }
  28743. };
  28744. ParticleSystem.prototype._getEffect = function () {
  28745. if (this._customEffect) {
  28746. return this._customEffect;
  28747. }
  28748. ;
  28749. var defines = [];
  28750. if (this._scene.clipPlane) {
  28751. defines.push("#define CLIPPLANE");
  28752. }
  28753. // Effect
  28754. var join = defines.join("\n");
  28755. if (this._cachedDefines !== join) {
  28756. this._cachedDefines = join;
  28757. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28758. }
  28759. return this._effect;
  28760. };
  28761. ParticleSystem.prototype.animate = function () {
  28762. if (!this._started)
  28763. return;
  28764. var effect = this._getEffect();
  28765. // Check
  28766. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28767. return;
  28768. if (this._currentRenderId === this._scene.getRenderId()) {
  28769. return;
  28770. }
  28771. this._currentRenderId = this._scene.getRenderId();
  28772. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28773. // determine the number of particles we need to create
  28774. var newParticles;
  28775. if (this.manualEmitCount > -1) {
  28776. newParticles = this.manualEmitCount;
  28777. this._newPartsExcess = 0;
  28778. this.manualEmitCount = 0;
  28779. }
  28780. else {
  28781. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28782. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28783. }
  28784. if (this._newPartsExcess > 1.0) {
  28785. newParticles += this._newPartsExcess >> 0;
  28786. this._newPartsExcess -= this._newPartsExcess >> 0;
  28787. }
  28788. this._alive = false;
  28789. if (!this._stopped) {
  28790. this._actualFrame += this._scaledUpdateSpeed;
  28791. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28792. this.stop();
  28793. }
  28794. else {
  28795. newParticles = 0;
  28796. }
  28797. this._update(newParticles);
  28798. // Stopped?
  28799. if (this._stopped) {
  28800. if (!this._alive) {
  28801. this._started = false;
  28802. if (this.disposeOnStop) {
  28803. this._scene._toBeDisposed.push(this);
  28804. }
  28805. }
  28806. }
  28807. // Update VBO
  28808. var offset = 0;
  28809. for (var index = 0; index < this.particles.length; index++) {
  28810. var particle = this.particles[index];
  28811. this._appendParticleVertex(offset++, particle, 0, 0);
  28812. this._appendParticleVertex(offset++, particle, 1, 0);
  28813. this._appendParticleVertex(offset++, particle, 1, 1);
  28814. this._appendParticleVertex(offset++, particle, 0, 1);
  28815. }
  28816. this._vertexBuffer.update(this._vertexData);
  28817. };
  28818. ParticleSystem.prototype.render = function () {
  28819. var effect = this._getEffect();
  28820. // Check
  28821. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28822. return 0;
  28823. var engine = this._scene.getEngine();
  28824. // Render
  28825. engine.enableEffect(effect);
  28826. engine.setState(false);
  28827. var viewMatrix = this._scene.getViewMatrix();
  28828. effect.setTexture("diffuseSampler", this.particleTexture);
  28829. effect.setMatrix("view", viewMatrix);
  28830. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28831. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28832. if (this._scene.clipPlane) {
  28833. var clipPlane = this._scene.clipPlane;
  28834. var invView = viewMatrix.clone();
  28835. invView.invert();
  28836. effect.setMatrix("invView", invView);
  28837. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28838. }
  28839. // VBOs
  28840. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28841. // Draw order
  28842. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28843. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28844. }
  28845. else {
  28846. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28847. }
  28848. if (this.forceDepthWrite) {
  28849. engine.setDepthWrite(true);
  28850. }
  28851. engine.draw(true, 0, this.particles.length * 6);
  28852. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28853. return this.particles.length;
  28854. };
  28855. ParticleSystem.prototype.dispose = function () {
  28856. if (this._vertexBuffer) {
  28857. this._vertexBuffer.dispose();
  28858. this._vertexBuffer = null;
  28859. }
  28860. if (this._indexBuffer) {
  28861. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28862. this._indexBuffer = null;
  28863. }
  28864. if (this.particleTexture) {
  28865. this.particleTexture.dispose();
  28866. this.particleTexture = null;
  28867. }
  28868. // Remove from scene
  28869. var index = this._scene.particleSystems.indexOf(this);
  28870. this._scene.particleSystems.splice(index, 1);
  28871. // Callback
  28872. this.onDisposeObservable.notifyObservers(this);
  28873. this.onDisposeObservable.clear();
  28874. };
  28875. // Clone
  28876. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28877. var result = new ParticleSystem(name, this._capacity, this._scene);
  28878. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28879. if (newEmitter === undefined) {
  28880. newEmitter = this.emitter;
  28881. }
  28882. result.emitter = newEmitter;
  28883. if (this.particleTexture) {
  28884. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28885. }
  28886. result.start();
  28887. return result;
  28888. };
  28889. ParticleSystem.prototype.serialize = function () {
  28890. var serializationObject = {};
  28891. serializationObject.name = this.name;
  28892. serializationObject.id = this.id;
  28893. // Emitter
  28894. if (this.emitter.position) {
  28895. serializationObject.emitterId = this.emitter.id;
  28896. }
  28897. else {
  28898. serializationObject.emitter = this.emitter.asArray();
  28899. }
  28900. serializationObject.capacity = this.getCapacity();
  28901. if (this.particleTexture) {
  28902. serializationObject.textureName = this.particleTexture.name;
  28903. }
  28904. // Animations
  28905. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28906. // Particle system
  28907. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28908. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28909. serializationObject.minSize = this.minSize;
  28910. serializationObject.maxSize = this.maxSize;
  28911. serializationObject.minEmitPower = this.minEmitPower;
  28912. serializationObject.maxEmitPower = this.maxEmitPower;
  28913. serializationObject.minLifeTime = this.minLifeTime;
  28914. serializationObject.maxLifeTime = this.maxLifeTime;
  28915. serializationObject.emitRate = this.emitRate;
  28916. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28917. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28918. serializationObject.gravity = this.gravity.asArray();
  28919. serializationObject.direction1 = this.direction1.asArray();
  28920. serializationObject.direction2 = this.direction2.asArray();
  28921. serializationObject.color1 = this.color1.asArray();
  28922. serializationObject.color2 = this.color2.asArray();
  28923. serializationObject.colorDead = this.colorDead.asArray();
  28924. serializationObject.updateSpeed = this.updateSpeed;
  28925. serializationObject.targetStopDuration = this.targetStopDuration;
  28926. serializationObject.textureMask = this.textureMask.asArray();
  28927. serializationObject.blendMode = this.blendMode;
  28928. return serializationObject;
  28929. };
  28930. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28931. var name = parsedParticleSystem.name;
  28932. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28933. if (parsedParticleSystem.id) {
  28934. particleSystem.id = parsedParticleSystem.id;
  28935. }
  28936. // Texture
  28937. if (parsedParticleSystem.textureName) {
  28938. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28939. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28940. }
  28941. // Emitter
  28942. if (parsedParticleSystem.emitterId) {
  28943. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28944. }
  28945. else {
  28946. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28947. }
  28948. // Animations
  28949. if (parsedParticleSystem.animations) {
  28950. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28951. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28952. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28953. }
  28954. }
  28955. if (parsedParticleSystem.autoAnimate) {
  28956. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28957. }
  28958. // Particle system
  28959. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28960. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28961. particleSystem.minSize = parsedParticleSystem.minSize;
  28962. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28963. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28964. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28965. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28966. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28967. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28968. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28969. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28970. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28971. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28972. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28973. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28974. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28975. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28976. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28977. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28978. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28979. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28980. if (!parsedParticleSystem.preventAutoStart) {
  28981. particleSystem.start();
  28982. }
  28983. return particleSystem;
  28984. };
  28985. // Statics
  28986. ParticleSystem.BLENDMODE_ONEONE = 0;
  28987. ParticleSystem.BLENDMODE_STANDARD = 1;
  28988. return ParticleSystem;
  28989. }());
  28990. BABYLON.ParticleSystem = ParticleSystem;
  28991. })(BABYLON || (BABYLON = {}));
  28992. //# sourceMappingURL=babylon.particleSystem.js.map
  28993. var BABYLON;
  28994. (function (BABYLON) {
  28995. var AnimationRange = (function () {
  28996. function AnimationRange(name, from, to) {
  28997. this.name = name;
  28998. this.from = from;
  28999. this.to = to;
  29000. }
  29001. AnimationRange.prototype.clone = function () {
  29002. return new AnimationRange(this.name, this.from, this.to);
  29003. };
  29004. return AnimationRange;
  29005. }());
  29006. BABYLON.AnimationRange = AnimationRange;
  29007. /**
  29008. * Composed of a frame, and an action function
  29009. */
  29010. var AnimationEvent = (function () {
  29011. function AnimationEvent(frame, action, onlyOnce) {
  29012. this.frame = frame;
  29013. this.action = action;
  29014. this.onlyOnce = onlyOnce;
  29015. this.isDone = false;
  29016. }
  29017. return AnimationEvent;
  29018. }());
  29019. BABYLON.AnimationEvent = AnimationEvent;
  29020. var PathCursor = (function () {
  29021. function PathCursor(path) {
  29022. this.path = path;
  29023. this._onchange = new Array();
  29024. this.value = 0;
  29025. this.animations = new Array();
  29026. }
  29027. PathCursor.prototype.getPoint = function () {
  29028. var point = this.path.getPointAtLengthPosition(this.value);
  29029. return new BABYLON.Vector3(point.x, 0, point.y);
  29030. };
  29031. PathCursor.prototype.moveAhead = function (step) {
  29032. if (step === void 0) { step = 0.002; }
  29033. this.move(step);
  29034. return this;
  29035. };
  29036. PathCursor.prototype.moveBack = function (step) {
  29037. if (step === void 0) { step = 0.002; }
  29038. this.move(-step);
  29039. return this;
  29040. };
  29041. PathCursor.prototype.move = function (step) {
  29042. if (Math.abs(step) > 1) {
  29043. throw "step size should be less than 1.";
  29044. }
  29045. this.value += step;
  29046. this.ensureLimits();
  29047. this.raiseOnChange();
  29048. return this;
  29049. };
  29050. PathCursor.prototype.ensureLimits = function () {
  29051. while (this.value > 1) {
  29052. this.value -= 1;
  29053. }
  29054. while (this.value < 0) {
  29055. this.value += 1;
  29056. }
  29057. return this;
  29058. };
  29059. // used by animation engine
  29060. PathCursor.prototype.markAsDirty = function (propertyName) {
  29061. this.ensureLimits();
  29062. this.raiseOnChange();
  29063. return this;
  29064. };
  29065. PathCursor.prototype.raiseOnChange = function () {
  29066. var _this = this;
  29067. this._onchange.forEach(function (f) { return f(_this); });
  29068. return this;
  29069. };
  29070. PathCursor.prototype.onchange = function (f) {
  29071. this._onchange.push(f);
  29072. return this;
  29073. };
  29074. return PathCursor;
  29075. }());
  29076. BABYLON.PathCursor = PathCursor;
  29077. var Animation = (function () {
  29078. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29079. this.name = name;
  29080. this.targetProperty = targetProperty;
  29081. this.framePerSecond = framePerSecond;
  29082. this.dataType = dataType;
  29083. this.loopMode = loopMode;
  29084. this.enableBlending = enableBlending;
  29085. this._offsetsCache = {};
  29086. this._highLimitsCache = {};
  29087. this._stopped = false;
  29088. this._blendingFactor = 0;
  29089. // The set of event that will be linked to this animation
  29090. this._events = new Array();
  29091. this.allowMatricesInterpolation = false;
  29092. this.blendingSpeed = 0.01;
  29093. this._ranges = {};
  29094. this.targetPropertyPath = targetProperty.split(".");
  29095. this.dataType = dataType;
  29096. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29097. }
  29098. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29099. var dataType = undefined;
  29100. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29101. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29102. }
  29103. else if (from instanceof BABYLON.Quaternion) {
  29104. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29105. }
  29106. else if (from instanceof BABYLON.Vector3) {
  29107. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29108. }
  29109. else if (from instanceof BABYLON.Vector2) {
  29110. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29111. }
  29112. else if (from instanceof BABYLON.Color3) {
  29113. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29114. }
  29115. else if (from instanceof BABYLON.Size) {
  29116. dataType = Animation.ANIMATIONTYPE_SIZE;
  29117. }
  29118. if (dataType == undefined) {
  29119. return null;
  29120. }
  29121. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29122. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29123. animation.setKeys(keys);
  29124. if (easingFunction !== undefined) {
  29125. animation.setEasingFunction(easingFunction);
  29126. }
  29127. return animation;
  29128. };
  29129. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29130. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29131. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29132. };
  29133. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29134. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29135. node.animations.push(animation);
  29136. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29137. };
  29138. // Methods
  29139. /**
  29140. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29141. */
  29142. Animation.prototype.toString = function (fullDetails) {
  29143. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29144. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29145. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29146. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29147. if (fullDetails) {
  29148. ret += ", Ranges: {";
  29149. var first = true;
  29150. for (var name in this._ranges) {
  29151. if (first) {
  29152. ret += ", ";
  29153. first = false;
  29154. }
  29155. ret += name;
  29156. }
  29157. ret += "}";
  29158. }
  29159. return ret;
  29160. };
  29161. /**
  29162. * Add an event to this animation.
  29163. */
  29164. Animation.prototype.addEvent = function (event) {
  29165. this._events.push(event);
  29166. };
  29167. /**
  29168. * Remove all events found at the given frame
  29169. * @param frame
  29170. */
  29171. Animation.prototype.removeEvents = function (frame) {
  29172. for (var index = 0; index < this._events.length; index++) {
  29173. if (this._events[index].frame === frame) {
  29174. this._events.splice(index, 1);
  29175. index--;
  29176. }
  29177. }
  29178. };
  29179. Animation.prototype.createRange = function (name, from, to) {
  29180. // check name not already in use; could happen for bones after serialized
  29181. if (!this._ranges[name]) {
  29182. this._ranges[name] = new AnimationRange(name, from, to);
  29183. }
  29184. };
  29185. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29186. if (deleteFrames === void 0) { deleteFrames = true; }
  29187. if (this._ranges[name]) {
  29188. if (deleteFrames) {
  29189. var from = this._ranges[name].from;
  29190. var to = this._ranges[name].to;
  29191. // this loop MUST go high to low for multiple splices to work
  29192. for (var key = this._keys.length - 1; key >= 0; key--) {
  29193. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29194. this._keys.splice(key, 1);
  29195. }
  29196. }
  29197. }
  29198. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29199. }
  29200. };
  29201. Animation.prototype.getRange = function (name) {
  29202. return this._ranges[name];
  29203. };
  29204. Animation.prototype.reset = function () {
  29205. this._offsetsCache = {};
  29206. this._highLimitsCache = {};
  29207. this.currentFrame = 0;
  29208. this._blendingFactor = 0;
  29209. this._originalBlendValue = null;
  29210. };
  29211. Animation.prototype.isStopped = function () {
  29212. return this._stopped;
  29213. };
  29214. Animation.prototype.getKeys = function () {
  29215. return this._keys;
  29216. };
  29217. Animation.prototype.getHighestFrame = function () {
  29218. var ret = 0;
  29219. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29220. if (ret < this._keys[key].frame) {
  29221. ret = this._keys[key].frame;
  29222. }
  29223. }
  29224. return ret;
  29225. };
  29226. Animation.prototype.getEasingFunction = function () {
  29227. return this._easingFunction;
  29228. };
  29229. Animation.prototype.setEasingFunction = function (easingFunction) {
  29230. this._easingFunction = easingFunction;
  29231. };
  29232. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29233. return startValue + (endValue - startValue) * gradient;
  29234. };
  29235. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29236. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29237. };
  29238. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29239. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29240. };
  29241. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29242. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29243. };
  29244. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29245. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29246. };
  29247. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29248. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29249. };
  29250. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29251. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29252. };
  29253. Animation.prototype.clone = function () {
  29254. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29255. if (this._keys) {
  29256. clone.setKeys(this._keys);
  29257. }
  29258. if (this._ranges) {
  29259. clone._ranges = {};
  29260. for (var name in this._ranges) {
  29261. clone._ranges[name] = this._ranges[name].clone();
  29262. }
  29263. }
  29264. return clone;
  29265. };
  29266. Animation.prototype.setKeys = function (values) {
  29267. this._keys = values.slice(0);
  29268. this._offsetsCache = {};
  29269. this._highLimitsCache = {};
  29270. };
  29271. Animation.prototype._getKeyValue = function (value) {
  29272. if (typeof value === "function") {
  29273. return value();
  29274. }
  29275. return value;
  29276. };
  29277. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  29278. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  29279. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  29280. }
  29281. this.currentFrame = currentFrame;
  29282. // Try to get a hash to find the right key
  29283. 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));
  29284. if (this._keys[startKey].frame >= currentFrame) {
  29285. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  29286. startKey--;
  29287. }
  29288. }
  29289. for (var key = startKey; key < this._keys.length; key++) {
  29290. if (this._keys[key + 1].frame >= currentFrame) {
  29291. var startValue = this._getKeyValue(this._keys[key].value);
  29292. var endValue = this._getKeyValue(this._keys[key + 1].value);
  29293. // gradient : percent of currentFrame between the frame inf and the frame sup
  29294. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  29295. // check for easingFunction and correction of gradient
  29296. if (this._easingFunction != null) {
  29297. gradient = this._easingFunction.ease(gradient);
  29298. }
  29299. switch (this.dataType) {
  29300. // Float
  29301. case Animation.ANIMATIONTYPE_FLOAT:
  29302. switch (loopMode) {
  29303. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29304. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29305. return this.floatInterpolateFunction(startValue, endValue, gradient);
  29306. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29307. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  29308. }
  29309. break;
  29310. // Quaternion
  29311. case Animation.ANIMATIONTYPE_QUATERNION:
  29312. var quaternion = null;
  29313. switch (loopMode) {
  29314. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29315. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29316. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  29317. break;
  29318. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29319. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29320. break;
  29321. }
  29322. return quaternion;
  29323. // Vector3
  29324. case Animation.ANIMATIONTYPE_VECTOR3:
  29325. switch (loopMode) {
  29326. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29327. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29328. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  29329. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29330. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29331. }
  29332. // Vector2
  29333. case Animation.ANIMATIONTYPE_VECTOR2:
  29334. switch (loopMode) {
  29335. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29336. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29337. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  29338. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29339. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29340. }
  29341. // Size
  29342. case Animation.ANIMATIONTYPE_SIZE:
  29343. switch (loopMode) {
  29344. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29345. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29346. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  29347. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29348. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29349. }
  29350. // Color3
  29351. case Animation.ANIMATIONTYPE_COLOR3:
  29352. switch (loopMode) {
  29353. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29354. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29355. return this.color3InterpolateFunction(startValue, endValue, gradient);
  29356. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29357. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29358. }
  29359. // Matrix
  29360. case Animation.ANIMATIONTYPE_MATRIX:
  29361. switch (loopMode) {
  29362. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29363. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29364. if (this.allowMatricesInterpolation) {
  29365. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  29366. }
  29367. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29368. return startValue;
  29369. }
  29370. default:
  29371. break;
  29372. }
  29373. break;
  29374. }
  29375. }
  29376. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  29377. };
  29378. Animation.prototype.setValue = function (currentValue, blend) {
  29379. if (blend === void 0) { blend = false; }
  29380. // Set value
  29381. var path;
  29382. var destination;
  29383. if (this.targetPropertyPath.length > 1) {
  29384. var property = this._target[this.targetPropertyPath[0]];
  29385. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  29386. property = property[this.targetPropertyPath[index]];
  29387. }
  29388. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  29389. destination = property;
  29390. }
  29391. else {
  29392. path = this.targetPropertyPath[0];
  29393. destination = this._target;
  29394. }
  29395. // Blending
  29396. if (this.enableBlending && this._blendingFactor <= 1.0) {
  29397. if (!this._originalBlendValue) {
  29398. if (destination[path].clone) {
  29399. this._originalBlendValue = destination[path].clone();
  29400. }
  29401. else {
  29402. this._originalBlendValue = destination[path];
  29403. }
  29404. }
  29405. if (this._originalBlendValue.prototype) {
  29406. if (this._originalBlendValue.prototype.Lerp) {
  29407. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  29408. }
  29409. else {
  29410. destination[path] = currentValue;
  29411. }
  29412. }
  29413. else if (this._originalBlendValue.m) {
  29414. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  29415. }
  29416. else {
  29417. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  29418. }
  29419. this._blendingFactor += this.blendingSpeed;
  29420. }
  29421. else {
  29422. destination[path] = currentValue;
  29423. }
  29424. if (this._target.markAsDirty) {
  29425. this._target.markAsDirty(this.targetProperty);
  29426. }
  29427. };
  29428. Animation.prototype.goToFrame = function (frame) {
  29429. if (frame < this._keys[0].frame) {
  29430. frame = this._keys[0].frame;
  29431. }
  29432. else if (frame > this._keys[this._keys.length - 1].frame) {
  29433. frame = this._keys[this._keys.length - 1].frame;
  29434. }
  29435. var currentValue = this._interpolate(frame, 0, this.loopMode);
  29436. this.setValue(currentValue);
  29437. };
  29438. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  29439. if (blend === void 0) { blend = false; }
  29440. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  29441. this._stopped = true;
  29442. return false;
  29443. }
  29444. var returnValue = true;
  29445. // Adding a start key at frame 0 if missing
  29446. if (this._keys[0].frame !== 0) {
  29447. var newKey = { frame: 0, value: this._keys[0].value };
  29448. this._keys.splice(0, 0, newKey);
  29449. }
  29450. // Check limits
  29451. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  29452. from = this._keys[0].frame;
  29453. }
  29454. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  29455. to = this._keys[this._keys.length - 1].frame;
  29456. }
  29457. //to and from cannot be the same key
  29458. if (from === to) {
  29459. from++;
  29460. }
  29461. // Compute ratio
  29462. var range = to - from;
  29463. var offsetValue;
  29464. // ratio represents the frame delta between from and to
  29465. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  29466. var highLimitValue = 0;
  29467. if (ratio > range && !loop) {
  29468. returnValue = false;
  29469. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  29470. }
  29471. else {
  29472. // Get max value if required
  29473. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  29474. var keyOffset = to.toString() + from.toString();
  29475. if (!this._offsetsCache[keyOffset]) {
  29476. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29477. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29478. switch (this.dataType) {
  29479. // Float
  29480. case Animation.ANIMATIONTYPE_FLOAT:
  29481. this._offsetsCache[keyOffset] = toValue - fromValue;
  29482. break;
  29483. // Quaternion
  29484. case Animation.ANIMATIONTYPE_QUATERNION:
  29485. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29486. break;
  29487. // Vector3
  29488. case Animation.ANIMATIONTYPE_VECTOR3:
  29489. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29490. // Vector2
  29491. case Animation.ANIMATIONTYPE_VECTOR2:
  29492. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29493. // Size
  29494. case Animation.ANIMATIONTYPE_SIZE:
  29495. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29496. // Color3
  29497. case Animation.ANIMATIONTYPE_COLOR3:
  29498. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29499. default:
  29500. break;
  29501. }
  29502. this._highLimitsCache[keyOffset] = toValue;
  29503. }
  29504. highLimitValue = this._highLimitsCache[keyOffset];
  29505. offsetValue = this._offsetsCache[keyOffset];
  29506. }
  29507. }
  29508. if (offsetValue === undefined) {
  29509. switch (this.dataType) {
  29510. // Float
  29511. case Animation.ANIMATIONTYPE_FLOAT:
  29512. offsetValue = 0;
  29513. break;
  29514. // Quaternion
  29515. case Animation.ANIMATIONTYPE_QUATERNION:
  29516. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  29517. break;
  29518. // Vector3
  29519. case Animation.ANIMATIONTYPE_VECTOR3:
  29520. offsetValue = BABYLON.Vector3.Zero();
  29521. break;
  29522. // Vector2
  29523. case Animation.ANIMATIONTYPE_VECTOR2:
  29524. offsetValue = BABYLON.Vector2.Zero();
  29525. break;
  29526. // Size
  29527. case Animation.ANIMATIONTYPE_SIZE:
  29528. offsetValue = BABYLON.Size.Zero();
  29529. break;
  29530. // Color3
  29531. case Animation.ANIMATIONTYPE_COLOR3:
  29532. offsetValue = BABYLON.Color3.Black();
  29533. }
  29534. }
  29535. // Compute value
  29536. var repeatCount = (ratio / range) >> 0;
  29537. var currentFrame = returnValue ? from + ratio % range : to;
  29538. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29539. // Set value
  29540. this.setValue(currentValue);
  29541. // Check events
  29542. for (var index = 0; index < this._events.length; index++) {
  29543. if (currentFrame >= this._events[index].frame) {
  29544. var event = this._events[index];
  29545. if (!event.isDone) {
  29546. // If event should be done only once, remove it.
  29547. if (event.onlyOnce) {
  29548. this._events.splice(index, 1);
  29549. index--;
  29550. }
  29551. event.isDone = true;
  29552. event.action();
  29553. } // Don't do anything if the event has already be done.
  29554. }
  29555. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29556. // reset event, the animation is looping
  29557. this._events[index].isDone = false;
  29558. }
  29559. }
  29560. if (!returnValue) {
  29561. this._stopped = true;
  29562. }
  29563. return returnValue;
  29564. };
  29565. Animation.prototype.serialize = function () {
  29566. var serializationObject = {};
  29567. serializationObject.name = this.name;
  29568. serializationObject.property = this.targetProperty;
  29569. serializationObject.framePerSecond = this.framePerSecond;
  29570. serializationObject.dataType = this.dataType;
  29571. serializationObject.loopBehavior = this.loopMode;
  29572. var dataType = this.dataType;
  29573. serializationObject.keys = [];
  29574. var keys = this.getKeys();
  29575. for (var index = 0; index < keys.length; index++) {
  29576. var animationKey = keys[index];
  29577. var key = {};
  29578. key.frame = animationKey.frame;
  29579. switch (dataType) {
  29580. case Animation.ANIMATIONTYPE_FLOAT:
  29581. key.values = [animationKey.value];
  29582. break;
  29583. case Animation.ANIMATIONTYPE_QUATERNION:
  29584. case Animation.ANIMATIONTYPE_MATRIX:
  29585. case Animation.ANIMATIONTYPE_VECTOR3:
  29586. case Animation.ANIMATIONTYPE_COLOR3:
  29587. key.values = animationKey.value.asArray();
  29588. break;
  29589. }
  29590. serializationObject.keys.push(key);
  29591. }
  29592. serializationObject.ranges = [];
  29593. for (var name in this._ranges) {
  29594. var range = {};
  29595. range.name = name;
  29596. range.from = this._ranges[name].from;
  29597. range.to = this._ranges[name].to;
  29598. serializationObject.ranges.push(range);
  29599. }
  29600. return serializationObject;
  29601. };
  29602. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29603. get: function () {
  29604. return Animation._ANIMATIONTYPE_FLOAT;
  29605. },
  29606. enumerable: true,
  29607. configurable: true
  29608. });
  29609. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29610. get: function () {
  29611. return Animation._ANIMATIONTYPE_VECTOR3;
  29612. },
  29613. enumerable: true,
  29614. configurable: true
  29615. });
  29616. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29617. get: function () {
  29618. return Animation._ANIMATIONTYPE_VECTOR2;
  29619. },
  29620. enumerable: true,
  29621. configurable: true
  29622. });
  29623. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29624. get: function () {
  29625. return Animation._ANIMATIONTYPE_SIZE;
  29626. },
  29627. enumerable: true,
  29628. configurable: true
  29629. });
  29630. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29631. get: function () {
  29632. return Animation._ANIMATIONTYPE_QUATERNION;
  29633. },
  29634. enumerable: true,
  29635. configurable: true
  29636. });
  29637. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29638. get: function () {
  29639. return Animation._ANIMATIONTYPE_MATRIX;
  29640. },
  29641. enumerable: true,
  29642. configurable: true
  29643. });
  29644. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29645. get: function () {
  29646. return Animation._ANIMATIONTYPE_COLOR3;
  29647. },
  29648. enumerable: true,
  29649. configurable: true
  29650. });
  29651. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29652. get: function () {
  29653. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29654. },
  29655. enumerable: true,
  29656. configurable: true
  29657. });
  29658. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29659. get: function () {
  29660. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29661. },
  29662. enumerable: true,
  29663. configurable: true
  29664. });
  29665. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29666. get: function () {
  29667. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29668. },
  29669. enumerable: true,
  29670. configurable: true
  29671. });
  29672. Animation.Parse = function (parsedAnimation) {
  29673. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29674. var dataType = parsedAnimation.dataType;
  29675. var keys = [];
  29676. var data;
  29677. var index;
  29678. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29679. var key = parsedAnimation.keys[index];
  29680. switch (dataType) {
  29681. case Animation.ANIMATIONTYPE_FLOAT:
  29682. data = key.values[0];
  29683. break;
  29684. case Animation.ANIMATIONTYPE_QUATERNION:
  29685. data = BABYLON.Quaternion.FromArray(key.values);
  29686. break;
  29687. case Animation.ANIMATIONTYPE_MATRIX:
  29688. data = BABYLON.Matrix.FromArray(key.values);
  29689. break;
  29690. case Animation.ANIMATIONTYPE_COLOR3:
  29691. data = BABYLON.Color3.FromArray(key.values);
  29692. break;
  29693. case Animation.ANIMATIONTYPE_VECTOR3:
  29694. default:
  29695. data = BABYLON.Vector3.FromArray(key.values);
  29696. break;
  29697. }
  29698. keys.push({
  29699. frame: key.frame,
  29700. value: data
  29701. });
  29702. }
  29703. animation.setKeys(keys);
  29704. if (parsedAnimation.ranges) {
  29705. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29706. data = parsedAnimation.ranges[index];
  29707. animation.createRange(data.name, data.from, data.to);
  29708. }
  29709. }
  29710. return animation;
  29711. };
  29712. Animation.AppendSerializedAnimations = function (source, destination) {
  29713. if (source.animations) {
  29714. destination.animations = [];
  29715. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29716. var animation = source.animations[animationIndex];
  29717. destination.animations.push(animation.serialize());
  29718. }
  29719. }
  29720. };
  29721. // Statics
  29722. Animation._ANIMATIONTYPE_FLOAT = 0;
  29723. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29724. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29725. Animation._ANIMATIONTYPE_MATRIX = 3;
  29726. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29727. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29728. Animation._ANIMATIONTYPE_SIZE = 6;
  29729. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29730. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29731. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29732. return Animation;
  29733. }());
  29734. BABYLON.Animation = Animation;
  29735. })(BABYLON || (BABYLON = {}));
  29736. //# sourceMappingURL=babylon.animation.js.map
  29737. var BABYLON;
  29738. (function (BABYLON) {
  29739. var Animatable = (function () {
  29740. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29741. if (fromFrame === void 0) { fromFrame = 0; }
  29742. if (toFrame === void 0) { toFrame = 100; }
  29743. if (loopAnimation === void 0) { loopAnimation = false; }
  29744. if (speedRatio === void 0) { speedRatio = 1.0; }
  29745. this.target = target;
  29746. this.fromFrame = fromFrame;
  29747. this.toFrame = toFrame;
  29748. this.loopAnimation = loopAnimation;
  29749. this.speedRatio = speedRatio;
  29750. this.onAnimationEnd = onAnimationEnd;
  29751. this._animations = new Array();
  29752. this._paused = false;
  29753. this.animationStarted = false;
  29754. if (animations) {
  29755. this.appendAnimations(target, animations);
  29756. }
  29757. this._scene = scene;
  29758. scene._activeAnimatables.push(this);
  29759. }
  29760. // Methods
  29761. Animatable.prototype.getAnimations = function () {
  29762. return this._animations;
  29763. };
  29764. Animatable.prototype.appendAnimations = function (target, animations) {
  29765. for (var index = 0; index < animations.length; index++) {
  29766. var animation = animations[index];
  29767. animation._target = target;
  29768. this._animations.push(animation);
  29769. }
  29770. };
  29771. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29772. var animations = this._animations;
  29773. for (var index = 0; index < animations.length; index++) {
  29774. if (animations[index].targetProperty === property) {
  29775. return animations[index];
  29776. }
  29777. }
  29778. return null;
  29779. };
  29780. Animatable.prototype.reset = function () {
  29781. var animations = this._animations;
  29782. for (var index = 0; index < animations.length; index++) {
  29783. animations[index].reset();
  29784. }
  29785. this._localDelayOffset = null;
  29786. this._pausedDelay = null;
  29787. };
  29788. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29789. var animations = this._animations;
  29790. for (var index = 0; index < animations.length; index++) {
  29791. animations[index].enableBlending = true;
  29792. animations[index].blendingSpeed = blendingSpeed;
  29793. }
  29794. };
  29795. Animatable.prototype.disableBlending = function () {
  29796. var animations = this._animations;
  29797. for (var index = 0; index < animations.length; index++) {
  29798. animations[index].enableBlending = false;
  29799. }
  29800. };
  29801. Animatable.prototype.goToFrame = function (frame) {
  29802. var animations = this._animations;
  29803. if (animations[0]) {
  29804. var fps = animations[0].framePerSecond;
  29805. var currentFrame = animations[0].currentFrame;
  29806. var adjustTime = frame - currentFrame;
  29807. var delay = adjustTime * 1000 / fps;
  29808. this._localDelayOffset -= delay;
  29809. }
  29810. for (var index = 0; index < animations.length; index++) {
  29811. animations[index].goToFrame(frame);
  29812. }
  29813. };
  29814. Animatable.prototype.pause = function () {
  29815. if (this._paused) {
  29816. return;
  29817. }
  29818. this._paused = true;
  29819. };
  29820. Animatable.prototype.restart = function () {
  29821. this._paused = false;
  29822. };
  29823. Animatable.prototype.stop = function (animationName) {
  29824. var index = this._scene._activeAnimatables.indexOf(this);
  29825. if (index > -1) {
  29826. var animations = this._animations;
  29827. var numberOfAnimationsStopped = 0;
  29828. for (var index = animations.length - 1; index >= 0; index--) {
  29829. if (typeof animationName === "string" && animations[index].name != animationName) {
  29830. continue;
  29831. }
  29832. animations[index].reset();
  29833. animations.splice(index, 1);
  29834. numberOfAnimationsStopped++;
  29835. }
  29836. if (animations.length == numberOfAnimationsStopped) {
  29837. this._scene._activeAnimatables.splice(index, 1);
  29838. if (this.onAnimationEnd) {
  29839. this.onAnimationEnd();
  29840. }
  29841. }
  29842. }
  29843. };
  29844. Animatable.prototype._animate = function (delay) {
  29845. if (this._paused) {
  29846. this.animationStarted = false;
  29847. if (!this._pausedDelay) {
  29848. this._pausedDelay = delay;
  29849. }
  29850. return true;
  29851. }
  29852. if (!this._localDelayOffset) {
  29853. this._localDelayOffset = delay;
  29854. }
  29855. else if (this._pausedDelay) {
  29856. this._localDelayOffset += delay - this._pausedDelay;
  29857. this._pausedDelay = null;
  29858. }
  29859. // Animating
  29860. var running = false;
  29861. var animations = this._animations;
  29862. var index;
  29863. for (index = 0; index < animations.length; index++) {
  29864. var animation = animations[index];
  29865. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29866. running = running || isRunning;
  29867. }
  29868. this.animationStarted = running;
  29869. if (!running) {
  29870. // Remove from active animatables
  29871. index = this._scene._activeAnimatables.indexOf(this);
  29872. this._scene._activeAnimatables.splice(index, 1);
  29873. }
  29874. if (!running && this.onAnimationEnd) {
  29875. this.onAnimationEnd();
  29876. this.onAnimationEnd = null;
  29877. }
  29878. return running;
  29879. };
  29880. return Animatable;
  29881. }());
  29882. BABYLON.Animatable = Animatable;
  29883. })(BABYLON || (BABYLON = {}));
  29884. //# sourceMappingURL=babylon.animatable.js.map
  29885. var BABYLON;
  29886. (function (BABYLON) {
  29887. var EasingFunction = (function () {
  29888. function EasingFunction() {
  29889. // Properties
  29890. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29891. }
  29892. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29893. get: function () {
  29894. return EasingFunction._EASINGMODE_EASEIN;
  29895. },
  29896. enumerable: true,
  29897. configurable: true
  29898. });
  29899. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29900. get: function () {
  29901. return EasingFunction._EASINGMODE_EASEOUT;
  29902. },
  29903. enumerable: true,
  29904. configurable: true
  29905. });
  29906. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29907. get: function () {
  29908. return EasingFunction._EASINGMODE_EASEINOUT;
  29909. },
  29910. enumerable: true,
  29911. configurable: true
  29912. });
  29913. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29914. var n = Math.min(Math.max(easingMode, 0), 2);
  29915. this._easingMode = n;
  29916. };
  29917. EasingFunction.prototype.getEasingMode = function () {
  29918. return this._easingMode;
  29919. };
  29920. EasingFunction.prototype.easeInCore = function (gradient) {
  29921. throw new Error('You must implement this method');
  29922. };
  29923. EasingFunction.prototype.ease = function (gradient) {
  29924. switch (this._easingMode) {
  29925. case EasingFunction.EASINGMODE_EASEIN:
  29926. return this.easeInCore(gradient);
  29927. case EasingFunction.EASINGMODE_EASEOUT:
  29928. return (1 - this.easeInCore(1 - gradient));
  29929. }
  29930. if (gradient >= 0.5) {
  29931. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29932. }
  29933. return (this.easeInCore(gradient * 2) * 0.5);
  29934. };
  29935. //Statics
  29936. EasingFunction._EASINGMODE_EASEIN = 0;
  29937. EasingFunction._EASINGMODE_EASEOUT = 1;
  29938. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29939. return EasingFunction;
  29940. }());
  29941. BABYLON.EasingFunction = EasingFunction;
  29942. var CircleEase = (function (_super) {
  29943. __extends(CircleEase, _super);
  29944. function CircleEase() {
  29945. _super.apply(this, arguments);
  29946. }
  29947. CircleEase.prototype.easeInCore = function (gradient) {
  29948. gradient = Math.max(0, Math.min(1, gradient));
  29949. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29950. };
  29951. return CircleEase;
  29952. }(EasingFunction));
  29953. BABYLON.CircleEase = CircleEase;
  29954. var BackEase = (function (_super) {
  29955. __extends(BackEase, _super);
  29956. function BackEase(amplitude) {
  29957. if (amplitude === void 0) { amplitude = 1; }
  29958. _super.call(this);
  29959. this.amplitude = amplitude;
  29960. }
  29961. BackEase.prototype.easeInCore = function (gradient) {
  29962. var num = Math.max(0, this.amplitude);
  29963. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29964. };
  29965. return BackEase;
  29966. }(EasingFunction));
  29967. BABYLON.BackEase = BackEase;
  29968. var BounceEase = (function (_super) {
  29969. __extends(BounceEase, _super);
  29970. function BounceEase(bounces, bounciness) {
  29971. if (bounces === void 0) { bounces = 3; }
  29972. if (bounciness === void 0) { bounciness = 2; }
  29973. _super.call(this);
  29974. this.bounces = bounces;
  29975. this.bounciness = bounciness;
  29976. }
  29977. BounceEase.prototype.easeInCore = function (gradient) {
  29978. var y = Math.max(0.0, this.bounces);
  29979. var bounciness = this.bounciness;
  29980. if (bounciness <= 1.0) {
  29981. bounciness = 1.001;
  29982. }
  29983. var num9 = Math.pow(bounciness, y);
  29984. var num5 = 1.0 - bounciness;
  29985. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29986. var num15 = gradient * num4;
  29987. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29988. var num3 = Math.floor(num65);
  29989. var num13 = num3 + 1.0;
  29990. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29991. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29992. var num7 = (num8 + num12) * 0.5;
  29993. var num6 = gradient - num7;
  29994. var num2 = num7 - num8;
  29995. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29996. };
  29997. return BounceEase;
  29998. }(EasingFunction));
  29999. BABYLON.BounceEase = BounceEase;
  30000. var CubicEase = (function (_super) {
  30001. __extends(CubicEase, _super);
  30002. function CubicEase() {
  30003. _super.apply(this, arguments);
  30004. }
  30005. CubicEase.prototype.easeInCore = function (gradient) {
  30006. return (gradient * gradient * gradient);
  30007. };
  30008. return CubicEase;
  30009. }(EasingFunction));
  30010. BABYLON.CubicEase = CubicEase;
  30011. var ElasticEase = (function (_super) {
  30012. __extends(ElasticEase, _super);
  30013. function ElasticEase(oscillations, springiness) {
  30014. if (oscillations === void 0) { oscillations = 3; }
  30015. if (springiness === void 0) { springiness = 3; }
  30016. _super.call(this);
  30017. this.oscillations = oscillations;
  30018. this.springiness = springiness;
  30019. }
  30020. ElasticEase.prototype.easeInCore = function (gradient) {
  30021. var num2;
  30022. var num3 = Math.max(0.0, this.oscillations);
  30023. var num = Math.max(0.0, this.springiness);
  30024. if (num == 0) {
  30025. num2 = gradient;
  30026. }
  30027. else {
  30028. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30029. }
  30030. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30031. };
  30032. return ElasticEase;
  30033. }(EasingFunction));
  30034. BABYLON.ElasticEase = ElasticEase;
  30035. var ExponentialEase = (function (_super) {
  30036. __extends(ExponentialEase, _super);
  30037. function ExponentialEase(exponent) {
  30038. if (exponent === void 0) { exponent = 2; }
  30039. _super.call(this);
  30040. this.exponent = exponent;
  30041. }
  30042. ExponentialEase.prototype.easeInCore = function (gradient) {
  30043. if (this.exponent <= 0) {
  30044. return gradient;
  30045. }
  30046. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30047. };
  30048. return ExponentialEase;
  30049. }(EasingFunction));
  30050. BABYLON.ExponentialEase = ExponentialEase;
  30051. var PowerEase = (function (_super) {
  30052. __extends(PowerEase, _super);
  30053. function PowerEase(power) {
  30054. if (power === void 0) { power = 2; }
  30055. _super.call(this);
  30056. this.power = power;
  30057. }
  30058. PowerEase.prototype.easeInCore = function (gradient) {
  30059. var y = Math.max(0.0, this.power);
  30060. return Math.pow(gradient, y);
  30061. };
  30062. return PowerEase;
  30063. }(EasingFunction));
  30064. BABYLON.PowerEase = PowerEase;
  30065. var QuadraticEase = (function (_super) {
  30066. __extends(QuadraticEase, _super);
  30067. function QuadraticEase() {
  30068. _super.apply(this, arguments);
  30069. }
  30070. QuadraticEase.prototype.easeInCore = function (gradient) {
  30071. return (gradient * gradient);
  30072. };
  30073. return QuadraticEase;
  30074. }(EasingFunction));
  30075. BABYLON.QuadraticEase = QuadraticEase;
  30076. var QuarticEase = (function (_super) {
  30077. __extends(QuarticEase, _super);
  30078. function QuarticEase() {
  30079. _super.apply(this, arguments);
  30080. }
  30081. QuarticEase.prototype.easeInCore = function (gradient) {
  30082. return (gradient * gradient * gradient * gradient);
  30083. };
  30084. return QuarticEase;
  30085. }(EasingFunction));
  30086. BABYLON.QuarticEase = QuarticEase;
  30087. var QuinticEase = (function (_super) {
  30088. __extends(QuinticEase, _super);
  30089. function QuinticEase() {
  30090. _super.apply(this, arguments);
  30091. }
  30092. QuinticEase.prototype.easeInCore = function (gradient) {
  30093. return (gradient * gradient * gradient * gradient * gradient);
  30094. };
  30095. return QuinticEase;
  30096. }(EasingFunction));
  30097. BABYLON.QuinticEase = QuinticEase;
  30098. var SineEase = (function (_super) {
  30099. __extends(SineEase, _super);
  30100. function SineEase() {
  30101. _super.apply(this, arguments);
  30102. }
  30103. SineEase.prototype.easeInCore = function (gradient) {
  30104. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30105. };
  30106. return SineEase;
  30107. }(EasingFunction));
  30108. BABYLON.SineEase = SineEase;
  30109. var BezierCurveEase = (function (_super) {
  30110. __extends(BezierCurveEase, _super);
  30111. function BezierCurveEase(x1, y1, x2, y2) {
  30112. if (x1 === void 0) { x1 = 0; }
  30113. if (y1 === void 0) { y1 = 0; }
  30114. if (x2 === void 0) { x2 = 1; }
  30115. if (y2 === void 0) { y2 = 1; }
  30116. _super.call(this);
  30117. this.x1 = x1;
  30118. this.y1 = y1;
  30119. this.x2 = x2;
  30120. this.y2 = y2;
  30121. }
  30122. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30123. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30124. };
  30125. return BezierCurveEase;
  30126. }(EasingFunction));
  30127. BABYLON.BezierCurveEase = BezierCurveEase;
  30128. })(BABYLON || (BABYLON = {}));
  30129. //# sourceMappingURL=babylon.easing.js.map
  30130. var BABYLON;
  30131. (function (BABYLON) {
  30132. var Bone = (function (_super) {
  30133. __extends(Bone, _super);
  30134. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30135. _super.call(this, name, skeleton.getScene());
  30136. this.name = name;
  30137. this.children = new Array();
  30138. this.animations = new Array();
  30139. this._worldTransform = new BABYLON.Matrix();
  30140. this._absoluteTransform = new BABYLON.Matrix();
  30141. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30142. this._scaleMatrix = BABYLON.Matrix.Identity();
  30143. this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30144. this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30145. this._scalingDeterminant = 1;
  30146. this._syncScaleVector = function () {
  30147. var lm = this.getLocalMatrix();
  30148. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30149. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30150. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30151. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30152. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30153. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30154. this._scaleVector.x = xs * Math.sqrt(xsq);
  30155. this._scaleVector.y = ys * Math.sqrt(ysq);
  30156. this._scaleVector.z = zs * Math.sqrt(zsq);
  30157. if (this._parent) {
  30158. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30159. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30160. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30161. }
  30162. 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);
  30163. };
  30164. this._skeleton = skeleton;
  30165. this._matrix = matrix;
  30166. this._baseMatrix = matrix;
  30167. this._restPose = restPose ? restPose : matrix.clone();
  30168. skeleton.bones.push(this);
  30169. if (parentBone) {
  30170. this._parent = parentBone;
  30171. parentBone.children.push(this);
  30172. }
  30173. else {
  30174. this._parent = null;
  30175. }
  30176. this._updateDifferenceMatrix();
  30177. if (this.getAbsoluteTransform().determinant() < 0) {
  30178. this._scalingDeterminant *= -1;
  30179. }
  30180. }
  30181. // Members
  30182. Bone.prototype.getParent = function () {
  30183. return this._parent;
  30184. };
  30185. Bone.prototype.getLocalMatrix = function () {
  30186. return this._matrix;
  30187. };
  30188. Bone.prototype.getBaseMatrix = function () {
  30189. return this._baseMatrix;
  30190. };
  30191. Bone.prototype.getRestPose = function () {
  30192. return this._restPose;
  30193. };
  30194. Bone.prototype.returnToRest = function () {
  30195. this.updateMatrix(this._restPose.clone());
  30196. };
  30197. Bone.prototype.getWorldMatrix = function () {
  30198. return this._worldTransform;
  30199. };
  30200. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30201. return this._invertedAbsoluteTransform;
  30202. };
  30203. Bone.prototype.getAbsoluteTransform = function () {
  30204. return this._absoluteTransform;
  30205. };
  30206. // Methods
  30207. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30208. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30209. this._baseMatrix = matrix.clone();
  30210. this._matrix = matrix.clone();
  30211. this._skeleton._markAsDirty();
  30212. if (updateDifferenceMatrix) {
  30213. this._updateDifferenceMatrix();
  30214. }
  30215. };
  30216. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30217. if (!rootMatrix) {
  30218. rootMatrix = this._baseMatrix;
  30219. }
  30220. if (this._parent) {
  30221. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30222. }
  30223. else {
  30224. this._absoluteTransform.copyFrom(rootMatrix);
  30225. }
  30226. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  30227. for (var index = 0; index < this.children.length; index++) {
  30228. this.children[index]._updateDifferenceMatrix();
  30229. }
  30230. };
  30231. Bone.prototype.markAsDirty = function () {
  30232. this._currentRenderId++;
  30233. this._skeleton._markAsDirty();
  30234. };
  30235. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  30236. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30237. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  30238. // all animation may be coming from a library skeleton, so may need to create animation
  30239. if (this.animations.length === 0) {
  30240. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  30241. this.animations[0].setKeys([]);
  30242. }
  30243. // get animation info / verify there is such a range from the source bone
  30244. var sourceRange = source.animations[0].getRange(rangeName);
  30245. if (!sourceRange) {
  30246. return false;
  30247. }
  30248. var from = sourceRange.from;
  30249. var to = sourceRange.to;
  30250. var sourceKeys = source.animations[0].getKeys();
  30251. // rescaling prep
  30252. var sourceBoneLength = source.length;
  30253. var sourceParent = source.getParent();
  30254. var parent = this.getParent();
  30255. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  30256. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  30257. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  30258. var destKeys = this.animations[0].getKeys();
  30259. // loop vars declaration
  30260. var orig;
  30261. var origTranslation;
  30262. var mat;
  30263. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  30264. orig = sourceKeys[key];
  30265. if (orig.frame >= from && orig.frame <= to) {
  30266. if (rescaleAsRequired) {
  30267. mat = orig.value.clone();
  30268. // scale based on parent ratio, when bone has parent
  30269. if (parentScalingReqd) {
  30270. origTranslation = mat.getTranslation();
  30271. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  30272. }
  30273. else if (dimensionsScalingReqd) {
  30274. origTranslation = mat.getTranslation();
  30275. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  30276. }
  30277. else {
  30278. mat = orig.value;
  30279. }
  30280. }
  30281. else {
  30282. mat = orig.value;
  30283. }
  30284. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  30285. }
  30286. }
  30287. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  30288. return true;
  30289. };
  30290. Bone.prototype.translate = function (vec, space, mesh) {
  30291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30292. var lm = this.getLocalMatrix();
  30293. if (space == BABYLON.Space.LOCAL) {
  30294. lm.m[12] += vec.x;
  30295. lm.m[13] += vec.y;
  30296. lm.m[14] += vec.z;
  30297. }
  30298. else {
  30299. this._skeleton.computeAbsoluteTransforms();
  30300. var tmat = BABYLON.Tmp.Matrix[0];
  30301. var tvec = BABYLON.Tmp.Vector3[0];
  30302. if (mesh) {
  30303. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30304. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30305. }
  30306. else {
  30307. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30308. }
  30309. tmat.m[12] = 0;
  30310. tmat.m[13] = 0;
  30311. tmat.m[14] = 0;
  30312. tmat.invert();
  30313. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  30314. lm.m[12] += tvec.x;
  30315. lm.m[13] += tvec.y;
  30316. lm.m[14] += tvec.z;
  30317. }
  30318. this.markAsDirty();
  30319. };
  30320. Bone.prototype.setPosition = function (position, space, mesh) {
  30321. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30322. var lm = this.getLocalMatrix();
  30323. if (space == BABYLON.Space.LOCAL) {
  30324. lm.m[12] = position.x;
  30325. lm.m[13] = position.y;
  30326. lm.m[14] = position.z;
  30327. }
  30328. else {
  30329. this._skeleton.computeAbsoluteTransforms();
  30330. var tmat = BABYLON.Tmp.Matrix[0];
  30331. var vec = BABYLON.Tmp.Vector3[0];
  30332. if (mesh) {
  30333. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30334. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30335. }
  30336. else {
  30337. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30338. }
  30339. tmat.invert();
  30340. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  30341. lm.m[12] = vec.x;
  30342. lm.m[13] = vec.y;
  30343. lm.m[14] = vec.z;
  30344. }
  30345. this.markAsDirty();
  30346. };
  30347. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  30348. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  30349. };
  30350. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  30351. if (scaleChildren === void 0) { scaleChildren = false; }
  30352. if (this.animations[0] && !this.animations[0].isStopped()) {
  30353. if (!scaleChildren) {
  30354. this._negateScaleChildren.x = 1 / x;
  30355. this._negateScaleChildren.y = 1 / y;
  30356. this._negateScaleChildren.z = 1 / z;
  30357. }
  30358. this._syncScaleVector();
  30359. }
  30360. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  30361. };
  30362. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  30363. if (scaleChildren === void 0) { scaleChildren = false; }
  30364. var locMat = this.getLocalMatrix();
  30365. var origLocMat = BABYLON.Tmp.Matrix[0];
  30366. origLocMat.copyFrom(locMat);
  30367. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  30368. origLocMatInv.copyFrom(origLocMat);
  30369. origLocMatInv.invert();
  30370. var scaleMat = BABYLON.Tmp.Matrix[2];
  30371. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  30372. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  30373. this._scaleVector.x *= x;
  30374. this._scaleVector.y *= y;
  30375. this._scaleVector.z *= z;
  30376. locMat.multiplyToRef(origLocMatInv, locMat);
  30377. locMat.multiplyToRef(scaleMat, locMat);
  30378. locMat.multiplyToRef(origLocMat, locMat);
  30379. var parent = this.getParent();
  30380. if (parent) {
  30381. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  30382. }
  30383. else {
  30384. this.getAbsoluteTransform().copyFrom(locMat);
  30385. }
  30386. var len = this.children.length;
  30387. scaleMat.invert();
  30388. for (var i = 0; i < len; i++) {
  30389. var child = this.children[i];
  30390. var cm = child.getLocalMatrix();
  30391. cm.multiplyToRef(scaleMat, cm);
  30392. var lm = child.getLocalMatrix();
  30393. lm.m[12] *= x;
  30394. lm.m[13] *= y;
  30395. lm.m[14] *= z;
  30396. }
  30397. this.computeAbsoluteTransforms();
  30398. if (scaleChildren) {
  30399. for (var i = 0; i < len; i++) {
  30400. this.children[i].scale(x, y, z, scaleChildren);
  30401. }
  30402. }
  30403. this.markAsDirty();
  30404. };
  30405. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  30406. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30407. var rotMat = BABYLON.Tmp.Matrix[0];
  30408. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  30409. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30410. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30411. rotMatInv.multiplyToRef(rotMat, rotMat);
  30412. this._rotateWithMatrix(rotMat, space, mesh);
  30413. };
  30414. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  30415. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30416. var rmat = BABYLON.Tmp.Matrix[0];
  30417. rmat.m[12] = 0;
  30418. rmat.m[13] = 0;
  30419. rmat.m[14] = 0;
  30420. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  30421. this._rotateWithMatrix(rmat, space, mesh);
  30422. };
  30423. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  30424. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30425. var rotMat = BABYLON.Tmp.Matrix[0];
  30426. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  30427. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30428. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30429. rotMatInv.multiplyToRef(rotMat, rotMat);
  30430. this._rotateWithMatrix(rotMat, space, mesh);
  30431. };
  30432. Bone.prototype.setRotation = function (rotation, space, mesh) {
  30433. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30434. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  30435. };
  30436. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  30437. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30438. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30439. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30440. var rotMat = BABYLON.Tmp.Matrix[1];
  30441. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  30442. rotMatInv.multiplyToRef(rotMat, rotMat);
  30443. this._rotateWithMatrix(rotMat, space, mesh);
  30444. };
  30445. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  30446. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30447. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30448. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30449. var rotMat2 = BABYLON.Tmp.Matrix[1];
  30450. rotMat2.copyFrom(rotMat);
  30451. rotMatInv.multiplyToRef(rotMat, rotMat2);
  30452. this._rotateWithMatrix(rotMat2, space, mesh);
  30453. };
  30454. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  30455. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30456. var lmat = this.getLocalMatrix();
  30457. var lx = lmat.m[12];
  30458. var ly = lmat.m[13];
  30459. var lz = lmat.m[14];
  30460. var parent = this.getParent();
  30461. var parentScale = BABYLON.Tmp.Matrix[3];
  30462. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  30463. if (parent) {
  30464. if (space == BABYLON.Space.WORLD) {
  30465. if (mesh) {
  30466. parentScale.copyFrom(mesh.getWorldMatrix());
  30467. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  30468. }
  30469. else {
  30470. parentScale.copyFrom(parent.getAbsoluteTransform());
  30471. }
  30472. }
  30473. else {
  30474. parentScale = parent._scaleMatrix;
  30475. }
  30476. parentScaleInv.copyFrom(parentScale);
  30477. parentScaleInv.invert();
  30478. lmat.multiplyToRef(parentScale, lmat);
  30479. lmat.multiplyToRef(rmat, lmat);
  30480. lmat.multiplyToRef(parentScaleInv, lmat);
  30481. }
  30482. else {
  30483. if (space == BABYLON.Space.WORLD && mesh) {
  30484. parentScale.copyFrom(mesh.getWorldMatrix());
  30485. parentScaleInv.copyFrom(parentScale);
  30486. parentScaleInv.invert();
  30487. lmat.multiplyToRef(parentScale, lmat);
  30488. lmat.multiplyToRef(rmat, lmat);
  30489. lmat.multiplyToRef(parentScaleInv, lmat);
  30490. }
  30491. else {
  30492. lmat.multiplyToRef(rmat, lmat);
  30493. }
  30494. }
  30495. lmat.m[12] = lx;
  30496. lmat.m[13] = ly;
  30497. lmat.m[14] = lz;
  30498. this.computeAbsoluteTransforms();
  30499. this.markAsDirty();
  30500. };
  30501. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  30502. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30503. if (space == BABYLON.Space.WORLD) {
  30504. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30505. scaleMatrix.copyFrom(this._scaleMatrix);
  30506. rotMatInv.copyFrom(this.getAbsoluteTransform());
  30507. if (mesh) {
  30508. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  30509. var meshScale = BABYLON.Tmp.Matrix[3];
  30510. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  30511. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  30512. }
  30513. rotMatInv.invert();
  30514. scaleMatrix.m[0] *= this._scalingDeterminant;
  30515. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30516. }
  30517. else {
  30518. rotMatInv.copyFrom(this.getLocalMatrix());
  30519. rotMatInv.invert();
  30520. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30521. scaleMatrix.copyFrom(this._scaleMatrix);
  30522. if (this._parent) {
  30523. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  30524. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  30525. pscaleMatrix.invert();
  30526. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  30527. }
  30528. else {
  30529. scaleMatrix.m[0] *= this._scalingDeterminant;
  30530. }
  30531. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30532. }
  30533. };
  30534. Bone.prototype.getScale = function () {
  30535. return this._scaleVector.clone();
  30536. };
  30537. Bone.prototype.getScaleToRef = function (result) {
  30538. result.copyFrom(this._scaleVector);
  30539. };
  30540. Bone.prototype.getPosition = function (space, mesh) {
  30541. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30542. var pos = BABYLON.Vector3.Zero();
  30543. this.getPositionToRef(space, mesh, pos);
  30544. return pos;
  30545. };
  30546. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  30547. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30548. if (space == BABYLON.Space.LOCAL) {
  30549. var lm = this.getLocalMatrix();
  30550. result.x = lm.m[12];
  30551. result.y = lm.m[13];
  30552. result.z = lm.m[14];
  30553. }
  30554. else {
  30555. this._skeleton.computeAbsoluteTransforms();
  30556. var tmat = BABYLON.Tmp.Matrix[0];
  30557. if (mesh) {
  30558. tmat.copyFrom(this.getAbsoluteTransform());
  30559. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30560. }
  30561. else {
  30562. tmat = this.getAbsoluteTransform();
  30563. }
  30564. result.x = tmat.m[12];
  30565. result.y = tmat.m[13];
  30566. result.z = tmat.m[14];
  30567. }
  30568. };
  30569. Bone.prototype.getAbsolutePosition = function (mesh) {
  30570. var pos = BABYLON.Vector3.Zero();
  30571. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  30572. return pos;
  30573. };
  30574. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  30575. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  30576. };
  30577. Bone.prototype.computeAbsoluteTransforms = function () {
  30578. if (this._parent) {
  30579. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30580. }
  30581. else {
  30582. this._absoluteTransform.copyFrom(this._matrix);
  30583. var poseMatrix = this._skeleton.getPoseMatrix();
  30584. if (poseMatrix) {
  30585. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  30586. }
  30587. }
  30588. var children = this.children;
  30589. var len = children.length;
  30590. for (var i = 0; i < len; i++) {
  30591. children[i].computeAbsoluteTransforms();
  30592. }
  30593. };
  30594. Bone.prototype.getDirection = function (localAxis, mesh) {
  30595. var result = BABYLON.Vector3.Zero();
  30596. this.getDirectionToRef(localAxis, mesh, result);
  30597. return result;
  30598. };
  30599. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  30600. this._skeleton.computeAbsoluteTransforms();
  30601. var mat = BABYLON.Tmp.Matrix[0];
  30602. mat.copyFrom(this.getAbsoluteTransform());
  30603. if (mesh) {
  30604. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30605. }
  30606. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  30607. result.normalize();
  30608. };
  30609. Bone.prototype.getRotation = function (space, mesh) {
  30610. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30611. var result = BABYLON.Vector3.Zero();
  30612. this.getRotationToRef(space, mesh, result);
  30613. return result;
  30614. };
  30615. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  30616. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30617. var quat = BABYLON.Tmp.Quaternion[0];
  30618. this.getRotationQuaternionToRef(space, mesh, quat);
  30619. quat.toEulerAnglesToRef(result);
  30620. };
  30621. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  30622. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30623. var result = BABYLON.Quaternion.Identity();
  30624. this.getRotationQuaternionToRef(space, mesh, result);
  30625. return result;
  30626. };
  30627. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  30628. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30629. if (space == BABYLON.Space.LOCAL) {
  30630. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30631. }
  30632. else {
  30633. var mat = BABYLON.Tmp.Matrix[0];
  30634. var amat = this.getAbsoluteTransform();
  30635. if (mesh) {
  30636. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30637. }
  30638. else {
  30639. mat.copyFrom(amat);
  30640. }
  30641. mat.m[0] *= this._scalingDeterminant;
  30642. mat.m[1] *= this._scalingDeterminant;
  30643. mat.m[2] *= this._scalingDeterminant;
  30644. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30645. }
  30646. };
  30647. Bone.prototype.getRotationMatrix = function (space, mesh) {
  30648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30649. var result = BABYLON.Matrix.Identity();
  30650. this.getRotationMatrixToRef(space, mesh, result);
  30651. return result;
  30652. };
  30653. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  30654. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30655. if (space == BABYLON.Space.LOCAL) {
  30656. this.getLocalMatrix().getRotationMatrixToRef(result);
  30657. }
  30658. else {
  30659. var mat = BABYLON.Tmp.Matrix[0];
  30660. var amat = this.getAbsoluteTransform();
  30661. if (mesh) {
  30662. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30663. }
  30664. else {
  30665. mat.copyFrom(amat);
  30666. }
  30667. mat.m[0] *= this._scalingDeterminant;
  30668. mat.m[1] *= this._scalingDeterminant;
  30669. mat.m[2] *= this._scalingDeterminant;
  30670. mat.getRotationMatrixToRef(result);
  30671. }
  30672. };
  30673. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  30674. var result = BABYLON.Vector3.Zero();
  30675. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  30676. return result;
  30677. };
  30678. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  30679. this._skeleton.computeAbsoluteTransforms();
  30680. var tmat = BABYLON.Tmp.Matrix[0];
  30681. if (mesh) {
  30682. tmat.copyFrom(this.getAbsoluteTransform());
  30683. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30684. }
  30685. else {
  30686. tmat = this.getAbsoluteTransform();
  30687. }
  30688. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30689. };
  30690. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  30691. var result = BABYLON.Vector3.Zero();
  30692. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  30693. return result;
  30694. };
  30695. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  30696. this._skeleton.computeAbsoluteTransforms();
  30697. var tmat = BABYLON.Tmp.Matrix[0];
  30698. tmat.copyFrom(this.getAbsoluteTransform());
  30699. if (mesh) {
  30700. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30701. }
  30702. tmat.invert();
  30703. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30704. };
  30705. return Bone;
  30706. }(BABYLON.Node));
  30707. BABYLON.Bone = Bone;
  30708. })(BABYLON || (BABYLON = {}));
  30709. //# sourceMappingURL=babylon.bone.js.map
  30710. var BABYLON;
  30711. (function (BABYLON) {
  30712. var BoneIKController = (function () {
  30713. function BoneIKController(mesh, bone, options) {
  30714. this.targetPosition = BABYLON.Vector3.Zero();
  30715. this.poleTargetPosition = BABYLON.Vector3.Zero();
  30716. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  30717. this.poleAngle = 0;
  30718. this.slerpAmount = 1;
  30719. this._bone1Quat = BABYLON.Quaternion.Identity();
  30720. this._bone1Mat = BABYLON.Matrix.Identity();
  30721. this._bone2Ang = Math.PI;
  30722. this._maxAngle = Math.PI;
  30723. this._tmpVec1 = BABYLON.Vector3.Zero();
  30724. this._tmpVec2 = BABYLON.Vector3.Zero();
  30725. this._tmpVec3 = BABYLON.Vector3.Zero();
  30726. this._tmpVec4 = BABYLON.Vector3.Zero();
  30727. this._tmpVec5 = BABYLON.Vector3.Zero();
  30728. this._tmpMat1 = BABYLON.Matrix.Identity();
  30729. this._tmpMat2 = BABYLON.Matrix.Identity();
  30730. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  30731. this._rightHandedSystem = false;
  30732. this._bendAxis = BABYLON.Vector3.Right();
  30733. this._slerping = false;
  30734. this._bone2 = bone;
  30735. this._bone1 = bone.getParent();
  30736. this.mesh = mesh;
  30737. if (bone.getAbsoluteTransform().determinant() > 0) {
  30738. this._rightHandedSystem = true;
  30739. this._bendAxis.x = 0;
  30740. this._bendAxis.y = 0;
  30741. this._bendAxis.z = 1;
  30742. }
  30743. if (this._bone1.length) {
  30744. var boneScale1 = this._bone1.getScale();
  30745. var boneScale2 = this._bone2.getScale();
  30746. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  30747. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  30748. }
  30749. else if (this._bone1.children[0]) {
  30750. mesh.computeWorldMatrix(true);
  30751. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  30752. var pos2 = this._bone2.getAbsolutePosition(mesh);
  30753. var pos3 = this._bone1.getAbsolutePosition(mesh);
  30754. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  30755. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  30756. }
  30757. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  30758. this.maxAngle = Math.PI;
  30759. if (options) {
  30760. if (options.targetMesh) {
  30761. this.targetMesh = options.targetMesh;
  30762. this.targetMesh.computeWorldMatrix(true);
  30763. }
  30764. if (options.poleTargetMesh) {
  30765. this.poleTargetMesh = options.poleTargetMesh;
  30766. this.poleTargetMesh.computeWorldMatrix(true);
  30767. }
  30768. else if (options.poleTargetBone) {
  30769. this.poleTargetBone = options.poleTargetBone;
  30770. }
  30771. else if (this._bone1.getParent()) {
  30772. this.poleTargetBone = this._bone1.getParent();
  30773. }
  30774. if (options.poleTargetLocalOffset) {
  30775. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  30776. }
  30777. if (options.poleAngle) {
  30778. this.poleAngle = options.poleAngle;
  30779. }
  30780. if (options.bendAxis) {
  30781. this._bendAxis.copyFrom(options.bendAxis);
  30782. }
  30783. if (options.maxAngle) {
  30784. this.maxAngle = options.maxAngle;
  30785. }
  30786. if (options.slerpAmount) {
  30787. this.slerpAmount = options.slerpAmount;
  30788. }
  30789. }
  30790. }
  30791. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  30792. get: function () {
  30793. return this._maxAngle;
  30794. },
  30795. set: function (value) {
  30796. this._setMaxAngle(value);
  30797. },
  30798. enumerable: true,
  30799. configurable: true
  30800. });
  30801. BoneIKController.prototype._setMaxAngle = function (ang) {
  30802. if (ang < 0) {
  30803. ang = 0;
  30804. }
  30805. if (ang > Math.PI || ang == undefined) {
  30806. ang = Math.PI;
  30807. }
  30808. this._maxAngle = ang;
  30809. var a = this._bone1Length;
  30810. var b = this._bone2Length;
  30811. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  30812. };
  30813. BoneIKController.prototype.update = function () {
  30814. var bone1 = this._bone1;
  30815. var target = this.targetPosition;
  30816. var poleTarget = this.poleTargetPosition;
  30817. var mat1 = this._tmpMat1;
  30818. var mat2 = this._tmpMat2;
  30819. if (this.targetMesh) {
  30820. target.copyFrom(this.targetMesh.getAbsolutePosition());
  30821. }
  30822. if (this.poleTargetBone) {
  30823. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  30824. }
  30825. else if (this.poleTargetMesh) {
  30826. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  30827. }
  30828. var bonePos = this._tmpVec1;
  30829. var zaxis = this._tmpVec2;
  30830. var xaxis = this._tmpVec3;
  30831. var yaxis = this._tmpVec4;
  30832. var upAxis = this._tmpVec5;
  30833. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  30834. poleTarget.subtractToRef(bonePos, upAxis);
  30835. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  30836. upAxis.y = 1;
  30837. }
  30838. else {
  30839. upAxis.normalize();
  30840. }
  30841. target.subtractToRef(bonePos, yaxis);
  30842. yaxis.normalize();
  30843. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  30844. zaxis.normalize();
  30845. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  30846. xaxis.normalize();
  30847. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30848. var a = this._bone1Length;
  30849. var b = this._bone2Length;
  30850. var c = BABYLON.Vector3.Distance(bonePos, target);
  30851. if (this._maxReach > 0) {
  30852. c = Math.min(this._maxReach, c);
  30853. }
  30854. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  30855. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  30856. if (acosa > 1) {
  30857. acosa = 1;
  30858. }
  30859. if (acosb > 1) {
  30860. acosb = 1;
  30861. }
  30862. if (acosa < -1) {
  30863. acosa = -1;
  30864. }
  30865. if (acosb < -1) {
  30866. acosb = -1;
  30867. }
  30868. var angA = Math.acos(acosa);
  30869. var angB = Math.acos(acosb);
  30870. var angC = -angA - angB;
  30871. if (this._rightHandedSystem) {
  30872. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  30873. mat2.multiplyToRef(mat1, mat1);
  30874. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  30875. mat2.multiplyToRef(mat1, mat1);
  30876. }
  30877. else {
  30878. this._tmpVec1.copyFrom(this._bendAxis);
  30879. this._tmpVec1.x *= -1;
  30880. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  30881. mat2.multiplyToRef(mat1, mat1);
  30882. }
  30883. if (this.poleAngle) {
  30884. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  30885. mat1.multiplyToRef(mat2, mat1);
  30886. }
  30887. if (this.slerpAmount < 1) {
  30888. if (!this._slerping) {
  30889. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  30890. }
  30891. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  30892. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  30893. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  30894. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  30895. this._slerping = true;
  30896. }
  30897. else {
  30898. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30899. this._bone1Mat.copyFrom(mat1);
  30900. this._slerping = false;
  30901. }
  30902. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  30903. this._bone2Ang = angC;
  30904. };
  30905. return BoneIKController;
  30906. }());
  30907. BABYLON.BoneIKController = BoneIKController;
  30908. })(BABYLON || (BABYLON = {}));
  30909. //# sourceMappingURL=babylon.boneIKController.js.map
  30910. var BABYLON;
  30911. (function (BABYLON) {
  30912. var BoneLookController = (function () {
  30913. function BoneLookController(mesh, bone, target, options) {
  30914. this.upAxis = BABYLON.Vector3.Up();
  30915. this.adjustYaw = 0;
  30916. this.adjustPitch = 0;
  30917. this.adjustRoll = 0;
  30918. this._tmpVec1 = BABYLON.Vector3.Zero();
  30919. this._tmpVec2 = BABYLON.Vector3.Zero();
  30920. this._tmpVec3 = BABYLON.Vector3.Zero();
  30921. this._tmpVec4 = BABYLON.Vector3.Zero();
  30922. this._tmpMat1 = BABYLON.Matrix.Identity();
  30923. this._tmpMat2 = BABYLON.Matrix.Identity();
  30924. this.mesh = mesh;
  30925. this.bone = bone;
  30926. this.target = target;
  30927. if (options) {
  30928. if (options.adjustYaw) {
  30929. this.adjustYaw = options.adjustYaw;
  30930. }
  30931. if (options.adjustPitch) {
  30932. this.adjustPitch = options.adjustPitch;
  30933. }
  30934. if (options.adjustRoll) {
  30935. this.adjustRoll = options.adjustRoll;
  30936. }
  30937. }
  30938. }
  30939. BoneLookController.prototype.update = function () {
  30940. var bone = this.bone;
  30941. var target = this.target;
  30942. var bonePos = this._tmpVec1;
  30943. var zaxis = this._tmpVec2;
  30944. var xaxis = this._tmpVec3;
  30945. var yaxis = this._tmpVec4;
  30946. var mat1 = this._tmpMat1;
  30947. var mat2 = this._tmpMat2;
  30948. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  30949. target.subtractToRef(bonePos, zaxis);
  30950. zaxis.normalize();
  30951. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  30952. xaxis.normalize();
  30953. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  30954. yaxis.normalize();
  30955. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30956. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  30957. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  30958. mat2.multiplyToRef(mat1, mat1);
  30959. }
  30960. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30961. };
  30962. return BoneLookController;
  30963. }());
  30964. BABYLON.BoneLookController = BoneLookController;
  30965. })(BABYLON || (BABYLON = {}));
  30966. //# sourceMappingURL=babylon.boneLookController.js.map
  30967. var BABYLON;
  30968. (function (BABYLON) {
  30969. var Skeleton = (function () {
  30970. function Skeleton(name, id, scene) {
  30971. this.name = name;
  30972. this.id = id;
  30973. this.bones = new Array();
  30974. this.needInitialSkinMatrix = false;
  30975. this._isDirty = true;
  30976. this._meshesWithPoseMatrix = new Array();
  30977. this._identity = BABYLON.Matrix.Identity();
  30978. this._ranges = {};
  30979. this._lastAbsoluteTransformsUpdateId = -1;
  30980. this.bones = [];
  30981. this._scene = scene;
  30982. scene.skeletons.push(this);
  30983. //make sure it will recalculate the matrix next time prepare is called.
  30984. this._isDirty = true;
  30985. }
  30986. // Members
  30987. Skeleton.prototype.getTransformMatrices = function (mesh) {
  30988. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  30989. return mesh._bonesTransformMatrices;
  30990. }
  30991. if (!this._transformMatrices) {
  30992. this.prepare();
  30993. }
  30994. return this._transformMatrices;
  30995. };
  30996. Skeleton.prototype.getScene = function () {
  30997. return this._scene;
  30998. };
  30999. // Methods
  31000. /**
  31001. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31002. */
  31003. Skeleton.prototype.toString = function (fullDetails) {
  31004. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  31005. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31006. if (fullDetails) {
  31007. ret += ", Ranges: {";
  31008. var first = true;
  31009. for (var name_1 in this._ranges) {
  31010. if (first) {
  31011. ret += ", ";
  31012. first = false;
  31013. }
  31014. ret += name_1;
  31015. }
  31016. ret += "}";
  31017. }
  31018. return ret;
  31019. };
  31020. /**
  31021. * Get bone's index searching by name
  31022. * @param {string} name is bone's name to search for
  31023. * @return {number} Indice of the bone. Returns -1 if not found
  31024. */
  31025. Skeleton.prototype.getBoneIndexByName = function (name) {
  31026. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  31027. if (this.bones[boneIndex].name === name) {
  31028. return boneIndex;
  31029. }
  31030. }
  31031. return -1;
  31032. };
  31033. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  31034. // check name not already in use
  31035. if (!this._ranges[name]) {
  31036. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  31037. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31038. if (this.bones[i].animations[0]) {
  31039. this.bones[i].animations[0].createRange(name, from, to);
  31040. }
  31041. }
  31042. }
  31043. };
  31044. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31045. if (deleteFrames === void 0) { deleteFrames = true; }
  31046. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31047. if (this.bones[i].animations[0]) {
  31048. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31049. }
  31050. }
  31051. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31052. };
  31053. Skeleton.prototype.getAnimationRange = function (name) {
  31054. return this._ranges[name];
  31055. };
  31056. /**
  31057. * Returns as an Array, all AnimationRanges defined on this skeleton
  31058. */
  31059. Skeleton.prototype.getAnimationRanges = function () {
  31060. var animationRanges = [];
  31061. var name;
  31062. var i = 0;
  31063. for (name in this._ranges) {
  31064. animationRanges[i] = this._ranges[name];
  31065. i++;
  31066. }
  31067. return animationRanges;
  31068. };
  31069. /**
  31070. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31071. */
  31072. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  31073. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31074. if (this._ranges[name] || !source.getAnimationRange(name)) {
  31075. return false;
  31076. }
  31077. var ret = true;
  31078. var frameOffset = this._getHighestAnimationFrame() + 1;
  31079. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  31080. var boneDict = {};
  31081. var sourceBones = source.bones;
  31082. var nBones;
  31083. var i;
  31084. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  31085. boneDict[sourceBones[i].name] = sourceBones[i];
  31086. }
  31087. if (this.bones.length !== sourceBones.length) {
  31088. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  31089. ret = false;
  31090. }
  31091. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  31092. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  31093. var boneName = this.bones[i].name;
  31094. var sourceBone = boneDict[boneName];
  31095. if (sourceBone) {
  31096. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  31097. }
  31098. else {
  31099. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  31100. ret = false;
  31101. }
  31102. }
  31103. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31104. var range = source.getAnimationRange(name);
  31105. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31106. return ret;
  31107. };
  31108. Skeleton.prototype.returnToRest = function () {
  31109. for (var index = 0; index < this.bones.length; index++) {
  31110. this.bones[index].returnToRest();
  31111. }
  31112. };
  31113. Skeleton.prototype._getHighestAnimationFrame = function () {
  31114. var ret = 0;
  31115. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31116. if (this.bones[i].animations[0]) {
  31117. var highest = this.bones[i].animations[0].getHighestFrame();
  31118. if (ret < highest) {
  31119. ret = highest;
  31120. }
  31121. }
  31122. }
  31123. return ret;
  31124. };
  31125. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31126. var range = this.getAnimationRange(name);
  31127. if (!range) {
  31128. return null;
  31129. }
  31130. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31131. };
  31132. Skeleton.prototype._markAsDirty = function () {
  31133. this._isDirty = true;
  31134. };
  31135. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31136. this._meshesWithPoseMatrix.push(mesh);
  31137. };
  31138. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31139. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31140. if (index > -1) {
  31141. this._meshesWithPoseMatrix.splice(index, 1);
  31142. }
  31143. };
  31144. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31145. for (var index = 0; index < this.bones.length; index++) {
  31146. var bone = this.bones[index];
  31147. var parentBone = bone.getParent();
  31148. if (parentBone) {
  31149. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31150. }
  31151. else {
  31152. if (initialSkinMatrix) {
  31153. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31154. }
  31155. else {
  31156. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31157. }
  31158. }
  31159. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31160. }
  31161. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31162. };
  31163. Skeleton.prototype.prepare = function () {
  31164. if (!this._isDirty) {
  31165. return;
  31166. }
  31167. if (this.needInitialSkinMatrix) {
  31168. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31169. var mesh = this._meshesWithPoseMatrix[index];
  31170. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31171. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31172. }
  31173. var poseMatrix = mesh.getPoseMatrix();
  31174. // Prepare bones
  31175. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31176. var bone = this.bones[boneIndex];
  31177. if (!bone.getParent()) {
  31178. var matrix = bone.getBaseMatrix();
  31179. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31180. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31181. }
  31182. }
  31183. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31184. }
  31185. }
  31186. else {
  31187. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31188. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31189. }
  31190. this._computeTransformMatrices(this._transformMatrices, null);
  31191. }
  31192. this._isDirty = false;
  31193. this._scene._activeBones.addCount(this.bones.length, false);
  31194. };
  31195. Skeleton.prototype.getAnimatables = function () {
  31196. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31197. this._animatables = [];
  31198. for (var index = 0; index < this.bones.length; index++) {
  31199. this._animatables.push(this.bones[index]);
  31200. }
  31201. }
  31202. return this._animatables;
  31203. };
  31204. Skeleton.prototype.clone = function (name, id) {
  31205. var result = new Skeleton(name, id || name, this._scene);
  31206. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31207. for (var index = 0; index < this.bones.length; index++) {
  31208. var source = this.bones[index];
  31209. var parentBone = null;
  31210. if (source.getParent()) {
  31211. var parentIndex = this.bones.indexOf(source.getParent());
  31212. parentBone = result.bones[parentIndex];
  31213. }
  31214. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31215. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31216. }
  31217. if (this._ranges) {
  31218. result._ranges = {};
  31219. for (var rangeName in this._ranges) {
  31220. result._ranges[rangeName] = this._ranges[rangeName].clone();
  31221. }
  31222. }
  31223. this._isDirty = true;
  31224. return result;
  31225. };
  31226. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  31227. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  31228. this.bones.forEach(function (bone) {
  31229. bone.animations.forEach(function (animation) {
  31230. animation.enableBlending = true;
  31231. animation.blendingSpeed = blendingSpeed;
  31232. });
  31233. });
  31234. };
  31235. Skeleton.prototype.dispose = function () {
  31236. this._meshesWithPoseMatrix = [];
  31237. // Animations
  31238. this.getScene().stopAnimation(this);
  31239. // Remove from scene
  31240. this.getScene().removeSkeleton(this);
  31241. };
  31242. Skeleton.prototype.serialize = function () {
  31243. var serializationObject = {};
  31244. serializationObject.name = this.name;
  31245. serializationObject.id = this.id;
  31246. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  31247. serializationObject.bones = [];
  31248. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31249. for (var index = 0; index < this.bones.length; index++) {
  31250. var bone = this.bones[index];
  31251. var serializedBone = {
  31252. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  31253. name: bone.name,
  31254. matrix: bone.getLocalMatrix().toArray(),
  31255. rest: bone.getRestPose().toArray()
  31256. };
  31257. serializationObject.bones.push(serializedBone);
  31258. if (bone.length) {
  31259. serializedBone.length = bone.length;
  31260. }
  31261. if (bone.animations && bone.animations.length > 0) {
  31262. serializedBone.animation = bone.animations[0].serialize();
  31263. }
  31264. serializationObject.ranges = [];
  31265. for (var name in this._ranges) {
  31266. var range = {};
  31267. range.name = name;
  31268. range.from = this._ranges[name].from;
  31269. range.to = this._ranges[name].to;
  31270. serializationObject.ranges.push(range);
  31271. }
  31272. }
  31273. return serializationObject;
  31274. };
  31275. Skeleton.Parse = function (parsedSkeleton, scene) {
  31276. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  31277. if (parsedSkeleton.dimensionsAtRest) {
  31278. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  31279. }
  31280. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  31281. var index;
  31282. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  31283. var parsedBone = parsedSkeleton.bones[index];
  31284. var parentBone = null;
  31285. if (parsedBone.parentBoneIndex > -1) {
  31286. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  31287. }
  31288. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  31289. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  31290. if (parsedBone.length) {
  31291. bone.length = parsedBone.length;
  31292. }
  31293. if (parsedBone.animation) {
  31294. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  31295. }
  31296. }
  31297. // placed after bones, so createAnimationRange can cascade down
  31298. if (parsedSkeleton.ranges) {
  31299. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  31300. var data = parsedSkeleton.ranges[index];
  31301. skeleton.createAnimationRange(data.name, data.from, data.to);
  31302. }
  31303. }
  31304. return skeleton;
  31305. };
  31306. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  31307. if (forceUpdate === void 0) { forceUpdate = false; }
  31308. var renderId = this._scene.getRenderId();
  31309. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  31310. this.bones[0].computeAbsoluteTransforms();
  31311. this._lastAbsoluteTransformsUpdateId = renderId;
  31312. }
  31313. };
  31314. Skeleton.prototype.getPoseMatrix = function () {
  31315. var poseMatrix;
  31316. if (this._meshesWithPoseMatrix.length > 0) {
  31317. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  31318. }
  31319. return poseMatrix;
  31320. };
  31321. return Skeleton;
  31322. }());
  31323. BABYLON.Skeleton = Skeleton;
  31324. })(BABYLON || (BABYLON = {}));
  31325. //# sourceMappingURL=babylon.skeleton.js.map
  31326. var BABYLON;
  31327. (function (BABYLON) {
  31328. var PostProcess = (function () {
  31329. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  31330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  31331. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31332. this.name = name;
  31333. this.width = -1;
  31334. this.height = -1;
  31335. /*
  31336. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  31337. Can only be used on a single postprocess or on the last one of a chain.
  31338. */
  31339. this.enablePixelPerfectMode = false;
  31340. this._reusable = false;
  31341. this._textures = new BABYLON.SmartArray(2);
  31342. this._currentRenderTextureInd = 0;
  31343. this._scaleRatio = new BABYLON.Vector2(1, 1);
  31344. // Events
  31345. /**
  31346. * An event triggered when the postprocess is activated.
  31347. * @type {BABYLON.Observable}
  31348. */
  31349. this.onActivateObservable = new BABYLON.Observable();
  31350. /**
  31351. * An event triggered when the postprocess changes its size.
  31352. * @type {BABYLON.Observable}
  31353. */
  31354. this.onSizeChangedObservable = new BABYLON.Observable();
  31355. /**
  31356. * An event triggered when the postprocess applies its effect.
  31357. * @type {BABYLON.Observable}
  31358. */
  31359. this.onApplyObservable = new BABYLON.Observable();
  31360. /**
  31361. * An event triggered before rendering the postprocess
  31362. * @type {BABYLON.Observable}
  31363. */
  31364. this.onBeforeRenderObservable = new BABYLON.Observable();
  31365. /**
  31366. * An event triggered after rendering the postprocess
  31367. * @type {BABYLON.Observable}
  31368. */
  31369. this.onAfterRenderObservable = new BABYLON.Observable();
  31370. if (camera != null) {
  31371. this._camera = camera;
  31372. this._scene = camera.getScene();
  31373. camera.attachPostProcess(this);
  31374. this._engine = this._scene.getEngine();
  31375. }
  31376. else {
  31377. this._engine = engine;
  31378. }
  31379. this._options = options;
  31380. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  31381. this._reusable = reusable || false;
  31382. this._textureType = textureType;
  31383. this._samplers = samplers || [];
  31384. this._samplers.push("textureSampler");
  31385. this._fragmentUrl = fragmentUrl;
  31386. this._parameters = parameters || [];
  31387. this._parameters.push("scale");
  31388. this.updateEffect(defines);
  31389. }
  31390. Object.defineProperty(PostProcess.prototype, "onActivate", {
  31391. set: function (callback) {
  31392. if (this._onActivateObserver) {
  31393. this.onActivateObservable.remove(this._onActivateObserver);
  31394. }
  31395. this._onActivateObserver = this.onActivateObservable.add(callback);
  31396. },
  31397. enumerable: true,
  31398. configurable: true
  31399. });
  31400. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  31401. set: function (callback) {
  31402. if (this._onSizeChangedObserver) {
  31403. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  31404. }
  31405. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  31406. },
  31407. enumerable: true,
  31408. configurable: true
  31409. });
  31410. Object.defineProperty(PostProcess.prototype, "onApply", {
  31411. set: function (callback) {
  31412. if (this._onApplyObserver) {
  31413. this.onApplyObservable.remove(this._onApplyObserver);
  31414. }
  31415. this._onApplyObserver = this.onApplyObservable.add(callback);
  31416. },
  31417. enumerable: true,
  31418. configurable: true
  31419. });
  31420. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  31421. set: function (callback) {
  31422. if (this._onBeforeRenderObserver) {
  31423. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31424. }
  31425. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31426. },
  31427. enumerable: true,
  31428. configurable: true
  31429. });
  31430. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  31431. set: function (callback) {
  31432. if (this._onAfterRenderObserver) {
  31433. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31434. }
  31435. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31436. },
  31437. enumerable: true,
  31438. configurable: true
  31439. });
  31440. PostProcess.prototype.updateEffect = function (defines) {
  31441. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  31442. };
  31443. PostProcess.prototype.isReusable = function () {
  31444. return this._reusable;
  31445. };
  31446. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  31447. PostProcess.prototype.markTextureDirty = function () {
  31448. this.width = -1;
  31449. };
  31450. PostProcess.prototype.activate = function (camera, sourceTexture) {
  31451. camera = camera || this._camera;
  31452. var scene = camera.getScene();
  31453. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  31454. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  31455. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  31456. var desiredWidth = this._options.width || requiredWidth;
  31457. var desiredHeight = this._options.height || requiredHeight;
  31458. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31459. if (!this._options.width) {
  31460. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  31461. }
  31462. if (!this._options.height) {
  31463. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  31464. }
  31465. }
  31466. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  31467. if (this._textures.length > 0) {
  31468. for (var i = 0; i < this._textures.length; i++) {
  31469. this._engine._releaseTexture(this._textures.data[i]);
  31470. }
  31471. this._textures.reset();
  31472. }
  31473. this.width = desiredWidth;
  31474. this.height = desiredHeight;
  31475. var textureSize = { width: this.width, height: this.height };
  31476. var textureOptions = {
  31477. generateMipMaps: false,
  31478. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  31479. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  31480. samplingMode: this.renderTargetSamplingMode,
  31481. type: this._textureType
  31482. };
  31483. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31484. if (this._reusable) {
  31485. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31486. }
  31487. this.onSizeChangedObservable.notifyObservers(this);
  31488. }
  31489. if (this.enablePixelPerfectMode) {
  31490. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  31491. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  31492. }
  31493. else {
  31494. this._scaleRatio.copyFromFloats(1, 1);
  31495. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  31496. }
  31497. this.onActivateObservable.notifyObservers(camera);
  31498. // Clear
  31499. if (this.clearColor) {
  31500. this._engine.clear(this.clearColor, true, true, true);
  31501. }
  31502. else {
  31503. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  31504. }
  31505. if (this._reusable) {
  31506. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  31507. }
  31508. };
  31509. Object.defineProperty(PostProcess.prototype, "isSupported", {
  31510. get: function () {
  31511. return this._effect.isSupported;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. PostProcess.prototype.apply = function () {
  31517. // Check
  31518. if (!this._effect.isReady())
  31519. return null;
  31520. // States
  31521. this._engine.enableEffect(this._effect);
  31522. this._engine.setState(false);
  31523. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31524. this._engine.setDepthBuffer(false);
  31525. this._engine.setDepthWrite(false);
  31526. // Texture
  31527. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  31528. // Parameters
  31529. this._effect.setVector2("scale", this._scaleRatio);
  31530. this.onApplyObservable.notifyObservers(this._effect);
  31531. return this._effect;
  31532. };
  31533. PostProcess.prototype.dispose = function (camera) {
  31534. camera = camera || this._camera;
  31535. if (this._textures.length > 0) {
  31536. for (var i = 0; i < this._textures.length; i++) {
  31537. this._engine._releaseTexture(this._textures.data[i]);
  31538. }
  31539. this._textures.reset();
  31540. }
  31541. if (!camera) {
  31542. return;
  31543. }
  31544. camera.detachPostProcess(this);
  31545. var index = camera._postProcesses.indexOf(this);
  31546. if (index === 0 && camera._postProcesses.length > 0) {
  31547. this._camera._postProcesses[0].markTextureDirty();
  31548. }
  31549. this.onActivateObservable.clear();
  31550. this.onAfterRenderObservable.clear();
  31551. this.onApplyObservable.clear();
  31552. this.onBeforeRenderObservable.clear();
  31553. this.onSizeChangedObservable.clear();
  31554. };
  31555. return PostProcess;
  31556. }());
  31557. BABYLON.PostProcess = PostProcess;
  31558. })(BABYLON || (BABYLON = {}));
  31559. //# sourceMappingURL=babylon.postProcess.js.map
  31560. var BABYLON;
  31561. (function (BABYLON) {
  31562. var PostProcessManager = (function () {
  31563. function PostProcessManager(scene) {
  31564. this._vertexBuffers = {};
  31565. this._scene = scene;
  31566. }
  31567. PostProcessManager.prototype._prepareBuffers = function () {
  31568. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31569. return;
  31570. }
  31571. // VBO
  31572. var vertices = [];
  31573. vertices.push(1, 1);
  31574. vertices.push(-1, 1);
  31575. vertices.push(-1, -1);
  31576. vertices.push(1, -1);
  31577. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31578. // Indices
  31579. var indices = [];
  31580. indices.push(0);
  31581. indices.push(1);
  31582. indices.push(2);
  31583. indices.push(0);
  31584. indices.push(2);
  31585. indices.push(3);
  31586. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31587. };
  31588. // Methods
  31589. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  31590. var postProcesses = this._scene.activeCamera._postProcesses;
  31591. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31592. return false;
  31593. }
  31594. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  31595. return true;
  31596. };
  31597. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  31598. var engine = this._scene.getEngine();
  31599. for (var index = 0; index < postProcesses.length; index++) {
  31600. if (index < postProcesses.length - 1) {
  31601. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31602. }
  31603. else {
  31604. if (targetTexture) {
  31605. engine.bindFramebuffer(targetTexture);
  31606. }
  31607. else {
  31608. engine.restoreDefaultFramebuffer();
  31609. }
  31610. }
  31611. var pp = postProcesses[index];
  31612. var effect = pp.apply();
  31613. if (effect) {
  31614. pp.onBeforeRenderObservable.notifyObservers(effect);
  31615. // VBOs
  31616. this._prepareBuffers();
  31617. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31618. // Draw order
  31619. engine.draw(true, 0, 6);
  31620. pp.onAfterRenderObservable.notifyObservers(effect);
  31621. }
  31622. }
  31623. // Restore depth buffer
  31624. engine.setDepthBuffer(true);
  31625. engine.setDepthWrite(true);
  31626. };
  31627. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  31628. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  31629. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31630. return;
  31631. }
  31632. var engine = this._scene.getEngine();
  31633. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31634. if (index < len - 1) {
  31635. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31636. }
  31637. else {
  31638. if (targetTexture) {
  31639. engine.bindFramebuffer(targetTexture, faceIndex);
  31640. }
  31641. else {
  31642. engine.restoreDefaultFramebuffer();
  31643. }
  31644. }
  31645. if (doNotPresent) {
  31646. break;
  31647. }
  31648. var pp = postProcesses[index];
  31649. var effect = pp.apply();
  31650. if (effect) {
  31651. pp.onBeforeRenderObservable.notifyObservers(effect);
  31652. // VBOs
  31653. this._prepareBuffers();
  31654. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31655. // Draw order
  31656. engine.draw(true, 0, 6);
  31657. pp.onAfterRenderObservable.notifyObservers(effect);
  31658. }
  31659. }
  31660. // Restore depth buffer
  31661. engine.setDepthBuffer(true);
  31662. engine.setDepthWrite(true);
  31663. };
  31664. PostProcessManager.prototype.dispose = function () {
  31665. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31666. if (buffer) {
  31667. buffer.dispose();
  31668. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31669. }
  31670. if (this._indexBuffer) {
  31671. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31672. this._indexBuffer = null;
  31673. }
  31674. };
  31675. return PostProcessManager;
  31676. }());
  31677. BABYLON.PostProcessManager = PostProcessManager;
  31678. })(BABYLON || (BABYLON = {}));
  31679. //# sourceMappingURL=babylon.postProcessManager.js.map
  31680. var BABYLON;
  31681. (function (BABYLON) {
  31682. var PassPostProcess = (function (_super) {
  31683. __extends(PassPostProcess, _super);
  31684. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  31685. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  31686. }
  31687. return PassPostProcess;
  31688. }(BABYLON.PostProcess));
  31689. BABYLON.PassPostProcess = PassPostProcess;
  31690. })(BABYLON || (BABYLON = {}));
  31691. //# sourceMappingURL=babylon.passPostProcess.js.map
  31692. var BABYLON;
  31693. (function (BABYLON) {
  31694. /**
  31695. * This is a holder class for the physics joint created by the physics plugin.
  31696. * It holds a set of functions to control the underlying joint.
  31697. */
  31698. var PhysicsJoint = (function () {
  31699. function PhysicsJoint(type, jointData) {
  31700. this.type = type;
  31701. this.jointData = jointData;
  31702. jointData.nativeParams = jointData.nativeParams || {};
  31703. }
  31704. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  31705. get: function () {
  31706. return this._physicsJoint;
  31707. },
  31708. set: function (newJoint) {
  31709. if (this._physicsJoint) {
  31710. }
  31711. this._physicsJoint = newJoint;
  31712. },
  31713. enumerable: true,
  31714. configurable: true
  31715. });
  31716. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  31717. set: function (physicsPlugin) {
  31718. this._physicsPlugin = physicsPlugin;
  31719. },
  31720. enumerable: true,
  31721. configurable: true
  31722. });
  31723. /**
  31724. * Execute a function that is physics-plugin specific.
  31725. * @param {Function} func the function that will be executed.
  31726. * It accepts two parameters: the physics world and the physics joint.
  31727. */
  31728. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  31729. func(this._physicsPlugin.world, this._physicsJoint);
  31730. };
  31731. //TODO check if the native joints are the same
  31732. //Joint Types
  31733. PhysicsJoint.DistanceJoint = 0;
  31734. PhysicsJoint.HingeJoint = 1;
  31735. PhysicsJoint.BallAndSocketJoint = 2;
  31736. PhysicsJoint.WheelJoint = 3;
  31737. PhysicsJoint.SliderJoint = 4;
  31738. //OIMO
  31739. PhysicsJoint.PrismaticJoint = 5;
  31740. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  31741. PhysicsJoint.UniversalJoint = 6;
  31742. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  31743. //Cannon
  31744. //Similar to a Ball-Joint. Different in params
  31745. PhysicsJoint.PointToPointJoint = 8;
  31746. //Cannon only at the moment
  31747. PhysicsJoint.SpringJoint = 9;
  31748. PhysicsJoint.LockJoint = 10;
  31749. return PhysicsJoint;
  31750. }());
  31751. BABYLON.PhysicsJoint = PhysicsJoint;
  31752. /**
  31753. * A class representing a physics distance joint.
  31754. */
  31755. var DistanceJoint = (function (_super) {
  31756. __extends(DistanceJoint, _super);
  31757. function DistanceJoint(jointData) {
  31758. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  31759. }
  31760. /**
  31761. * Update the predefined distance.
  31762. */
  31763. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  31764. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  31765. };
  31766. return DistanceJoint;
  31767. }(PhysicsJoint));
  31768. BABYLON.DistanceJoint = DistanceJoint;
  31769. var MotorEnabledJoint = (function (_super) {
  31770. __extends(MotorEnabledJoint, _super);
  31771. function MotorEnabledJoint(type, jointData) {
  31772. _super.call(this, type, jointData);
  31773. }
  31774. /**
  31775. * Set the motor values.
  31776. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31777. * @param {number} force the force to apply
  31778. * @param {number} maxForce max force for this motor.
  31779. */
  31780. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  31781. this._physicsPlugin.setMotor(this, force, maxForce);
  31782. };
  31783. /**
  31784. * Set the motor's limits.
  31785. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31786. */
  31787. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31788. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31789. };
  31790. return MotorEnabledJoint;
  31791. }(PhysicsJoint));
  31792. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  31793. /**
  31794. * This class represents a single hinge physics joint
  31795. */
  31796. var HingeJoint = (function (_super) {
  31797. __extends(HingeJoint, _super);
  31798. function HingeJoint(jointData) {
  31799. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  31800. }
  31801. /**
  31802. * Set the motor values.
  31803. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31804. * @param {number} force the force to apply
  31805. * @param {number} maxForce max force for this motor.
  31806. */
  31807. HingeJoint.prototype.setMotor = function (force, maxForce) {
  31808. this._physicsPlugin.setMotor(this, force, maxForce);
  31809. };
  31810. /**
  31811. * Set the motor's limits.
  31812. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31813. */
  31814. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31815. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31816. };
  31817. return HingeJoint;
  31818. }(MotorEnabledJoint));
  31819. BABYLON.HingeJoint = HingeJoint;
  31820. /**
  31821. * This class represents a dual hinge physics joint (same as wheel joint)
  31822. */
  31823. var Hinge2Joint = (function (_super) {
  31824. __extends(Hinge2Joint, _super);
  31825. function Hinge2Joint(jointData) {
  31826. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  31827. }
  31828. /**
  31829. * Set the motor values.
  31830. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31831. * @param {number} force the force to apply
  31832. * @param {number} maxForce max force for this motor.
  31833. * @param {motorIndex} the motor's index, 0 or 1.
  31834. */
  31835. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  31836. if (motorIndex === void 0) { motorIndex = 0; }
  31837. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  31838. };
  31839. /**
  31840. * Set the motor limits.
  31841. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31842. * @param {number} upperLimit the upper limit
  31843. * @param {number} lowerLimit lower limit
  31844. * @param {motorIndex} the motor's index, 0 or 1.
  31845. */
  31846. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  31847. if (motorIndex === void 0) { motorIndex = 0; }
  31848. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  31849. };
  31850. return Hinge2Joint;
  31851. }(MotorEnabledJoint));
  31852. BABYLON.Hinge2Joint = Hinge2Joint;
  31853. })(BABYLON || (BABYLON = {}));
  31854. //# sourceMappingURL=babylon.physicsJoint.js.map
  31855. var BABYLON;
  31856. (function (BABYLON) {
  31857. var PhysicsImpostor = (function () {
  31858. function PhysicsImpostor(object, type, _options, _scene) {
  31859. var _this = this;
  31860. if (_options === void 0) { _options = { mass: 0 }; }
  31861. this.object = object;
  31862. this.type = type;
  31863. this._options = _options;
  31864. this._scene = _scene;
  31865. this._bodyUpdateRequired = false;
  31866. this._onBeforePhysicsStepCallbacks = new Array();
  31867. this._onAfterPhysicsStepCallbacks = new Array();
  31868. this._onPhysicsCollideCallbacks = [];
  31869. this._deltaPosition = BABYLON.Vector3.Zero();
  31870. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  31871. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  31872. /**
  31873. * this function is executed by the physics engine.
  31874. */
  31875. this.beforeStep = function () {
  31876. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  31877. //conjugate deltaRotation
  31878. if (_this._deltaRotationConjugated) {
  31879. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  31880. }
  31881. else {
  31882. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  31883. }
  31884. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  31885. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  31886. func(_this);
  31887. });
  31888. };
  31889. /**
  31890. * this function is executed by the physics engine.
  31891. */
  31892. this.afterStep = function () {
  31893. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  31894. func(_this);
  31895. });
  31896. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  31897. _this.object.position.addInPlace(_this._deltaPosition);
  31898. if (_this._deltaRotation) {
  31899. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  31900. }
  31901. };
  31902. //event and body object due to cannon's event-based architecture.
  31903. this.onCollide = function (e) {
  31904. if (!_this._onPhysicsCollideCallbacks.length)
  31905. return;
  31906. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  31907. if (otherImpostor) {
  31908. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  31909. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  31910. }).forEach(function (obj) {
  31911. obj.callback(_this, otherImpostor);
  31912. });
  31913. }
  31914. };
  31915. //sanity check!
  31916. if (!this.object) {
  31917. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  31918. return;
  31919. }
  31920. //legacy support for old syntax.
  31921. if (!this._scene && object.getScene) {
  31922. this._scene = object.getScene();
  31923. }
  31924. this._physicsEngine = this._scene.getPhysicsEngine();
  31925. if (!this._physicsEngine) {
  31926. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  31927. }
  31928. else {
  31929. //set the object's quaternion, if not set
  31930. if (!this.object.rotationQuaternion) {
  31931. if (this.object.rotation) {
  31932. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  31933. }
  31934. else {
  31935. this.object.rotationQuaternion = new BABYLON.Quaternion();
  31936. }
  31937. }
  31938. //default options params
  31939. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  31940. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  31941. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  31942. this._joints = [];
  31943. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  31944. if (!this.object.parent) {
  31945. this._init();
  31946. }
  31947. }
  31948. }
  31949. /**
  31950. * This function will completly initialize this impostor.
  31951. * It will create a new body - but only if this mesh has no parent.
  31952. * If it has, this impostor will not be used other than to define the impostor
  31953. * of the child mesh.
  31954. */
  31955. PhysicsImpostor.prototype._init = function () {
  31956. this._physicsEngine.removeImpostor(this);
  31957. this.physicsBody = null;
  31958. this._parent = this._parent || this._getPhysicsParent();
  31959. if (!this.parent) {
  31960. this._physicsEngine.addImpostor(this);
  31961. }
  31962. };
  31963. PhysicsImpostor.prototype._getPhysicsParent = function () {
  31964. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  31965. var parentMesh = this.object.parent;
  31966. return parentMesh.physicsImpostor;
  31967. }
  31968. return;
  31969. };
  31970. /**
  31971. * Should a new body be generated.
  31972. */
  31973. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  31974. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  31975. };
  31976. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  31977. this.forceUpdate();
  31978. };
  31979. /**
  31980. * Force a regeneration of this or the parent's impostor's body.
  31981. * Use under cautious - This will remove all joints already implemented.
  31982. */
  31983. PhysicsImpostor.prototype.forceUpdate = function () {
  31984. this._init();
  31985. if (this.parent) {
  31986. this.parent.forceUpdate();
  31987. }
  31988. };
  31989. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  31990. /*public get mesh(): AbstractMesh {
  31991. return this._mesh;
  31992. }*/
  31993. /**
  31994. * Gets the body that holds this impostor. Either its own, or its parent.
  31995. */
  31996. get: function () {
  31997. return this._parent ? this._parent.physicsBody : this._physicsBody;
  31998. },
  31999. /**
  32000. * Set the physics body. Used mainly by the physics engine/plugin
  32001. */
  32002. set: function (physicsBody) {
  32003. if (this._physicsBody) {
  32004. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  32005. }
  32006. this._physicsBody = physicsBody;
  32007. this.resetUpdateFlags();
  32008. },
  32009. enumerable: true,
  32010. configurable: true
  32011. });
  32012. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  32013. get: function () {
  32014. return this._parent;
  32015. },
  32016. set: function (value) {
  32017. this._parent = value;
  32018. },
  32019. enumerable: true,
  32020. configurable: true
  32021. });
  32022. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  32023. this._bodyUpdateRequired = false;
  32024. };
  32025. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  32026. if (this.object.getBoundingInfo) {
  32027. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  32028. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  32029. }
  32030. else {
  32031. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  32032. }
  32033. };
  32034. PhysicsImpostor.prototype.getObjectCenter = function () {
  32035. if (this.object.getBoundingInfo) {
  32036. return this.object.getBoundingInfo().boundingBox.center;
  32037. }
  32038. else {
  32039. return this.object.position;
  32040. }
  32041. };
  32042. /**
  32043. * Get a specific parametes from the options parameter.
  32044. */
  32045. PhysicsImpostor.prototype.getParam = function (paramName) {
  32046. return this._options[paramName];
  32047. };
  32048. /**
  32049. * Sets a specific parameter in the options given to the physics plugin
  32050. */
  32051. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32052. this._options[paramName] = value;
  32053. this._bodyUpdateRequired = true;
  32054. };
  32055. /**
  32056. * Specifically change the body's mass option. Won't recreate the physics body object
  32057. */
  32058. PhysicsImpostor.prototype.setMass = function (mass) {
  32059. if (this.getParam("mass") !== mass) {
  32060. this.setParam("mass", mass);
  32061. }
  32062. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32063. };
  32064. PhysicsImpostor.prototype.getLinearVelocity = function () {
  32065. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  32066. };
  32067. /**
  32068. * Set the body's linear velocity.
  32069. */
  32070. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  32071. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  32072. };
  32073. PhysicsImpostor.prototype.getAngularVelocity = function () {
  32074. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  32075. };
  32076. /**
  32077. * Set the body's linear velocity.
  32078. */
  32079. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  32080. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  32081. };
  32082. /**
  32083. * Execute a function with the physics plugin native code.
  32084. * Provide a function the will have two variables - the world object and the physics body object.
  32085. */
  32086. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  32087. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  32088. };
  32089. /**
  32090. * Register a function that will be executed before the physics world is stepping forward.
  32091. */
  32092. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  32093. this._onBeforePhysicsStepCallbacks.push(func);
  32094. };
  32095. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  32096. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  32097. if (index > -1) {
  32098. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  32099. }
  32100. else {
  32101. BABYLON.Tools.Warn("Function to remove was not found");
  32102. }
  32103. };
  32104. /**
  32105. * Register a function that will be executed after the physics step
  32106. */
  32107. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32108. this._onAfterPhysicsStepCallbacks.push(func);
  32109. };
  32110. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32111. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32112. if (index > -1) {
  32113. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32114. }
  32115. else {
  32116. BABYLON.Tools.Warn("Function to remove was not found");
  32117. }
  32118. };
  32119. /**
  32120. * register a function that will be executed when this impostor collides against a different body.
  32121. */
  32122. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32123. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32124. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32125. };
  32126. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32127. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32128. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32129. if (index > -1) {
  32130. this._onPhysicsCollideCallbacks.splice(index, 1);
  32131. }
  32132. else {
  32133. BABYLON.Tools.Warn("Function to remove was not found");
  32134. }
  32135. };
  32136. /**
  32137. * Apply a force
  32138. */
  32139. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32140. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32141. };
  32142. /**
  32143. * Apply an impulse
  32144. */
  32145. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32146. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32147. };
  32148. /**
  32149. * A help function to create a joint.
  32150. */
  32151. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32152. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32153. this.addJoint(otherImpostor, joint);
  32154. };
  32155. /**
  32156. * Add a joint to this impostor with a different impostor.
  32157. */
  32158. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32159. this._joints.push({
  32160. otherImpostor: otherImpostor,
  32161. joint: joint
  32162. });
  32163. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32164. };
  32165. /**
  32166. * Will keep this body still, in a sleep mode.
  32167. */
  32168. PhysicsImpostor.prototype.sleep = function () {
  32169. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32170. };
  32171. /**
  32172. * Wake the body up.
  32173. */
  32174. PhysicsImpostor.prototype.wakeUp = function () {
  32175. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32176. };
  32177. PhysicsImpostor.prototype.clone = function (newObject) {
  32178. if (!newObject)
  32179. return null;
  32180. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32181. };
  32182. PhysicsImpostor.prototype.dispose = function () {
  32183. var _this = this;
  32184. //no dispose if no physics engine is available.
  32185. if (!this._physicsEngine) {
  32186. return;
  32187. }
  32188. this._joints.forEach(function (j) {
  32189. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32190. });
  32191. //dispose the physics body
  32192. this._physicsEngine.removeImpostor(this);
  32193. if (this.parent) {
  32194. this.parent.forceUpdate();
  32195. }
  32196. else {
  32197. }
  32198. };
  32199. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32200. this._deltaPosition.copyFrom(position);
  32201. };
  32202. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32203. if (!this._deltaRotation) {
  32204. this._deltaRotation = new BABYLON.Quaternion();
  32205. }
  32206. this._deltaRotation.copyFrom(rotation);
  32207. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32208. };
  32209. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32210. //Impostor types
  32211. PhysicsImpostor.NoImpostor = 0;
  32212. PhysicsImpostor.SphereImpostor = 1;
  32213. PhysicsImpostor.BoxImpostor = 2;
  32214. PhysicsImpostor.PlaneImpostor = 3;
  32215. PhysicsImpostor.MeshImpostor = 4;
  32216. PhysicsImpostor.CylinderImpostor = 7;
  32217. PhysicsImpostor.ParticleImpostor = 8;
  32218. PhysicsImpostor.HeightmapImpostor = 9;
  32219. return PhysicsImpostor;
  32220. }());
  32221. BABYLON.PhysicsImpostor = PhysicsImpostor;
  32222. })(BABYLON || (BABYLON = {}));
  32223. //# sourceMappingURL=babylon.physicsImpostor.js.map
  32224. var BABYLON;
  32225. (function (BABYLON) {
  32226. var PhysicsEngine = (function () {
  32227. function PhysicsEngine(gravity, _physicsPlugin) {
  32228. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  32229. this._physicsPlugin = _physicsPlugin;
  32230. //new methods and parameters
  32231. this._impostors = [];
  32232. this._joints = [];
  32233. if (!this._physicsPlugin.isSupported()) {
  32234. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  32235. + "Please make sure it is included.");
  32236. }
  32237. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  32238. this.setGravity(gravity);
  32239. this.setTimeStep();
  32240. }
  32241. PhysicsEngine.prototype.setGravity = function (gravity) {
  32242. this.gravity = gravity;
  32243. this._physicsPlugin.setGravity(this.gravity);
  32244. };
  32245. /**
  32246. * Set the time step of the physics engine.
  32247. * default is 1/60.
  32248. * To slow it down, enter 1/600 for example.
  32249. * To speed it up, 1/30
  32250. * @param {number} newTimeStep the new timestep to apply to this world.
  32251. */
  32252. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  32253. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  32254. this._physicsPlugin.setTimeStep(newTimeStep);
  32255. };
  32256. PhysicsEngine.prototype.dispose = function () {
  32257. this._impostors.forEach(function (impostor) {
  32258. impostor.dispose();
  32259. });
  32260. this._physicsPlugin.dispose();
  32261. };
  32262. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  32263. return this._physicsPlugin.name;
  32264. };
  32265. /**
  32266. * Adding a new impostor for the impostor tracking.
  32267. * This will be done by the impostor itself.
  32268. * @param {PhysicsImpostor} impostor the impostor to add
  32269. */
  32270. PhysicsEngine.prototype.addImpostor = function (impostor) {
  32271. impostor.uniqueId = this._impostors.push(impostor);
  32272. //if no parent, generate the body
  32273. if (!impostor.parent) {
  32274. this._physicsPlugin.generatePhysicsBody(impostor);
  32275. }
  32276. };
  32277. /**
  32278. * Remove an impostor from the engine.
  32279. * This impostor and its mesh will not longer be updated by the physics engine.
  32280. * @param {PhysicsImpostor} impostor the impostor to remove
  32281. */
  32282. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  32283. var index = this._impostors.indexOf(impostor);
  32284. if (index > -1) {
  32285. var removed = this._impostors.splice(index, 1);
  32286. //Is it needed?
  32287. if (removed.length) {
  32288. //this will also remove it from the world.
  32289. removed[0].physicsBody = null;
  32290. }
  32291. }
  32292. };
  32293. /**
  32294. * Add a joint to the physics engine
  32295. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  32296. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  32297. * @param {PhysicsJoint} the joint that will connect both impostors.
  32298. */
  32299. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  32300. var impostorJoint = {
  32301. mainImpostor: mainImpostor,
  32302. connectedImpostor: connectedImpostor,
  32303. joint: joint
  32304. };
  32305. joint.physicsPlugin = this._physicsPlugin;
  32306. this._joints.push(impostorJoint);
  32307. this._physicsPlugin.generateJoint(impostorJoint);
  32308. };
  32309. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  32310. var matchingJoints = this._joints.filter(function (impostorJoint) {
  32311. return (impostorJoint.connectedImpostor === connectedImpostor
  32312. && impostorJoint.joint === joint
  32313. && impostorJoint.mainImpostor === mainImpostor);
  32314. });
  32315. if (matchingJoints.length) {
  32316. this._physicsPlugin.removeJoint(matchingJoints[0]);
  32317. }
  32318. };
  32319. /**
  32320. * Called by the scene. no need to call it.
  32321. */
  32322. PhysicsEngine.prototype._step = function (delta) {
  32323. var _this = this;
  32324. //check if any mesh has no body / requires an update
  32325. this._impostors.forEach(function (impostor) {
  32326. if (impostor.isBodyInitRequired()) {
  32327. _this._physicsPlugin.generatePhysicsBody(impostor);
  32328. }
  32329. });
  32330. if (delta > 0.1) {
  32331. delta = 0.1;
  32332. }
  32333. else if (delta <= 0) {
  32334. delta = 1.0 / 60.0;
  32335. }
  32336. this._physicsPlugin.executeStep(delta, this._impostors);
  32337. };
  32338. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  32339. return this._physicsPlugin;
  32340. };
  32341. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  32342. for (var i = 0; i < this._impostors.length; ++i) {
  32343. if (this._impostors[i].object === object) {
  32344. return this._impostors[i];
  32345. }
  32346. }
  32347. };
  32348. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  32349. for (var i = 0; i < this._impostors.length; ++i) {
  32350. if (this._impostors[i].physicsBody === body) {
  32351. return this._impostors[i];
  32352. }
  32353. }
  32354. };
  32355. // Statics, Legacy support.
  32356. /**
  32357. * @Deprecated
  32358. *
  32359. */
  32360. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  32361. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  32362. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  32363. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  32364. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  32365. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  32366. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  32367. PhysicsEngine.CapsuleImpostor = -1;
  32368. PhysicsEngine.ConeImpostor = -1;
  32369. PhysicsEngine.ConvexHullImpostor = -1;
  32370. PhysicsEngine.Epsilon = 0.001;
  32371. return PhysicsEngine;
  32372. }());
  32373. BABYLON.PhysicsEngine = PhysicsEngine;
  32374. })(BABYLON || (BABYLON = {}));
  32375. //# sourceMappingURL=babylon.physicsEngine.js.map
  32376. var BABYLON;
  32377. (function (BABYLON) {
  32378. var VertexData = (function () {
  32379. function VertexData() {
  32380. }
  32381. VertexData.prototype.set = function (data, kind) {
  32382. switch (kind) {
  32383. case BABYLON.VertexBuffer.PositionKind:
  32384. this.positions = data;
  32385. break;
  32386. case BABYLON.VertexBuffer.NormalKind:
  32387. this.normals = data;
  32388. break;
  32389. case BABYLON.VertexBuffer.UVKind:
  32390. this.uvs = data;
  32391. break;
  32392. case BABYLON.VertexBuffer.UV2Kind:
  32393. this.uvs2 = data;
  32394. break;
  32395. case BABYLON.VertexBuffer.UV3Kind:
  32396. this.uvs3 = data;
  32397. break;
  32398. case BABYLON.VertexBuffer.UV4Kind:
  32399. this.uvs4 = data;
  32400. break;
  32401. case BABYLON.VertexBuffer.UV5Kind:
  32402. this.uvs5 = data;
  32403. break;
  32404. case BABYLON.VertexBuffer.UV6Kind:
  32405. this.uvs6 = data;
  32406. break;
  32407. case BABYLON.VertexBuffer.ColorKind:
  32408. this.colors = data;
  32409. break;
  32410. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32411. this.matricesIndices = data;
  32412. break;
  32413. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32414. this.matricesWeights = data;
  32415. break;
  32416. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32417. this.matricesIndicesExtra = data;
  32418. break;
  32419. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32420. this.matricesWeightsExtra = data;
  32421. break;
  32422. }
  32423. };
  32424. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32425. this._applyTo(mesh, updatable);
  32426. };
  32427. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32428. this._applyTo(geometry, updatable);
  32429. };
  32430. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32431. this._update(mesh);
  32432. };
  32433. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32434. this._update(geometry);
  32435. };
  32436. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32437. if (this.positions) {
  32438. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32439. }
  32440. if (this.normals) {
  32441. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32442. }
  32443. if (this.uvs) {
  32444. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32445. }
  32446. if (this.uvs2) {
  32447. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32448. }
  32449. if (this.uvs3) {
  32450. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32451. }
  32452. if (this.uvs4) {
  32453. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32454. }
  32455. if (this.uvs5) {
  32456. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32457. }
  32458. if (this.uvs6) {
  32459. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32460. }
  32461. if (this.colors) {
  32462. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32463. }
  32464. if (this.matricesIndices) {
  32465. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32466. }
  32467. if (this.matricesWeights) {
  32468. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32469. }
  32470. if (this.matricesIndicesExtra) {
  32471. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32472. }
  32473. if (this.matricesWeightsExtra) {
  32474. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32475. }
  32476. if (this.indices) {
  32477. meshOrGeometry.setIndices(this.indices);
  32478. }
  32479. };
  32480. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32481. if (this.positions) {
  32482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32483. }
  32484. if (this.normals) {
  32485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32486. }
  32487. if (this.uvs) {
  32488. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32489. }
  32490. if (this.uvs2) {
  32491. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32492. }
  32493. if (this.uvs3) {
  32494. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32495. }
  32496. if (this.uvs4) {
  32497. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32498. }
  32499. if (this.uvs5) {
  32500. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32501. }
  32502. if (this.uvs6) {
  32503. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32504. }
  32505. if (this.colors) {
  32506. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32507. }
  32508. if (this.matricesIndices) {
  32509. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32510. }
  32511. if (this.matricesWeights) {
  32512. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32513. }
  32514. if (this.matricesIndicesExtra) {
  32515. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32516. }
  32517. if (this.matricesWeightsExtra) {
  32518. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32519. }
  32520. if (this.indices) {
  32521. meshOrGeometry.setIndices(this.indices);
  32522. }
  32523. };
  32524. VertexData.prototype.transform = function (matrix) {
  32525. var transformed = BABYLON.Vector3.Zero();
  32526. var index;
  32527. if (this.positions) {
  32528. var position = BABYLON.Vector3.Zero();
  32529. for (index = 0; index < this.positions.length; index += 3) {
  32530. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32531. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32532. this.positions[index] = transformed.x;
  32533. this.positions[index + 1] = transformed.y;
  32534. this.positions[index + 2] = transformed.z;
  32535. }
  32536. }
  32537. if (this.normals) {
  32538. var normal = BABYLON.Vector3.Zero();
  32539. for (index = 0; index < this.normals.length; index += 3) {
  32540. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32541. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32542. this.normals[index] = transformed.x;
  32543. this.normals[index + 1] = transformed.y;
  32544. this.normals[index + 2] = transformed.z;
  32545. }
  32546. }
  32547. };
  32548. VertexData.prototype.merge = function (other) {
  32549. if (other.indices) {
  32550. if (!this.indices) {
  32551. this.indices = [];
  32552. }
  32553. var offset = this.positions ? this.positions.length / 3 : 0;
  32554. for (var index = 0; index < other.indices.length; index++) {
  32555. //TODO check type - if Int32Array!
  32556. this.indices.push(other.indices[index] + offset);
  32557. }
  32558. }
  32559. this.positions = this._mergeElement(this.positions, other.positions);
  32560. this.normals = this._mergeElement(this.normals, other.normals);
  32561. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32562. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32563. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32564. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32565. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32566. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32567. this.colors = this._mergeElement(this.colors, other.colors);
  32568. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32569. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32570. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32571. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32572. };
  32573. VertexData.prototype._mergeElement = function (source, other) {
  32574. if (!other)
  32575. return source;
  32576. if (!source)
  32577. return other;
  32578. var len = other.length + source.length;
  32579. var isSrcTypedArray = source instanceof Float32Array;
  32580. var isOthTypedArray = other instanceof Float32Array;
  32581. // use non-loop method when the source is Float32Array
  32582. if (isSrcTypedArray) {
  32583. var ret32 = new Float32Array(len);
  32584. ret32.set(source);
  32585. ret32.set(other, source.length);
  32586. return ret32;
  32587. }
  32588. else if (!isOthTypedArray) {
  32589. return source.concat(other);
  32590. }
  32591. else {
  32592. var ret = source.slice(0); // copy source to a separate array
  32593. for (var i = 0, len = other.length; i < len; i++) {
  32594. ret.push(other[i]);
  32595. }
  32596. return ret;
  32597. }
  32598. };
  32599. VertexData.prototype.serialize = function () {
  32600. var serializationObject = this.serialize();
  32601. if (this.positions) {
  32602. serializationObject.positions = this.positions;
  32603. }
  32604. if (this.normals) {
  32605. serializationObject.normals = this.normals;
  32606. }
  32607. if (this.uvs) {
  32608. serializationObject.uvs = this.uvs;
  32609. }
  32610. if (this.uvs2) {
  32611. serializationObject.uvs2 = this.uvs2;
  32612. }
  32613. if (this.uvs3) {
  32614. serializationObject.uvs3 = this.uvs3;
  32615. }
  32616. if (this.uvs4) {
  32617. serializationObject.uvs4 = this.uvs4;
  32618. }
  32619. if (this.uvs5) {
  32620. serializationObject.uvs5 = this.uvs5;
  32621. }
  32622. if (this.uvs6) {
  32623. serializationObject.uvs6 = this.uvs6;
  32624. }
  32625. if (this.colors) {
  32626. serializationObject.colors = this.colors;
  32627. }
  32628. if (this.matricesIndices) {
  32629. serializationObject.matricesIndices = this.matricesIndices;
  32630. serializationObject.matricesIndices._isExpanded = true;
  32631. }
  32632. if (this.matricesWeights) {
  32633. serializationObject.matricesWeights = this.matricesWeights;
  32634. }
  32635. if (this.matricesIndicesExtra) {
  32636. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32637. serializationObject.matricesIndicesExtra._isExpanded = true;
  32638. }
  32639. if (this.matricesWeightsExtra) {
  32640. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32641. }
  32642. serializationObject.indices = this.indices;
  32643. return serializationObject;
  32644. };
  32645. // Statics
  32646. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  32647. return VertexData._ExtractFrom(mesh, copyWhenShared);
  32648. };
  32649. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  32650. return VertexData._ExtractFrom(geometry, copyWhenShared);
  32651. };
  32652. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  32653. var result = new VertexData();
  32654. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32655. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  32656. }
  32657. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32658. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  32659. }
  32660. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32661. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  32662. }
  32663. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32664. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  32665. }
  32666. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32667. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  32668. }
  32669. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32670. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  32671. }
  32672. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32673. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  32674. }
  32675. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32676. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  32677. }
  32678. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32679. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  32680. }
  32681. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32682. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  32683. }
  32684. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32685. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  32686. }
  32687. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32688. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  32689. }
  32690. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32691. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  32692. }
  32693. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32694. return result;
  32695. };
  32696. VertexData.CreateRibbon = function (options) {
  32697. var pathArray = options.pathArray;
  32698. var closeArray = options.closeArray || false;
  32699. var closePath = options.closePath || false;
  32700. var invertUV = options.invertUV || false;
  32701. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32702. var offset = options.offset || defaultOffset;
  32703. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32704. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32705. var positions = [];
  32706. var indices = [];
  32707. var normals = [];
  32708. var uvs = [];
  32709. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32710. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32711. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32712. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32713. var minlg; // minimal length among all paths from pathArray
  32714. var lg = []; // array of path lengths : nb of vertex per path
  32715. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32716. var p; // path iterator
  32717. var i; // point iterator
  32718. var j; // point iterator
  32719. // if single path in pathArray
  32720. if (pathArray.length < 2) {
  32721. var ar1 = [];
  32722. var ar2 = [];
  32723. for (i = 0; i < pathArray[0].length - offset; i++) {
  32724. ar1.push(pathArray[0][i]);
  32725. ar2.push(pathArray[0][i + offset]);
  32726. }
  32727. pathArray = [ar1, ar2];
  32728. }
  32729. // positions and horizontal distances (u)
  32730. var idc = 0;
  32731. var closePathCorr = (closePath) ? 1 : 0;
  32732. var path;
  32733. var l;
  32734. minlg = pathArray[0].length;
  32735. var vectlg;
  32736. var dist;
  32737. for (p = 0; p < pathArray.length; p++) {
  32738. uTotalDistance[p] = 0;
  32739. us[p] = [0];
  32740. path = pathArray[p];
  32741. l = path.length;
  32742. minlg = (minlg < l) ? minlg : l;
  32743. j = 0;
  32744. while (j < l) {
  32745. positions.push(path[j].x, path[j].y, path[j].z);
  32746. if (j > 0) {
  32747. vectlg = path[j].subtract(path[j - 1]).length();
  32748. dist = vectlg + uTotalDistance[p];
  32749. us[p].push(dist);
  32750. uTotalDistance[p] = dist;
  32751. }
  32752. j++;
  32753. }
  32754. if (closePath) {
  32755. j--;
  32756. positions.push(path[0].x, path[0].y, path[0].z);
  32757. vectlg = path[j].subtract(path[0]).length();
  32758. dist = vectlg + uTotalDistance[p];
  32759. us[p].push(dist);
  32760. uTotalDistance[p] = dist;
  32761. }
  32762. lg[p] = l + closePathCorr;
  32763. idx[p] = idc;
  32764. idc += (l + closePathCorr);
  32765. }
  32766. // vertical distances (v)
  32767. var path1;
  32768. var path2;
  32769. var vertex1;
  32770. var vertex2;
  32771. for (i = 0; i < minlg + closePathCorr; i++) {
  32772. vTotalDistance[i] = 0;
  32773. vs[i] = [0];
  32774. for (p = 0; p < pathArray.length - 1; p++) {
  32775. path1 = pathArray[p];
  32776. path2 = pathArray[p + 1];
  32777. if (i === minlg) {
  32778. vertex1 = path1[0];
  32779. vertex2 = path2[0];
  32780. }
  32781. else {
  32782. vertex1 = path1[i];
  32783. vertex2 = path2[i];
  32784. }
  32785. vectlg = vertex2.subtract(vertex1).length();
  32786. dist = vectlg + vTotalDistance[i];
  32787. vs[i].push(dist);
  32788. vTotalDistance[i] = dist;
  32789. }
  32790. if (closeArray) {
  32791. path1 = pathArray[p];
  32792. path2 = pathArray[0];
  32793. if (i === minlg) {
  32794. vertex2 = path2[0];
  32795. }
  32796. vectlg = vertex2.subtract(vertex1).length();
  32797. dist = vectlg + vTotalDistance[i];
  32798. vTotalDistance[i] = dist;
  32799. }
  32800. }
  32801. // uvs
  32802. var u;
  32803. var v;
  32804. for (p = 0; p < pathArray.length; p++) {
  32805. for (i = 0; i < minlg + closePathCorr; i++) {
  32806. u = us[p][i] / uTotalDistance[p];
  32807. v = vs[i][p] / vTotalDistance[i];
  32808. if (invertUV) {
  32809. uvs.push(v, u);
  32810. }
  32811. else {
  32812. uvs.push(u, v);
  32813. }
  32814. }
  32815. }
  32816. // indices
  32817. p = 0; // path index
  32818. var pi = 0; // positions array index
  32819. var l1 = lg[p] - 1; // path1 length
  32820. var l2 = lg[p + 1] - 1; // path2 length
  32821. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32822. var shft = idx[1] - idx[0]; // shift
  32823. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32824. while (pi <= min && p < path1nb) {
  32825. // 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
  32826. indices.push(pi, pi + shft, pi + 1);
  32827. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32828. pi += 1;
  32829. if (pi === min) {
  32830. p++;
  32831. if (p === lg.length - 1) {
  32832. shft = idx[0] - idx[p];
  32833. l1 = lg[p] - 1;
  32834. l2 = lg[0] - 1;
  32835. }
  32836. else {
  32837. shft = idx[p + 1] - idx[p];
  32838. l1 = lg[p] - 1;
  32839. l2 = lg[p + 1] - 1;
  32840. }
  32841. pi = idx[p];
  32842. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32843. }
  32844. }
  32845. // normals
  32846. VertexData.ComputeNormals(positions, indices, normals);
  32847. if (closePath) {
  32848. var indexFirst = 0;
  32849. var indexLast = 0;
  32850. for (p = 0; p < pathArray.length; p++) {
  32851. indexFirst = idx[p] * 3;
  32852. if (p + 1 < pathArray.length) {
  32853. indexLast = (idx[p + 1] - 1) * 3;
  32854. }
  32855. else {
  32856. indexLast = normals.length - 3;
  32857. }
  32858. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32859. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32860. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32861. normals[indexLast] = normals[indexFirst];
  32862. normals[indexLast + 1] = normals[indexFirst + 1];
  32863. normals[indexLast + 2] = normals[indexFirst + 2];
  32864. }
  32865. }
  32866. // sides
  32867. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32868. // Result
  32869. var vertexData = new VertexData();
  32870. vertexData.indices = indices;
  32871. vertexData.positions = positions;
  32872. vertexData.normals = normals;
  32873. vertexData.uvs = uvs;
  32874. if (closePath) {
  32875. vertexData._idx = idx;
  32876. }
  32877. return vertexData;
  32878. };
  32879. VertexData.CreateBox = function (options) {
  32880. var normalsSource = [
  32881. new BABYLON.Vector3(0, 0, 1),
  32882. new BABYLON.Vector3(0, 0, -1),
  32883. new BABYLON.Vector3(1, 0, 0),
  32884. new BABYLON.Vector3(-1, 0, 0),
  32885. new BABYLON.Vector3(0, 1, 0),
  32886. new BABYLON.Vector3(0, -1, 0)
  32887. ];
  32888. var indices = [];
  32889. var positions = [];
  32890. var normals = [];
  32891. var uvs = [];
  32892. var width = options.width || options.size || 1;
  32893. var height = options.height || options.size || 1;
  32894. var depth = options.depth || options.size || 1;
  32895. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32896. var faceUV = options.faceUV || new Array(6);
  32897. var faceColors = options.faceColors;
  32898. var colors = [];
  32899. // default face colors and UV if undefined
  32900. for (var f = 0; f < 6; f++) {
  32901. if (faceUV[f] === undefined) {
  32902. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32903. }
  32904. if (faceColors && faceColors[f] === undefined) {
  32905. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32906. }
  32907. }
  32908. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32909. // Create each face in turn.
  32910. for (var index = 0; index < normalsSource.length; index++) {
  32911. var normal = normalsSource[index];
  32912. // Get two vectors perpendicular to the face normal and to each other.
  32913. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32914. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32915. // Six indices (two triangles) per face.
  32916. var verticesLength = positions.length / 3;
  32917. indices.push(verticesLength);
  32918. indices.push(verticesLength + 1);
  32919. indices.push(verticesLength + 2);
  32920. indices.push(verticesLength);
  32921. indices.push(verticesLength + 2);
  32922. indices.push(verticesLength + 3);
  32923. // Four vertices per face.
  32924. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32925. positions.push(vertex.x, vertex.y, vertex.z);
  32926. normals.push(normal.x, normal.y, normal.z);
  32927. uvs.push(faceUV[index].z, faceUV[index].w);
  32928. if (faceColors) {
  32929. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32930. }
  32931. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32932. positions.push(vertex.x, vertex.y, vertex.z);
  32933. normals.push(normal.x, normal.y, normal.z);
  32934. uvs.push(faceUV[index].x, faceUV[index].w);
  32935. if (faceColors) {
  32936. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32937. }
  32938. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32939. positions.push(vertex.x, vertex.y, vertex.z);
  32940. normals.push(normal.x, normal.y, normal.z);
  32941. uvs.push(faceUV[index].x, faceUV[index].y);
  32942. if (faceColors) {
  32943. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32944. }
  32945. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32946. positions.push(vertex.x, vertex.y, vertex.z);
  32947. normals.push(normal.x, normal.y, normal.z);
  32948. uvs.push(faceUV[index].z, faceUV[index].y);
  32949. if (faceColors) {
  32950. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32951. }
  32952. }
  32953. // sides
  32954. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32955. // Result
  32956. var vertexData = new VertexData();
  32957. vertexData.indices = indices;
  32958. vertexData.positions = positions;
  32959. vertexData.normals = normals;
  32960. vertexData.uvs = uvs;
  32961. if (faceColors) {
  32962. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32963. vertexData.colors = totalColors;
  32964. }
  32965. return vertexData;
  32966. };
  32967. VertexData.CreateSphere = function (options) {
  32968. var segments = options.segments || 32;
  32969. var diameterX = options.diameterX || options.diameter || 1;
  32970. var diameterY = options.diameterY || options.diameter || 1;
  32971. var diameterZ = options.diameterZ || options.diameter || 1;
  32972. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32973. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32974. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32975. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32976. var totalZRotationSteps = 2 + segments;
  32977. var totalYRotationSteps = 2 * totalZRotationSteps;
  32978. var indices = [];
  32979. var positions = [];
  32980. var normals = [];
  32981. var uvs = [];
  32982. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32983. var normalizedZ = zRotationStep / totalZRotationSteps;
  32984. var angleZ = normalizedZ * Math.PI * slice;
  32985. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32986. var normalizedY = yRotationStep / totalYRotationSteps;
  32987. var angleY = normalizedY * Math.PI * 2 * arc;
  32988. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32989. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32990. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32991. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32992. var vertex = complete.multiply(radius);
  32993. var normal = complete.divide(radius).normalize();
  32994. positions.push(vertex.x, vertex.y, vertex.z);
  32995. normals.push(normal.x, normal.y, normal.z);
  32996. uvs.push(normalizedY, normalizedZ);
  32997. }
  32998. if (zRotationStep > 0) {
  32999. var verticesCount = positions.length / 3;
  33000. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33001. indices.push((firstIndex));
  33002. indices.push((firstIndex + 1));
  33003. indices.push(firstIndex + totalYRotationSteps + 1);
  33004. indices.push((firstIndex + totalYRotationSteps + 1));
  33005. indices.push((firstIndex + 1));
  33006. indices.push((firstIndex + totalYRotationSteps + 2));
  33007. }
  33008. }
  33009. }
  33010. // Sides
  33011. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33012. // Result
  33013. var vertexData = new VertexData();
  33014. vertexData.indices = indices;
  33015. vertexData.positions = positions;
  33016. vertexData.normals = normals;
  33017. vertexData.uvs = uvs;
  33018. return vertexData;
  33019. };
  33020. // Cylinder and cone
  33021. VertexData.CreateCylinder = function (options) {
  33022. var height = options.height || 2;
  33023. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33024. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33025. var tessellation = options.tessellation || 24;
  33026. var subdivisions = options.subdivisions || 1;
  33027. var hasRings = options.hasRings;
  33028. var enclose = options.enclose;
  33029. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33030. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33031. var faceUV = options.faceUV || new Array(3);
  33032. var faceColors = options.faceColors;
  33033. // default face colors and UV if undefined
  33034. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33035. var ringNb = (hasRings) ? subdivisions : 1;
  33036. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33037. var f;
  33038. for (f = 0; f < surfaceNb; f++) {
  33039. if (faceColors && faceColors[f] === undefined) {
  33040. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33041. }
  33042. }
  33043. for (f = 0; f < surfaceNb; f++) {
  33044. if (faceUV && faceUV[f] === undefined) {
  33045. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33046. }
  33047. }
  33048. var indices = [];
  33049. var positions = [];
  33050. var normals = [];
  33051. var uvs = [];
  33052. var colors = [];
  33053. var angle_step = Math.PI * 2 * arc / tessellation;
  33054. var angle;
  33055. var h;
  33056. var radius;
  33057. var tan = (diameterBottom - diameterTop) / 2 / height;
  33058. var ringVertex = BABYLON.Vector3.Zero();
  33059. var ringNormal = BABYLON.Vector3.Zero();
  33060. var ringFirstVertex = BABYLON.Vector3.Zero();
  33061. var ringFirstNormal = BABYLON.Vector3.Zero();
  33062. var quadNormal = BABYLON.Vector3.Zero();
  33063. var Y = BABYLON.Axis.Y;
  33064. // positions, normals, uvs
  33065. var i;
  33066. var j;
  33067. var r;
  33068. var ringIdx = 1;
  33069. var s = 1; // surface index
  33070. var cs = 0;
  33071. var v = 0;
  33072. for (i = 0; i <= subdivisions; i++) {
  33073. h = i / subdivisions;
  33074. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33075. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33076. for (r = 0; r < ringIdx; r++) {
  33077. if (hasRings) {
  33078. s += r;
  33079. }
  33080. if (enclose) {
  33081. s += 2 * r;
  33082. }
  33083. for (j = 0; j <= tessellation; j++) {
  33084. angle = j * angle_step;
  33085. // position
  33086. ringVertex.x = Math.cos(-angle) * radius;
  33087. ringVertex.y = -height / 2 + h * height;
  33088. ringVertex.z = Math.sin(-angle) * radius;
  33089. // normal
  33090. if (diameterTop === 0 && i === subdivisions) {
  33091. // if no top cap, reuse former normals
  33092. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33093. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33094. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33095. }
  33096. else {
  33097. ringNormal.x = ringVertex.x;
  33098. ringNormal.z = ringVertex.z;
  33099. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33100. ringNormal.normalize();
  33101. }
  33102. // keep first ring vertex values for enclose
  33103. if (j === 0) {
  33104. ringFirstVertex.copyFrom(ringVertex);
  33105. ringFirstNormal.copyFrom(ringNormal);
  33106. }
  33107. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33108. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33109. if (hasRings) {
  33110. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33111. }
  33112. else {
  33113. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33114. }
  33115. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33116. if (faceColors) {
  33117. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33118. }
  33119. }
  33120. // if enclose, add four vertices and their dedicated normals
  33121. if (arc !== 1 && enclose) {
  33122. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33123. positions.push(0, ringVertex.y, 0);
  33124. positions.push(0, ringVertex.y, 0);
  33125. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33126. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33127. quadNormal.normalize();
  33128. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33129. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33130. quadNormal.normalize();
  33131. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33132. if (hasRings) {
  33133. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33134. }
  33135. else {
  33136. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33137. }
  33138. uvs.push(faceUV[s + 1].x, v);
  33139. uvs.push(faceUV[s + 1].z, v);
  33140. if (hasRings) {
  33141. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33142. }
  33143. else {
  33144. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33145. }
  33146. uvs.push(faceUV[s + 2].x, v);
  33147. uvs.push(faceUV[s + 2].z, v);
  33148. if (faceColors) {
  33149. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33150. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33151. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33152. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33153. }
  33154. }
  33155. if (cs !== s) {
  33156. cs = s;
  33157. }
  33158. }
  33159. }
  33160. // indices
  33161. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33162. var s;
  33163. i = 0;
  33164. for (s = 0; s < subdivisions; s++) {
  33165. for (j = 0; j < tessellation; j++) {
  33166. var i0 = i * (e + 1) + j;
  33167. var i1 = (i + 1) * (e + 1) + j;
  33168. var i2 = i * (e + 1) + (j + 1);
  33169. var i3 = (i + 1) * (e + 1) + (j + 1);
  33170. indices.push(i0, i1, i2);
  33171. indices.push(i3, i2, i1);
  33172. }
  33173. if (arc !== 1 && enclose) {
  33174. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33175. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33176. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33177. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33178. }
  33179. i = (hasRings) ? (i + 2) : (i + 1);
  33180. }
  33181. // Caps
  33182. var createCylinderCap = function (isTop) {
  33183. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33184. if (radius === 0) {
  33185. return;
  33186. }
  33187. // Cap positions, normals & uvs
  33188. var angle;
  33189. var circleVector;
  33190. var i;
  33191. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33192. var c;
  33193. if (faceColors) {
  33194. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33195. }
  33196. // cap center
  33197. var vbase = positions.length / 3;
  33198. var offset = isTop ? height / 2 : -height / 2;
  33199. var center = new BABYLON.Vector3(0, offset, 0);
  33200. positions.push(center.x, center.y, center.z);
  33201. normals.push(0, isTop ? 1 : -1, 0);
  33202. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33203. if (faceColors) {
  33204. colors.push(c.r, c.g, c.b, c.a);
  33205. }
  33206. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33207. for (i = 0; i <= tessellation; i++) {
  33208. angle = Math.PI * 2 * i * arc / tessellation;
  33209. var cos = Math.cos(-angle);
  33210. var sin = Math.sin(-angle);
  33211. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33212. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33213. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33214. normals.push(0, isTop ? 1 : -1, 0);
  33215. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33216. if (faceColors) {
  33217. colors.push(c.r, c.g, c.b, c.a);
  33218. }
  33219. }
  33220. // Cap indices
  33221. for (i = 0; i < tessellation; i++) {
  33222. if (!isTop) {
  33223. indices.push(vbase);
  33224. indices.push(vbase + (i + 1));
  33225. indices.push(vbase + (i + 2));
  33226. }
  33227. else {
  33228. indices.push(vbase);
  33229. indices.push(vbase + (i + 2));
  33230. indices.push(vbase + (i + 1));
  33231. }
  33232. }
  33233. };
  33234. // add caps to geometry
  33235. createCylinderCap(false);
  33236. createCylinderCap(true);
  33237. // Sides
  33238. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33239. var vertexData = new VertexData();
  33240. vertexData.indices = indices;
  33241. vertexData.positions = positions;
  33242. vertexData.normals = normals;
  33243. vertexData.uvs = uvs;
  33244. if (faceColors) {
  33245. vertexData.colors = colors;
  33246. }
  33247. return vertexData;
  33248. };
  33249. VertexData.CreateTorus = function (options) {
  33250. var indices = [];
  33251. var positions = [];
  33252. var normals = [];
  33253. var uvs = [];
  33254. var diameter = options.diameter || 1;
  33255. var thickness = options.thickness || 0.5;
  33256. var tessellation = options.tessellation || 16;
  33257. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33258. var stride = tessellation + 1;
  33259. for (var i = 0; i <= tessellation; i++) {
  33260. var u = i / tessellation;
  33261. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33262. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33263. for (var j = 0; j <= tessellation; j++) {
  33264. var v = 1 - j / tessellation;
  33265. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33266. var dx = Math.cos(innerAngle);
  33267. var dy = Math.sin(innerAngle);
  33268. // Create a vertex.
  33269. var normal = new BABYLON.Vector3(dx, dy, 0);
  33270. var position = normal.scale(thickness / 2);
  33271. var textureCoordinate = new BABYLON.Vector2(u, v);
  33272. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33273. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33274. positions.push(position.x, position.y, position.z);
  33275. normals.push(normal.x, normal.y, normal.z);
  33276. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33277. // And create indices for two triangles.
  33278. var nextI = (i + 1) % stride;
  33279. var nextJ = (j + 1) % stride;
  33280. indices.push(i * stride + j);
  33281. indices.push(i * stride + nextJ);
  33282. indices.push(nextI * stride + j);
  33283. indices.push(i * stride + nextJ);
  33284. indices.push(nextI * stride + nextJ);
  33285. indices.push(nextI * stride + j);
  33286. }
  33287. }
  33288. // Sides
  33289. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33290. // Result
  33291. var vertexData = new VertexData();
  33292. vertexData.indices = indices;
  33293. vertexData.positions = positions;
  33294. vertexData.normals = normals;
  33295. vertexData.uvs = uvs;
  33296. return vertexData;
  33297. };
  33298. VertexData.CreateLineSystem = function (options) {
  33299. var indices = [];
  33300. var positions = [];
  33301. var lines = options.lines;
  33302. var idx = 0;
  33303. for (var l = 0; l < lines.length; l++) {
  33304. var points = lines[l];
  33305. for (var index = 0; index < points.length; index++) {
  33306. positions.push(points[index].x, points[index].y, points[index].z);
  33307. if (index > 0) {
  33308. indices.push(idx - 1);
  33309. indices.push(idx);
  33310. }
  33311. idx++;
  33312. }
  33313. }
  33314. var vertexData = new VertexData();
  33315. vertexData.indices = indices;
  33316. vertexData.positions = positions;
  33317. return vertexData;
  33318. };
  33319. VertexData.CreateDashedLines = function (options) {
  33320. var dashSize = options.dashSize || 3;
  33321. var gapSize = options.gapSize || 1;
  33322. var dashNb = options.dashNb || 200;
  33323. var points = options.points;
  33324. var positions = new Array();
  33325. var indices = new Array();
  33326. var curvect = BABYLON.Vector3.Zero();
  33327. var lg = 0;
  33328. var nb = 0;
  33329. var shft = 0;
  33330. var dashshft = 0;
  33331. var curshft = 0;
  33332. var idx = 0;
  33333. var i = 0;
  33334. for (i = 0; i < points.length - 1; i++) {
  33335. points[i + 1].subtractToRef(points[i], curvect);
  33336. lg += curvect.length();
  33337. }
  33338. shft = lg / dashNb;
  33339. dashshft = dashSize * shft / (dashSize + gapSize);
  33340. for (i = 0; i < points.length - 1; i++) {
  33341. points[i + 1].subtractToRef(points[i], curvect);
  33342. nb = Math.floor(curvect.length() / shft);
  33343. curvect.normalize();
  33344. for (var j = 0; j < nb; j++) {
  33345. curshft = shft * j;
  33346. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33347. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33348. indices.push(idx, idx + 1);
  33349. idx += 2;
  33350. }
  33351. }
  33352. // Result
  33353. var vertexData = new VertexData();
  33354. vertexData.positions = positions;
  33355. vertexData.indices = indices;
  33356. return vertexData;
  33357. };
  33358. VertexData.CreateGround = function (options) {
  33359. var indices = [];
  33360. var positions = [];
  33361. var normals = [];
  33362. var uvs = [];
  33363. var row, col;
  33364. var width = options.width || 1;
  33365. var height = options.height || 1;
  33366. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33367. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33368. for (row = 0; row <= subdivisionsY; row++) {
  33369. for (col = 0; col <= subdivisionsX; col++) {
  33370. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33371. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33372. positions.push(position.x, position.y, position.z);
  33373. normals.push(normal.x, normal.y, normal.z);
  33374. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  33375. }
  33376. }
  33377. for (row = 0; row < subdivisionsY; row++) {
  33378. for (col = 0; col < subdivisionsX; col++) {
  33379. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33380. indices.push(col + 1 + row * (subdivisionsX + 1));
  33381. indices.push(col + row * (subdivisionsX + 1));
  33382. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33383. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33384. indices.push(col + row * (subdivisionsX + 1));
  33385. }
  33386. }
  33387. // Result
  33388. var vertexData = new VertexData();
  33389. vertexData.indices = indices;
  33390. vertexData.positions = positions;
  33391. vertexData.normals = normals;
  33392. vertexData.uvs = uvs;
  33393. return vertexData;
  33394. };
  33395. VertexData.CreateTiledGround = function (options) {
  33396. var xmin = options.xmin || -1.0;
  33397. var zmin = options.zmin || -1.0;
  33398. var xmax = options.xmax || 1.0;
  33399. var zmax = options.zmax || 1.0;
  33400. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33401. var precision = options.precision || { w: 1, h: 1 };
  33402. var indices = [];
  33403. var positions = [];
  33404. var normals = [];
  33405. var uvs = [];
  33406. var row, col, tileRow, tileCol;
  33407. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33408. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33409. precision.w = (precision.w < 1) ? 1 : precision.w;
  33410. precision.h = (precision.h < 1) ? 1 : precision.h;
  33411. var tileSize = {
  33412. 'w': (xmax - xmin) / subdivisions.w,
  33413. 'h': (zmax - zmin) / subdivisions.h
  33414. };
  33415. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33416. // Indices
  33417. var base = positions.length / 3;
  33418. var rowLength = precision.w + 1;
  33419. for (row = 0; row < precision.h; row++) {
  33420. for (col = 0; col < precision.w; col++) {
  33421. var square = [
  33422. base + col + row * rowLength,
  33423. base + (col + 1) + row * rowLength,
  33424. base + (col + 1) + (row + 1) * rowLength,
  33425. base + col + (row + 1) * rowLength
  33426. ];
  33427. indices.push(square[1]);
  33428. indices.push(square[2]);
  33429. indices.push(square[3]);
  33430. indices.push(square[0]);
  33431. indices.push(square[1]);
  33432. indices.push(square[3]);
  33433. }
  33434. }
  33435. // Position, normals and uvs
  33436. var position = BABYLON.Vector3.Zero();
  33437. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33438. for (row = 0; row <= precision.h; row++) {
  33439. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33440. for (col = 0; col <= precision.w; col++) {
  33441. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33442. position.y = 0;
  33443. positions.push(position.x, position.y, position.z);
  33444. normals.push(normal.x, normal.y, normal.z);
  33445. uvs.push(col / precision.w, row / precision.h);
  33446. }
  33447. }
  33448. }
  33449. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33450. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33451. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33452. }
  33453. }
  33454. // Result
  33455. var vertexData = new VertexData();
  33456. vertexData.indices = indices;
  33457. vertexData.positions = positions;
  33458. vertexData.normals = normals;
  33459. vertexData.uvs = uvs;
  33460. return vertexData;
  33461. };
  33462. VertexData.CreateGroundFromHeightMap = function (options) {
  33463. var indices = [];
  33464. var positions = [];
  33465. var normals = [];
  33466. var uvs = [];
  33467. var row, col;
  33468. // Vertices
  33469. for (row = 0; row <= options.subdivisions; row++) {
  33470. for (col = 0; col <= options.subdivisions; col++) {
  33471. 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));
  33472. // Compute height
  33473. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33474. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33475. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33476. var r = options.buffer[pos] / 255.0;
  33477. var g = options.buffer[pos + 1] / 255.0;
  33478. var b = options.buffer[pos + 2] / 255.0;
  33479. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33480. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33481. // Add vertex
  33482. positions.push(position.x, position.y, position.z);
  33483. normals.push(0, 0, 0);
  33484. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33485. }
  33486. }
  33487. // Indices
  33488. for (row = 0; row < options.subdivisions; row++) {
  33489. for (col = 0; col < options.subdivisions; col++) {
  33490. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33491. indices.push(col + 1 + row * (options.subdivisions + 1));
  33492. indices.push(col + row * (options.subdivisions + 1));
  33493. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33494. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33495. indices.push(col + row * (options.subdivisions + 1));
  33496. }
  33497. }
  33498. // Normals
  33499. VertexData.ComputeNormals(positions, indices, normals);
  33500. // Result
  33501. var vertexData = new VertexData();
  33502. vertexData.indices = indices;
  33503. vertexData.positions = positions;
  33504. vertexData.normals = normals;
  33505. vertexData.uvs = uvs;
  33506. return vertexData;
  33507. };
  33508. VertexData.CreatePlane = function (options) {
  33509. var indices = [];
  33510. var positions = [];
  33511. var normals = [];
  33512. var uvs = [];
  33513. var width = options.width || options.size || 1;
  33514. var height = options.height || options.size || 1;
  33515. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33516. // Vertices
  33517. var halfWidth = width / 2.0;
  33518. var halfHeight = height / 2.0;
  33519. positions.push(-halfWidth, -halfHeight, 0);
  33520. normals.push(0, 0, -1.0);
  33521. uvs.push(0.0, 0.0);
  33522. positions.push(halfWidth, -halfHeight, 0);
  33523. normals.push(0, 0, -1.0);
  33524. uvs.push(1.0, 0.0);
  33525. positions.push(halfWidth, halfHeight, 0);
  33526. normals.push(0, 0, -1.0);
  33527. uvs.push(1.0, 1.0);
  33528. positions.push(-halfWidth, halfHeight, 0);
  33529. normals.push(0, 0, -1.0);
  33530. uvs.push(0.0, 1.0);
  33531. // Indices
  33532. indices.push(0);
  33533. indices.push(1);
  33534. indices.push(2);
  33535. indices.push(0);
  33536. indices.push(2);
  33537. indices.push(3);
  33538. // Sides
  33539. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33540. // Result
  33541. var vertexData = new VertexData();
  33542. vertexData.indices = indices;
  33543. vertexData.positions = positions;
  33544. vertexData.normals = normals;
  33545. vertexData.uvs = uvs;
  33546. return vertexData;
  33547. };
  33548. VertexData.CreateDisc = function (options) {
  33549. var positions = [];
  33550. var indices = [];
  33551. var normals = [];
  33552. var uvs = [];
  33553. var radius = options.radius || 0.5;
  33554. var tessellation = options.tessellation || 64;
  33555. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33556. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33557. // positions and uvs
  33558. positions.push(0, 0, 0); // disc center first
  33559. uvs.push(0.5, 0.5);
  33560. var theta = Math.PI * 2 * arc;
  33561. var step = theta / tessellation;
  33562. for (var a = 0; a < theta; a += step) {
  33563. var x = Math.cos(a);
  33564. var y = Math.sin(a);
  33565. var u = (x + 1) / 2;
  33566. var v = (1 - y) / 2;
  33567. positions.push(radius * x, radius * y, 0);
  33568. uvs.push(u, v);
  33569. }
  33570. if (arc === 1) {
  33571. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33572. uvs.push(uvs[2], uvs[3]);
  33573. }
  33574. //indices
  33575. var vertexNb = positions.length / 3;
  33576. for (var i = 1; i < vertexNb - 1; i++) {
  33577. indices.push(i + 1, 0, i);
  33578. }
  33579. // result
  33580. VertexData.ComputeNormals(positions, indices, normals);
  33581. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33582. var vertexData = new VertexData();
  33583. vertexData.indices = indices;
  33584. vertexData.positions = positions;
  33585. vertexData.normals = normals;
  33586. vertexData.uvs = uvs;
  33587. return vertexData;
  33588. };
  33589. VertexData.CreateIcoSphere = function (options) {
  33590. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33591. var radius = options.radius || 1;
  33592. var flat = (options.flat === undefined) ? true : options.flat;
  33593. var subdivisions = options.subdivisions || 4;
  33594. var radiusX = options.radiusX || radius;
  33595. var radiusY = options.radiusY || radius;
  33596. var radiusZ = options.radiusZ || radius;
  33597. var t = (1 + Math.sqrt(5)) / 2;
  33598. // 12 vertex x,y,z
  33599. var ico_vertices = [
  33600. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33601. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33602. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33603. ];
  33604. // index of 3 vertex makes a face of icopshere
  33605. var ico_indices = [
  33606. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33607. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33608. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33609. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33610. ];
  33611. // vertex for uv have aliased position, not for UV
  33612. var vertices_unalias_id = [
  33613. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33614. // vertex alias
  33615. 0,
  33616. 2,
  33617. 3,
  33618. 3,
  33619. 3,
  33620. 4,
  33621. 7,
  33622. 8,
  33623. 9,
  33624. 9,
  33625. 10,
  33626. 11 // 23: B + 12
  33627. ];
  33628. // uv as integer step (not pixels !)
  33629. var ico_vertexuv = [
  33630. 5, 1, 3, 1, 6, 4, 0, 0,
  33631. 5, 3, 4, 2, 2, 2, 4, 0,
  33632. 2, 0, 1, 1, 6, 0, 6, 2,
  33633. // vertex alias (for same vertex on different faces)
  33634. 0, 4,
  33635. 3, 3,
  33636. 4, 4,
  33637. 3, 1,
  33638. 4, 2,
  33639. 4, 4,
  33640. 0, 2,
  33641. 1, 1,
  33642. 2, 2,
  33643. 3, 3,
  33644. 1, 3,
  33645. 2, 4 // 23: B + 12
  33646. ];
  33647. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33648. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33649. // First island of uv mapping
  33650. // v = 4h 3+ 2
  33651. // v = 3h 9+ 4
  33652. // v = 2h 9+ 5 B
  33653. // v = 1h 9 1 0
  33654. // v = 0h 3 8 7 A
  33655. // u = 0 1 2 3 4 5 6 *a
  33656. // Second island of uv mapping
  33657. // v = 4h 0+ B+ 4+
  33658. // v = 3h A+ 2+
  33659. // v = 2h 7+ 6 3+
  33660. // v = 1h 8+ 3+
  33661. // v = 0h
  33662. // u = 0 1 2 3 4 5 6 *a
  33663. // Face layout on texture UV mapping
  33664. // ============
  33665. // \ 4 /\ 16 / ======
  33666. // \ / \ / /\ 11 /
  33667. // \/ 7 \/ / \ /
  33668. // ======= / 10 \/
  33669. // /\ 17 /\ =======
  33670. // / \ / \ \ 15 /\
  33671. // / 8 \/ 12 \ \ / \
  33672. // ============ \/ 6 \
  33673. // \ 18 /\ ============
  33674. // \ / \ \ 5 /\ 0 /
  33675. // \/ 13 \ \ / \ /
  33676. // ======= \/ 1 \/
  33677. // =============
  33678. // /\ 19 /\ 2 /\
  33679. // / \ / \ / \
  33680. // / 14 \/ 9 \/ 3 \
  33681. // ===================
  33682. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33683. var ustep = 138 / 1024;
  33684. var vstep = 239 / 1024;
  33685. var uoffset = 60 / 1024;
  33686. var voffset = 26 / 1024;
  33687. // Second island should have margin, not to touch the first island
  33688. // avoid any borderline artefact in pixel rounding
  33689. var island_u_offset = -40 / 1024;
  33690. var island_v_offset = +20 / 1024;
  33691. // face is either island 0 or 1 :
  33692. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33693. var island = [
  33694. 0, 0, 0, 0, 1,
  33695. 0, 0, 1, 1, 0,
  33696. 0, 0, 1, 1, 0,
  33697. 0, 1, 1, 1, 0 // 15 - 19
  33698. ];
  33699. var indices = [];
  33700. var positions = [];
  33701. var normals = [];
  33702. var uvs = [];
  33703. var current_indice = 0;
  33704. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33705. var face_vertex_pos = new Array(3);
  33706. var face_vertex_uv = new Array(3);
  33707. var v012;
  33708. for (v012 = 0; v012 < 3; v012++) {
  33709. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33710. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33711. }
  33712. // create all with normals
  33713. for (var face = 0; face < 20; face++) {
  33714. // 3 vertex per face
  33715. for (v012 = 0; v012 < 3; v012++) {
  33716. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33717. var v_id = ico_indices[3 * face + v012];
  33718. // vertex have 3D position (x,y,z)
  33719. 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]);
  33720. // Normalize to get normal, then scale to radius
  33721. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33722. // uv Coordinates from vertex ID
  33723. 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);
  33724. }
  33725. // Subdivide the face (interpolate pos, norm, uv)
  33726. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33727. // - norm is linear interpolation of vertex corner normal
  33728. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33729. // - uv is linear interpolation
  33730. //
  33731. // Topology is as below for sub-divide by 2
  33732. // vertex shown as v0,v1,v2
  33733. // interp index is i1 to progress in range [v0,v1[
  33734. // interp index is i2 to progress in range [v0,v2[
  33735. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33736. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33737. //
  33738. //
  33739. // i2 v2
  33740. // ^ ^
  33741. // / / \
  33742. // / / \
  33743. // / / \
  33744. // / / (0,1) \
  33745. // / #---------\
  33746. // / / \ (0,0)'/ \
  33747. // / / \ / \
  33748. // / / \ / \
  33749. // / / (0,0) \ / (1,0) \
  33750. // / #---------#---------\
  33751. // v0 v1
  33752. //
  33753. // --------------------> i1
  33754. //
  33755. // interp of (i1,i2):
  33756. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33757. // along i1 : lerp(x0,x1, i1/(S-i2))
  33758. //
  33759. // centroid of triangle is needed to get help normal computation
  33760. // (c1,c2) are used for centroid location
  33761. var interp_vertex = function (i1, i2, c1, c2) {
  33762. // vertex is interpolated from
  33763. // - face_vertex_pos[0..2]
  33764. // - face_vertex_uv[0..2]
  33765. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33766. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33767. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33768. pos_interp.normalize();
  33769. var vertex_normal;
  33770. if (flat) {
  33771. // in flat mode, recalculate normal as face centroid normal
  33772. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33773. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33774. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33775. }
  33776. else {
  33777. // in smooth mode, recalculate normal from each single vertex position
  33778. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33779. }
  33780. // Vertex normal need correction due to X,Y,Z radius scaling
  33781. vertex_normal.x /= radiusX;
  33782. vertex_normal.y /= radiusY;
  33783. vertex_normal.z /= radiusZ;
  33784. vertex_normal.normalize();
  33785. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33786. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33787. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33788. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33789. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33790. uvs.push(uv_interp.x, uv_interp.y);
  33791. // push each vertex has member of a face
  33792. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33793. indices.push(current_indice);
  33794. current_indice++;
  33795. };
  33796. for (var i2 = 0; i2 < subdivisions; i2++) {
  33797. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33798. // face : (i1,i2) for /\ :
  33799. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33800. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33801. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33802. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33803. if (i1 + i2 + 1 < subdivisions) {
  33804. // face : (i1,i2)' for \/ :
  33805. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33806. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33807. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33808. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33809. }
  33810. }
  33811. }
  33812. }
  33813. // Sides
  33814. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33815. // Result
  33816. var vertexData = new VertexData();
  33817. vertexData.indices = indices;
  33818. vertexData.positions = positions;
  33819. vertexData.normals = normals;
  33820. vertexData.uvs = uvs;
  33821. return vertexData;
  33822. };
  33823. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33824. VertexData.CreatePolyhedron = function (options) {
  33825. // provided polyhedron types :
  33826. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33827. // 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)
  33828. var polyhedra = [];
  33829. 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]] };
  33830. 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]] };
  33831. polyhedra[2] = {
  33832. 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]],
  33833. 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]]
  33834. };
  33835. polyhedra[3] = {
  33836. 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]],
  33837. 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]]
  33838. };
  33839. polyhedra[4] = {
  33840. 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]],
  33841. 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]]
  33842. };
  33843. 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]] };
  33844. 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]] };
  33845. 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]] };
  33846. 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]] };
  33847. 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]] };
  33848. 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]] };
  33849. 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]] };
  33850. 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]] };
  33851. 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]] };
  33852. polyhedra[14] = {
  33853. 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]],
  33854. 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]]
  33855. };
  33856. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33857. var size = options.size;
  33858. var sizeX = options.sizeX || size || 1;
  33859. var sizeY = options.sizeY || size || 1;
  33860. var sizeZ = options.sizeZ || size || 1;
  33861. var data = options.custom || polyhedra[type];
  33862. var nbfaces = data.face.length;
  33863. var faceUV = options.faceUV || new Array(nbfaces);
  33864. var faceColors = options.faceColors;
  33865. var flat = (options.flat === undefined) ? true : options.flat;
  33866. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33867. var positions = [];
  33868. var indices = [];
  33869. var normals = [];
  33870. var uvs = [];
  33871. var colors = [];
  33872. var index = 0;
  33873. var faceIdx = 0; // face cursor in the array "indexes"
  33874. var indexes = [];
  33875. var i = 0;
  33876. var f = 0;
  33877. var u, v, ang, x, y, tmp;
  33878. // default face colors and UV if undefined
  33879. if (flat) {
  33880. for (f = 0; f < nbfaces; f++) {
  33881. if (faceColors && faceColors[f] === undefined) {
  33882. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33883. }
  33884. if (faceUV && faceUV[f] === undefined) {
  33885. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33886. }
  33887. }
  33888. }
  33889. if (!flat) {
  33890. for (i = 0; i < data.vertex.length; i++) {
  33891. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33892. uvs.push(0, 0);
  33893. }
  33894. for (f = 0; f < nbfaces; f++) {
  33895. for (i = 0; i < data.face[f].length - 2; i++) {
  33896. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33897. }
  33898. }
  33899. }
  33900. else {
  33901. for (f = 0; f < nbfaces; f++) {
  33902. var fl = data.face[f].length; // number of vertices of the current face
  33903. ang = 2 * Math.PI / fl;
  33904. x = 0.5 * Math.tan(ang / 2);
  33905. y = 0.5;
  33906. // positions, uvs, colors
  33907. for (i = 0; i < fl; i++) {
  33908. // positions
  33909. 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);
  33910. indexes.push(index);
  33911. index++;
  33912. // uvs
  33913. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33914. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33915. uvs.push(u, v);
  33916. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33917. y = x * Math.sin(ang) + y * Math.cos(ang);
  33918. x = tmp;
  33919. // colors
  33920. if (faceColors) {
  33921. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33922. }
  33923. }
  33924. // indices from indexes
  33925. for (i = 0; i < fl - 2; i++) {
  33926. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33927. }
  33928. faceIdx += fl;
  33929. }
  33930. }
  33931. VertexData.ComputeNormals(positions, indices, normals);
  33932. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33933. var vertexData = new VertexData();
  33934. vertexData.positions = positions;
  33935. vertexData.indices = indices;
  33936. vertexData.normals = normals;
  33937. vertexData.uvs = uvs;
  33938. if (faceColors && flat) {
  33939. vertexData.colors = colors;
  33940. }
  33941. return vertexData;
  33942. };
  33943. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33944. VertexData.CreateTorusKnot = function (options) {
  33945. var indices = [];
  33946. var positions = [];
  33947. var normals = [];
  33948. var uvs = [];
  33949. var radius = options.radius || 2;
  33950. var tube = options.tube || 0.5;
  33951. var radialSegments = options.radialSegments || 32;
  33952. var tubularSegments = options.tubularSegments || 32;
  33953. var p = options.p || 2;
  33954. var q = options.q || 3;
  33955. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33956. // Helper
  33957. var getPos = function (angle) {
  33958. var cu = Math.cos(angle);
  33959. var su = Math.sin(angle);
  33960. var quOverP = q / p * angle;
  33961. var cs = Math.cos(quOverP);
  33962. var tx = radius * (2 + cs) * 0.5 * cu;
  33963. var ty = radius * (2 + cs) * su * 0.5;
  33964. var tz = radius * Math.sin(quOverP) * 0.5;
  33965. return new BABYLON.Vector3(tx, ty, tz);
  33966. };
  33967. // Vertices
  33968. var i;
  33969. var j;
  33970. for (i = 0; i <= radialSegments; i++) {
  33971. var modI = i % radialSegments;
  33972. var u = modI / radialSegments * 2 * p * Math.PI;
  33973. var p1 = getPos(u);
  33974. var p2 = getPos(u + 0.01);
  33975. var tang = p2.subtract(p1);
  33976. var n = p2.add(p1);
  33977. var bitan = BABYLON.Vector3.Cross(tang, n);
  33978. n = BABYLON.Vector3.Cross(bitan, tang);
  33979. bitan.normalize();
  33980. n.normalize();
  33981. for (j = 0; j < tubularSegments; j++) {
  33982. var modJ = j % tubularSegments;
  33983. var v = modJ / tubularSegments * 2 * Math.PI;
  33984. var cx = -tube * Math.cos(v);
  33985. var cy = tube * Math.sin(v);
  33986. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33987. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33988. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33989. uvs.push(i / radialSegments);
  33990. uvs.push(j / tubularSegments);
  33991. }
  33992. }
  33993. for (i = 0; i < radialSegments; i++) {
  33994. for (j = 0; j < tubularSegments; j++) {
  33995. var jNext = (j + 1) % tubularSegments;
  33996. var a = i * tubularSegments + j;
  33997. var b = (i + 1) * tubularSegments + j;
  33998. var c = (i + 1) * tubularSegments + jNext;
  33999. var d = i * tubularSegments + jNext;
  34000. indices.push(d);
  34001. indices.push(b);
  34002. indices.push(a);
  34003. indices.push(d);
  34004. indices.push(c);
  34005. indices.push(b);
  34006. }
  34007. }
  34008. // Normals
  34009. VertexData.ComputeNormals(positions, indices, normals);
  34010. // Sides
  34011. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34012. // Result
  34013. var vertexData = new VertexData();
  34014. vertexData.indices = indices;
  34015. vertexData.positions = positions;
  34016. vertexData.normals = normals;
  34017. vertexData.uvs = uvs;
  34018. return vertexData;
  34019. };
  34020. // Tools
  34021. /**
  34022. * @param {any} - positions (number[] or Float32Array)
  34023. * @param {any} - indices (number[] or Uint16Array)
  34024. * @param {any} - normals (number[] or Float32Array)
  34025. */
  34026. VertexData.ComputeNormals = function (positions, indices, normals) {
  34027. var index = 0;
  34028. var p1p2x = 0.0;
  34029. var p1p2y = 0.0;
  34030. var p1p2z = 0.0;
  34031. var p3p2x = 0.0;
  34032. var p3p2y = 0.0;
  34033. var p3p2z = 0.0;
  34034. var faceNormalx = 0.0;
  34035. var faceNormaly = 0.0;
  34036. var faceNormalz = 0.0;
  34037. var length = 0.0;
  34038. var i1 = 0;
  34039. var i2 = 0;
  34040. var i3 = 0;
  34041. for (index = 0; index < positions.length; index++) {
  34042. normals[index] = 0.0;
  34043. }
  34044. // indice triplet = 1 face
  34045. var nbFaces = indices.length / 3;
  34046. for (index = 0; index < nbFaces; index++) {
  34047. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  34048. i2 = indices[index * 3 + 1];
  34049. i3 = indices[index * 3 + 2];
  34050. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  34051. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  34052. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  34053. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  34054. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  34055. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  34056. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  34057. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  34058. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  34059. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34060. length = (length === 0) ? 1.0 : length;
  34061. faceNormalx /= length; // normalize this normal
  34062. faceNormaly /= length;
  34063. faceNormalz /= length;
  34064. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  34065. normals[i1 * 3 + 1] += faceNormaly;
  34066. normals[i1 * 3 + 2] += faceNormalz;
  34067. normals[i2 * 3] += faceNormalx;
  34068. normals[i2 * 3 + 1] += faceNormaly;
  34069. normals[i2 * 3 + 2] += faceNormalz;
  34070. normals[i3 * 3] += faceNormalx;
  34071. normals[i3 * 3 + 1] += faceNormaly;
  34072. normals[i3 * 3 + 2] += faceNormalz;
  34073. }
  34074. // last normalization of each normal
  34075. for (index = 0; index < normals.length / 3; index++) {
  34076. faceNormalx = normals[index * 3];
  34077. faceNormaly = normals[index * 3 + 1];
  34078. faceNormalz = normals[index * 3 + 2];
  34079. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34080. length = (length === 0) ? 1.0 : length;
  34081. faceNormalx /= length;
  34082. faceNormaly /= length;
  34083. faceNormalz /= length;
  34084. normals[index * 3] = faceNormalx;
  34085. normals[index * 3 + 1] = faceNormaly;
  34086. normals[index * 3 + 2] = faceNormalz;
  34087. }
  34088. };
  34089. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  34090. var li = indices.length;
  34091. var ln = normals.length;
  34092. var i;
  34093. var n;
  34094. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34095. switch (sideOrientation) {
  34096. case BABYLON.Mesh.FRONTSIDE:
  34097. // nothing changed
  34098. break;
  34099. case BABYLON.Mesh.BACKSIDE:
  34100. var tmp;
  34101. // indices
  34102. for (i = 0; i < li; i += 3) {
  34103. tmp = indices[i];
  34104. indices[i] = indices[i + 2];
  34105. indices[i + 2] = tmp;
  34106. }
  34107. // normals
  34108. for (n = 0; n < ln; n++) {
  34109. normals[n] = -normals[n];
  34110. }
  34111. break;
  34112. case BABYLON.Mesh.DOUBLESIDE:
  34113. // positions
  34114. var lp = positions.length;
  34115. var l = lp / 3;
  34116. for (var p = 0; p < lp; p++) {
  34117. positions[lp + p] = positions[p];
  34118. }
  34119. // indices
  34120. for (i = 0; i < li; i += 3) {
  34121. indices[i + li] = indices[i + 2] + l;
  34122. indices[i + 1 + li] = indices[i + 1] + l;
  34123. indices[i + 2 + li] = indices[i] + l;
  34124. }
  34125. // normals
  34126. for (n = 0; n < ln; n++) {
  34127. normals[ln + n] = -normals[n];
  34128. }
  34129. // uvs
  34130. var lu = uvs.length;
  34131. for (var u = 0; u < lu; u++) {
  34132. uvs[u + lu] = uvs[u];
  34133. }
  34134. break;
  34135. }
  34136. };
  34137. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34138. var vertexData = new VertexData();
  34139. // positions
  34140. var positions = parsedVertexData.positions;
  34141. if (positions) {
  34142. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34143. }
  34144. // normals
  34145. var normals = parsedVertexData.normals;
  34146. if (normals) {
  34147. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34148. }
  34149. // uvs
  34150. var uvs = parsedVertexData.uvs;
  34151. if (uvs) {
  34152. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34153. }
  34154. // uv2s
  34155. var uv2s = parsedVertexData.uv2s;
  34156. if (uv2s) {
  34157. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34158. }
  34159. // uv3s
  34160. var uv3s = parsedVertexData.uv3s;
  34161. if (uv3s) {
  34162. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34163. }
  34164. // uv4s
  34165. var uv4s = parsedVertexData.uv4s;
  34166. if (uv4s) {
  34167. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34168. }
  34169. // uv5s
  34170. var uv5s = parsedVertexData.uv5s;
  34171. if (uv5s) {
  34172. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34173. }
  34174. // uv6s
  34175. var uv6s = parsedVertexData.uv6s;
  34176. if (uv6s) {
  34177. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34178. }
  34179. // colors
  34180. var colors = parsedVertexData.colors;
  34181. if (colors) {
  34182. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34183. }
  34184. // matricesIndices
  34185. var matricesIndices = parsedVertexData.matricesIndices;
  34186. if (matricesIndices) {
  34187. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34188. }
  34189. // matricesWeights
  34190. var matricesWeights = parsedVertexData.matricesWeights;
  34191. if (matricesWeights) {
  34192. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34193. }
  34194. // indices
  34195. var indices = parsedVertexData.indices;
  34196. if (indices) {
  34197. vertexData.indices = indices;
  34198. }
  34199. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34200. };
  34201. return VertexData;
  34202. }());
  34203. BABYLON.VertexData = VertexData;
  34204. })(BABYLON || (BABYLON = {}));
  34205. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34206. var BABYLON;
  34207. (function (BABYLON) {
  34208. var Tags = (function () {
  34209. function Tags() {
  34210. }
  34211. Tags.EnableFor = function (obj) {
  34212. obj._tags = obj._tags || {};
  34213. obj.hasTags = function () {
  34214. return Tags.HasTags(obj);
  34215. };
  34216. obj.addTags = function (tagsString) {
  34217. return Tags.AddTagsTo(obj, tagsString);
  34218. };
  34219. obj.removeTags = function (tagsString) {
  34220. return Tags.RemoveTagsFrom(obj, tagsString);
  34221. };
  34222. obj.matchesTagsQuery = function (tagsQuery) {
  34223. return Tags.MatchesQuery(obj, tagsQuery);
  34224. };
  34225. };
  34226. Tags.DisableFor = function (obj) {
  34227. delete obj._tags;
  34228. delete obj.hasTags;
  34229. delete obj.addTags;
  34230. delete obj.removeTags;
  34231. delete obj.matchesTagsQuery;
  34232. };
  34233. Tags.HasTags = function (obj) {
  34234. if (!obj._tags) {
  34235. return false;
  34236. }
  34237. return !BABYLON.Tools.IsEmpty(obj._tags);
  34238. };
  34239. Tags.GetTags = function (obj, asString) {
  34240. if (asString === void 0) { asString = true; }
  34241. if (!obj._tags) {
  34242. return null;
  34243. }
  34244. if (asString) {
  34245. var tagsArray = [];
  34246. for (var tag in obj._tags) {
  34247. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  34248. tagsArray.push(tag);
  34249. }
  34250. }
  34251. return tagsArray.join(" ");
  34252. }
  34253. else {
  34254. return obj._tags;
  34255. }
  34256. };
  34257. // the tags 'true' and 'false' are reserved and cannot be used as tags
  34258. // a tag cannot start with '||', '&&', and '!'
  34259. // it cannot contain whitespaces
  34260. Tags.AddTagsTo = function (obj, tagsString) {
  34261. if (!tagsString) {
  34262. return;
  34263. }
  34264. if (typeof tagsString !== "string") {
  34265. return;
  34266. }
  34267. var tags = tagsString.split(" ");
  34268. tags.forEach(function (tag, index, array) {
  34269. Tags._AddTagTo(obj, tag);
  34270. });
  34271. };
  34272. Tags._AddTagTo = function (obj, tag) {
  34273. tag = tag.trim();
  34274. if (tag === "" || tag === "true" || tag === "false") {
  34275. return;
  34276. }
  34277. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  34278. return;
  34279. }
  34280. Tags.EnableFor(obj);
  34281. obj._tags[tag] = true;
  34282. };
  34283. Tags.RemoveTagsFrom = function (obj, tagsString) {
  34284. if (!Tags.HasTags(obj)) {
  34285. return;
  34286. }
  34287. var tags = tagsString.split(" ");
  34288. for (var t in tags) {
  34289. Tags._RemoveTagFrom(obj, tags[t]);
  34290. }
  34291. };
  34292. Tags._RemoveTagFrom = function (obj, tag) {
  34293. delete obj._tags[tag];
  34294. };
  34295. Tags.MatchesQuery = function (obj, tagsQuery) {
  34296. if (tagsQuery === undefined) {
  34297. return true;
  34298. }
  34299. if (tagsQuery === "") {
  34300. return Tags.HasTags(obj);
  34301. }
  34302. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  34303. };
  34304. return Tags;
  34305. }());
  34306. BABYLON.Tags = Tags;
  34307. })(BABYLON || (BABYLON = {}));
  34308. //# sourceMappingURL=babylon.tags.js.map
  34309. var BABYLON;
  34310. (function (BABYLON) {
  34311. var Internals;
  34312. (function (Internals) {
  34313. var AndOrNotEvaluator = (function () {
  34314. function AndOrNotEvaluator() {
  34315. }
  34316. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  34317. if (!query.match(/\([^\(\)]*\)/g)) {
  34318. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  34319. }
  34320. else {
  34321. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  34322. // remove parenthesis
  34323. r = r.slice(1, r.length - 1);
  34324. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  34325. });
  34326. }
  34327. if (query === "true") {
  34328. return true;
  34329. }
  34330. if (query === "false") {
  34331. return false;
  34332. }
  34333. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  34334. };
  34335. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  34336. evaluateCallback = evaluateCallback || (function (r) {
  34337. return r === "true" ? true : false;
  34338. });
  34339. var result;
  34340. var or = parenthesisContent.split("||");
  34341. for (var i in or) {
  34342. if (or.hasOwnProperty(i)) {
  34343. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  34344. var and = ori.split("&&");
  34345. if (and.length > 1) {
  34346. for (var j = 0; j < and.length; ++j) {
  34347. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  34348. if (andj !== "true" && andj !== "false") {
  34349. if (andj[0] === "!") {
  34350. result = !evaluateCallback(andj.substring(1));
  34351. }
  34352. else {
  34353. result = evaluateCallback(andj);
  34354. }
  34355. }
  34356. else {
  34357. result = andj === "true" ? true : false;
  34358. }
  34359. if (!result) {
  34360. ori = "false";
  34361. break;
  34362. }
  34363. }
  34364. }
  34365. if (result || ori === "true") {
  34366. result = true;
  34367. break;
  34368. }
  34369. // result equals false (or undefined)
  34370. if (ori !== "true" && ori !== "false") {
  34371. if (ori[0] === "!") {
  34372. result = !evaluateCallback(ori.substring(1));
  34373. }
  34374. else {
  34375. result = evaluateCallback(ori);
  34376. }
  34377. }
  34378. else {
  34379. result = ori === "true" ? true : false;
  34380. }
  34381. }
  34382. }
  34383. // the whole parenthesis scope is replaced by 'true' or 'false'
  34384. return result ? "true" : "false";
  34385. };
  34386. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  34387. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  34388. // remove whitespaces
  34389. r = r.replace(/[\s]/g, function () { return ""; });
  34390. return r.length % 2 ? "!" : "";
  34391. });
  34392. booleanString = booleanString.trim();
  34393. if (booleanString === "!true") {
  34394. booleanString = "false";
  34395. }
  34396. else if (booleanString === "!false") {
  34397. booleanString = "true";
  34398. }
  34399. return booleanString;
  34400. };
  34401. return AndOrNotEvaluator;
  34402. }());
  34403. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  34404. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34405. })(BABYLON || (BABYLON = {}));
  34406. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  34407. var BABYLON;
  34408. (function (BABYLON) {
  34409. var PostProcessRenderPass = (function () {
  34410. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  34411. this._enabled = true;
  34412. this._refCount = 0;
  34413. this._name = name;
  34414. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  34415. this.setRenderList(renderList);
  34416. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  34417. this._renderTexture.onAfterRenderObservable.add(afterRender);
  34418. this._scene = scene;
  34419. this._renderList = renderList;
  34420. }
  34421. // private
  34422. PostProcessRenderPass.prototype._incRefCount = function () {
  34423. if (this._refCount === 0) {
  34424. this._scene.customRenderTargets.push(this._renderTexture);
  34425. }
  34426. return ++this._refCount;
  34427. };
  34428. PostProcessRenderPass.prototype._decRefCount = function () {
  34429. this._refCount--;
  34430. if (this._refCount <= 0) {
  34431. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  34432. }
  34433. return this._refCount;
  34434. };
  34435. PostProcessRenderPass.prototype._update = function () {
  34436. this.setRenderList(this._renderList);
  34437. };
  34438. // public
  34439. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  34440. this._renderTexture.renderList = renderList;
  34441. };
  34442. PostProcessRenderPass.prototype.getRenderTexture = function () {
  34443. return this._renderTexture;
  34444. };
  34445. return PostProcessRenderPass;
  34446. }());
  34447. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  34448. })(BABYLON || (BABYLON = {}));
  34449. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  34450. var BABYLON;
  34451. (function (BABYLON) {
  34452. var PostProcessRenderEffect = (function () {
  34453. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  34454. this._engine = engine;
  34455. this._name = name;
  34456. this._singleInstance = singleInstance || true;
  34457. this._getPostProcess = getPostProcess;
  34458. this._cameras = [];
  34459. this._indicesForCamera = [];
  34460. this._postProcesses = {};
  34461. this._renderPasses = {};
  34462. this._renderEffectAsPasses = {};
  34463. }
  34464. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  34465. get: function () {
  34466. for (var index in this._postProcesses) {
  34467. if (!this._postProcesses[index].isSupported) {
  34468. return false;
  34469. }
  34470. }
  34471. return true;
  34472. },
  34473. enumerable: true,
  34474. configurable: true
  34475. });
  34476. PostProcessRenderEffect.prototype._update = function () {
  34477. for (var renderPassName in this._renderPasses) {
  34478. this._renderPasses[renderPassName]._update();
  34479. }
  34480. };
  34481. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  34482. this._renderPasses[renderPass._name] = renderPass;
  34483. this._linkParameters();
  34484. };
  34485. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  34486. delete this._renderPasses[renderPass._name];
  34487. this._linkParameters();
  34488. };
  34489. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  34490. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  34491. this._linkParameters();
  34492. };
  34493. PostProcessRenderEffect.prototype.getPass = function (passName) {
  34494. for (var renderPassName in this._renderPasses) {
  34495. if (renderPassName === passName) {
  34496. return this._renderPasses[passName];
  34497. }
  34498. }
  34499. };
  34500. PostProcessRenderEffect.prototype.emptyPasses = function () {
  34501. this._renderPasses = {};
  34502. this._linkParameters();
  34503. };
  34504. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  34505. var cameraKey;
  34506. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34507. for (var i = 0; i < _cam.length; i++) {
  34508. var camera = _cam[i];
  34509. var cameraName = camera.name;
  34510. if (this._singleInstance) {
  34511. cameraKey = 0;
  34512. }
  34513. else {
  34514. cameraKey = cameraName;
  34515. }
  34516. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  34517. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  34518. if (!this._indicesForCamera[cameraName]) {
  34519. this._indicesForCamera[cameraName] = [];
  34520. }
  34521. this._indicesForCamera[cameraName].push(index);
  34522. if (this._cameras.indexOf(camera) === -1) {
  34523. this._cameras[cameraName] = camera;
  34524. }
  34525. for (var passName in this._renderPasses) {
  34526. this._renderPasses[passName]._incRefCount();
  34527. }
  34528. }
  34529. this._linkParameters();
  34530. };
  34531. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  34532. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34533. for (var i = 0; i < _cam.length; i++) {
  34534. var camera = _cam[i];
  34535. var cameraName = camera.name;
  34536. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34537. var index = this._cameras.indexOf(cameraName);
  34538. this._indicesForCamera.splice(index, 1);
  34539. this._cameras.splice(index, 1);
  34540. for (var passName in this._renderPasses) {
  34541. this._renderPasses[passName]._decRefCount();
  34542. }
  34543. }
  34544. };
  34545. PostProcessRenderEffect.prototype._enable = function (cameras) {
  34546. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34547. for (var i = 0; i < _cam.length; i++) {
  34548. var camera = _cam[i];
  34549. var cameraName = camera.name;
  34550. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  34551. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  34552. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  34553. }
  34554. }
  34555. for (var passName in this._renderPasses) {
  34556. this._renderPasses[passName]._incRefCount();
  34557. }
  34558. }
  34559. };
  34560. PostProcessRenderEffect.prototype._disable = function (cameras) {
  34561. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34562. for (var i = 0; i < _cam.length; i++) {
  34563. var camera = _cam[i];
  34564. var cameraName = camera.Name;
  34565. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34566. for (var passName in this._renderPasses) {
  34567. this._renderPasses[passName]._decRefCount();
  34568. }
  34569. }
  34570. };
  34571. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  34572. if (this._singleInstance) {
  34573. return this._postProcesses[0];
  34574. }
  34575. else {
  34576. return this._postProcesses[camera.name];
  34577. }
  34578. };
  34579. PostProcessRenderEffect.prototype._linkParameters = function () {
  34580. var _this = this;
  34581. for (var index in this._postProcesses) {
  34582. if (this.applyParameters) {
  34583. this.applyParameters(this._postProcesses[index]);
  34584. }
  34585. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  34586. _this._linkTextures(effect);
  34587. });
  34588. }
  34589. };
  34590. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  34591. for (var renderPassName in this._renderPasses) {
  34592. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  34593. }
  34594. for (var renderEffectName in this._renderEffectAsPasses) {
  34595. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  34596. }
  34597. };
  34598. return PostProcessRenderEffect;
  34599. }());
  34600. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  34601. })(BABYLON || (BABYLON = {}));
  34602. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  34603. var BABYLON;
  34604. (function (BABYLON) {
  34605. var PostProcessRenderPipeline = (function () {
  34606. function PostProcessRenderPipeline(engine, name) {
  34607. this._engine = engine;
  34608. this._name = name;
  34609. this._renderEffects = {};
  34610. this._renderEffectsForIsolatedPass = {};
  34611. this._cameras = [];
  34612. }
  34613. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  34614. get: function () {
  34615. for (var renderEffectName in this._renderEffects) {
  34616. if (!this._renderEffects[renderEffectName].isSupported) {
  34617. return false;
  34618. }
  34619. }
  34620. return true;
  34621. },
  34622. enumerable: true,
  34623. configurable: true
  34624. });
  34625. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  34626. this._renderEffects[renderEffect._name] = renderEffect;
  34627. };
  34628. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  34629. var renderEffects = this._renderEffects[renderEffectName];
  34630. if (!renderEffects) {
  34631. return;
  34632. }
  34633. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34634. };
  34635. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  34636. var renderEffects = this._renderEffects[renderEffectName];
  34637. if (!renderEffects) {
  34638. return;
  34639. }
  34640. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34641. };
  34642. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  34643. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34644. var indicesToDelete = [];
  34645. var i;
  34646. for (i = 0; i < _cam.length; i++) {
  34647. var camera = _cam[i];
  34648. var cameraName = camera.name;
  34649. if (this._cameras.indexOf(camera) === -1) {
  34650. this._cameras[cameraName] = camera;
  34651. }
  34652. else if (unique) {
  34653. indicesToDelete.push(i);
  34654. }
  34655. }
  34656. for (i = 0; i < indicesToDelete.length; i++) {
  34657. cameras.splice(indicesToDelete[i], 1);
  34658. }
  34659. for (var renderEffectName in this._renderEffects) {
  34660. this._renderEffects[renderEffectName]._attachCameras(_cam);
  34661. }
  34662. };
  34663. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  34664. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34665. for (var renderEffectName in this._renderEffects) {
  34666. this._renderEffects[renderEffectName]._detachCameras(_cam);
  34667. }
  34668. for (var i = 0; i < _cam.length; i++) {
  34669. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  34670. }
  34671. };
  34672. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  34673. var _this = this;
  34674. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34675. var pass = null;
  34676. var renderEffectName;
  34677. for (renderEffectName in this._renderEffects) {
  34678. pass = this._renderEffects[renderEffectName].getPass(passName);
  34679. if (pass != null) {
  34680. break;
  34681. }
  34682. }
  34683. if (pass === null) {
  34684. return;
  34685. }
  34686. for (renderEffectName in this._renderEffects) {
  34687. this._renderEffects[renderEffectName]._disable(_cam);
  34688. }
  34689. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  34690. for (var i = 0; i < _cam.length; i++) {
  34691. var camera = _cam[i];
  34692. var cameraName = camera.name;
  34693. 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); });
  34694. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  34695. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  34696. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  34697. }
  34698. };
  34699. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  34700. var _this = this;
  34701. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34702. for (var i = 0; i < _cam.length; i++) {
  34703. var camera = _cam[i];
  34704. var cameraName = camera.name;
  34705. 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); });
  34706. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  34707. }
  34708. for (var renderEffectName in this._renderEffects) {
  34709. this._renderEffects[renderEffectName]._enable(_cam);
  34710. }
  34711. };
  34712. PostProcessRenderPipeline.prototype._update = function () {
  34713. for (var renderEffectName in this._renderEffects) {
  34714. this._renderEffects[renderEffectName]._update();
  34715. }
  34716. for (var i = 0; i < this._cameras.length; i++) {
  34717. var cameraName = this._cameras[i].name;
  34718. if (this._renderEffectsForIsolatedPass[cameraName]) {
  34719. this._renderEffectsForIsolatedPass[cameraName]._update();
  34720. }
  34721. }
  34722. };
  34723. PostProcessRenderPipeline.prototype.dispose = function () {
  34724. // Must be implemented by children
  34725. };
  34726. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  34727. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  34728. return PostProcessRenderPipeline;
  34729. }());
  34730. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  34731. })(BABYLON || (BABYLON = {}));
  34732. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  34733. var BABYLON;
  34734. (function (BABYLON) {
  34735. var PostProcessRenderPipelineManager = (function () {
  34736. function PostProcessRenderPipelineManager() {
  34737. this._renderPipelines = {};
  34738. }
  34739. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  34740. this._renderPipelines[renderPipeline._name] = renderPipeline;
  34741. };
  34742. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  34743. var renderPipeline = this._renderPipelines[renderPipelineName];
  34744. if (!renderPipeline) {
  34745. return;
  34746. }
  34747. renderPipeline._attachCameras(cameras, unique);
  34748. };
  34749. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  34750. var renderPipeline = this._renderPipelines[renderPipelineName];
  34751. if (!renderPipeline) {
  34752. return;
  34753. }
  34754. renderPipeline._detachCameras(cameras);
  34755. };
  34756. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34757. var renderPipeline = this._renderPipelines[renderPipelineName];
  34758. if (!renderPipeline) {
  34759. return;
  34760. }
  34761. renderPipeline._enableEffect(renderEffectName, cameras);
  34762. };
  34763. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34764. var renderPipeline = this._renderPipelines[renderPipelineName];
  34765. if (!renderPipeline) {
  34766. return;
  34767. }
  34768. renderPipeline._disableEffect(renderEffectName, cameras);
  34769. };
  34770. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  34771. var renderPipeline = this._renderPipelines[renderPipelineName];
  34772. if (!renderPipeline) {
  34773. return;
  34774. }
  34775. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  34776. };
  34777. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  34778. var renderPipeline = this._renderPipelines[renderPipelineName];
  34779. if (!renderPipeline) {
  34780. return;
  34781. }
  34782. renderPipeline._disableDisplayOnlyPass(cameras);
  34783. };
  34784. PostProcessRenderPipelineManager.prototype.update = function () {
  34785. for (var renderPipelineName in this._renderPipelines) {
  34786. var pipeline = this._renderPipelines[renderPipelineName];
  34787. if (!pipeline.isSupported) {
  34788. pipeline.dispose();
  34789. delete this._renderPipelines[renderPipelineName];
  34790. }
  34791. else {
  34792. pipeline._update();
  34793. }
  34794. }
  34795. };
  34796. return PostProcessRenderPipelineManager;
  34797. }());
  34798. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  34799. })(BABYLON || (BABYLON = {}));
  34800. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  34801. var BABYLON;
  34802. (function (BABYLON) {
  34803. var BoundingBoxRenderer = (function () {
  34804. function BoundingBoxRenderer(scene) {
  34805. this.frontColor = new BABYLON.Color3(1, 1, 1);
  34806. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  34807. this.showBackLines = true;
  34808. this.renderList = new BABYLON.SmartArray(32);
  34809. this._vertexBuffers = {};
  34810. this._scene = scene;
  34811. }
  34812. BoundingBoxRenderer.prototype._prepareRessources = function () {
  34813. if (this._colorShader) {
  34814. return;
  34815. }
  34816. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  34817. attributes: [BABYLON.VertexBuffer.PositionKind],
  34818. uniforms: ["worldViewProjection", "color"]
  34819. });
  34820. var engine = this._scene.getEngine();
  34821. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  34822. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  34823. 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]);
  34824. };
  34825. BoundingBoxRenderer.prototype.reset = function () {
  34826. this.renderList.reset();
  34827. };
  34828. BoundingBoxRenderer.prototype.render = function () {
  34829. if (this.renderList.length === 0) {
  34830. return;
  34831. }
  34832. this._prepareRessources();
  34833. if (!this._colorShader.isReady()) {
  34834. return;
  34835. }
  34836. var engine = this._scene.getEngine();
  34837. engine.setDepthWrite(false);
  34838. this._colorShader._preBind();
  34839. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34840. var boundingBox = this.renderList.data[boundingBoxIndex];
  34841. var min = boundingBox.minimum;
  34842. var max = boundingBox.maximum;
  34843. var diff = max.subtract(min);
  34844. var median = min.add(diff.scale(0.5));
  34845. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  34846. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  34847. .multiply(boundingBox.getWorldMatrix());
  34848. // VBOs
  34849. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  34850. if (this.showBackLines) {
  34851. // Back
  34852. engine.setDepthFunctionToGreaterOrEqual();
  34853. this._scene.resetCachedMaterial();
  34854. this._colorShader.setColor4("color", this.backColor.toColor4());
  34855. this._colorShader.bind(worldMatrix);
  34856. // Draw order
  34857. engine.draw(false, 0, 24);
  34858. }
  34859. // Front
  34860. engine.setDepthFunctionToLess();
  34861. this._scene.resetCachedMaterial();
  34862. this._colorShader.setColor4("color", this.frontColor.toColor4());
  34863. this._colorShader.bind(worldMatrix);
  34864. // Draw order
  34865. engine.draw(false, 0, 24);
  34866. }
  34867. this._colorShader.unbind();
  34868. engine.setDepthFunctionToLessOrEqual();
  34869. engine.setDepthWrite(true);
  34870. };
  34871. BoundingBoxRenderer.prototype.dispose = function () {
  34872. if (!this._colorShader) {
  34873. return;
  34874. }
  34875. this._colorShader.dispose();
  34876. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34877. if (buffer) {
  34878. buffer.dispose();
  34879. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34880. }
  34881. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34882. };
  34883. return BoundingBoxRenderer;
  34884. }());
  34885. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  34886. })(BABYLON || (BABYLON = {}));
  34887. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  34888. var BABYLON;
  34889. (function (BABYLON) {
  34890. var Condition = (function () {
  34891. function Condition(actionManager) {
  34892. this._actionManager = actionManager;
  34893. }
  34894. Condition.prototype.isValid = function () {
  34895. return true;
  34896. };
  34897. Condition.prototype._getProperty = function (propertyPath) {
  34898. return this._actionManager._getProperty(propertyPath);
  34899. };
  34900. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34901. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34902. };
  34903. Condition.prototype.serialize = function () {
  34904. };
  34905. Condition.prototype._serialize = function (serializedCondition) {
  34906. return {
  34907. type: 2,
  34908. children: [],
  34909. name: serializedCondition.name,
  34910. properties: serializedCondition.properties
  34911. };
  34912. };
  34913. return Condition;
  34914. }());
  34915. BABYLON.Condition = Condition;
  34916. var ValueCondition = (function (_super) {
  34917. __extends(ValueCondition, _super);
  34918. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  34919. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  34920. _super.call(this, actionManager);
  34921. this.propertyPath = propertyPath;
  34922. this.value = value;
  34923. this.operator = operator;
  34924. this._target = target;
  34925. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  34926. this._property = this._getProperty(this.propertyPath);
  34927. }
  34928. Object.defineProperty(ValueCondition, "IsEqual", {
  34929. get: function () {
  34930. return ValueCondition._IsEqual;
  34931. },
  34932. enumerable: true,
  34933. configurable: true
  34934. });
  34935. Object.defineProperty(ValueCondition, "IsDifferent", {
  34936. get: function () {
  34937. return ValueCondition._IsDifferent;
  34938. },
  34939. enumerable: true,
  34940. configurable: true
  34941. });
  34942. Object.defineProperty(ValueCondition, "IsGreater", {
  34943. get: function () {
  34944. return ValueCondition._IsGreater;
  34945. },
  34946. enumerable: true,
  34947. configurable: true
  34948. });
  34949. Object.defineProperty(ValueCondition, "IsLesser", {
  34950. get: function () {
  34951. return ValueCondition._IsLesser;
  34952. },
  34953. enumerable: true,
  34954. configurable: true
  34955. });
  34956. // Methods
  34957. ValueCondition.prototype.isValid = function () {
  34958. switch (this.operator) {
  34959. case ValueCondition.IsGreater:
  34960. return this._effectiveTarget[this._property] > this.value;
  34961. case ValueCondition.IsLesser:
  34962. return this._effectiveTarget[this._property] < this.value;
  34963. case ValueCondition.IsEqual:
  34964. case ValueCondition.IsDifferent:
  34965. var check;
  34966. if (this.value.equals) {
  34967. check = this.value.equals(this._effectiveTarget[this._property]);
  34968. }
  34969. else {
  34970. check = this.value === this._effectiveTarget[this._property];
  34971. }
  34972. return this.operator === ValueCondition.IsEqual ? check : !check;
  34973. }
  34974. return false;
  34975. };
  34976. ValueCondition.prototype.serialize = function () {
  34977. return this._serialize({
  34978. name: "ValueCondition",
  34979. properties: [
  34980. BABYLON.Action._GetTargetProperty(this._target),
  34981. { name: "propertyPath", value: this.propertyPath },
  34982. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34983. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  34984. ]
  34985. });
  34986. };
  34987. ValueCondition.GetOperatorName = function (operator) {
  34988. switch (operator) {
  34989. case ValueCondition._IsEqual: return "IsEqual";
  34990. case ValueCondition._IsDifferent: return "IsDifferent";
  34991. case ValueCondition._IsGreater: return "IsGreater";
  34992. case ValueCondition._IsLesser: return "IsLesser";
  34993. default: return "";
  34994. }
  34995. };
  34996. // Statics
  34997. ValueCondition._IsEqual = 0;
  34998. ValueCondition._IsDifferent = 1;
  34999. ValueCondition._IsGreater = 2;
  35000. ValueCondition._IsLesser = 3;
  35001. return ValueCondition;
  35002. }(Condition));
  35003. BABYLON.ValueCondition = ValueCondition;
  35004. var PredicateCondition = (function (_super) {
  35005. __extends(PredicateCondition, _super);
  35006. function PredicateCondition(actionManager, predicate) {
  35007. _super.call(this, actionManager);
  35008. this.predicate = predicate;
  35009. }
  35010. PredicateCondition.prototype.isValid = function () {
  35011. return this.predicate();
  35012. };
  35013. return PredicateCondition;
  35014. }(Condition));
  35015. BABYLON.PredicateCondition = PredicateCondition;
  35016. var StateCondition = (function (_super) {
  35017. __extends(StateCondition, _super);
  35018. function StateCondition(actionManager, target, value) {
  35019. _super.call(this, actionManager);
  35020. this.value = value;
  35021. this._target = target;
  35022. }
  35023. // Methods
  35024. StateCondition.prototype.isValid = function () {
  35025. return this._target.state === this.value;
  35026. };
  35027. StateCondition.prototype.serialize = function () {
  35028. return this._serialize({
  35029. name: "StateCondition",
  35030. properties: [
  35031. BABYLON.Action._GetTargetProperty(this._target),
  35032. { name: "value", value: this.value }
  35033. ]
  35034. });
  35035. };
  35036. return StateCondition;
  35037. }(Condition));
  35038. BABYLON.StateCondition = StateCondition;
  35039. })(BABYLON || (BABYLON = {}));
  35040. //# sourceMappingURL=babylon.condition.js.map
  35041. var BABYLON;
  35042. (function (BABYLON) {
  35043. var Action = (function () {
  35044. function Action(triggerOptions, condition) {
  35045. this.triggerOptions = triggerOptions;
  35046. if (triggerOptions.parameter) {
  35047. this.trigger = triggerOptions.trigger;
  35048. this._triggerParameter = triggerOptions.parameter;
  35049. }
  35050. else {
  35051. this.trigger = triggerOptions;
  35052. }
  35053. this._nextActiveAction = this;
  35054. this._condition = condition;
  35055. }
  35056. // Methods
  35057. Action.prototype._prepare = function () {
  35058. };
  35059. Action.prototype.getTriggerParameter = function () {
  35060. return this._triggerParameter;
  35061. };
  35062. Action.prototype._executeCurrent = function (evt) {
  35063. if (this._nextActiveAction._condition) {
  35064. var condition = this._nextActiveAction._condition;
  35065. var currentRenderId = this._actionManager.getScene().getRenderId();
  35066. // We cache the current evaluation for the current frame
  35067. if (condition._evaluationId === currentRenderId) {
  35068. if (!condition._currentResult) {
  35069. return;
  35070. }
  35071. }
  35072. else {
  35073. condition._evaluationId = currentRenderId;
  35074. if (!condition.isValid()) {
  35075. condition._currentResult = false;
  35076. return;
  35077. }
  35078. condition._currentResult = true;
  35079. }
  35080. }
  35081. this._nextActiveAction.execute(evt);
  35082. this.skipToNextActiveAction();
  35083. };
  35084. Action.prototype.execute = function (evt) {
  35085. };
  35086. Action.prototype.skipToNextActiveAction = function () {
  35087. if (this._nextActiveAction._child) {
  35088. if (!this._nextActiveAction._child._actionManager) {
  35089. this._nextActiveAction._child._actionManager = this._actionManager;
  35090. }
  35091. this._nextActiveAction = this._nextActiveAction._child;
  35092. }
  35093. else {
  35094. this._nextActiveAction = this;
  35095. }
  35096. };
  35097. Action.prototype.then = function (action) {
  35098. this._child = action;
  35099. action._actionManager = this._actionManager;
  35100. action._prepare();
  35101. return action;
  35102. };
  35103. Action.prototype._getProperty = function (propertyPath) {
  35104. return this._actionManager._getProperty(propertyPath);
  35105. };
  35106. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35107. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35108. };
  35109. Action.prototype.serialize = function (parent) {
  35110. };
  35111. // Called by BABYLON.Action objects in serialize(...). Internal use
  35112. Action.prototype._serialize = function (serializedAction, parent) {
  35113. var serializationObject = {
  35114. type: 1,
  35115. children: [],
  35116. name: serializedAction.name,
  35117. properties: serializedAction.properties || []
  35118. };
  35119. // Serialize child
  35120. if (this._child) {
  35121. this._child.serialize(serializationObject);
  35122. }
  35123. // Check if "this" has a condition
  35124. if (this._condition) {
  35125. var serializedCondition = this._condition.serialize();
  35126. serializedCondition.children.push(serializationObject);
  35127. if (parent) {
  35128. parent.children.push(serializedCondition);
  35129. }
  35130. return serializedCondition;
  35131. }
  35132. if (parent) {
  35133. parent.children.push(serializationObject);
  35134. }
  35135. return serializationObject;
  35136. };
  35137. Action._SerializeValueAsString = function (value) {
  35138. if (typeof value === "number") {
  35139. return value.toString();
  35140. }
  35141. if (typeof value === "boolean") {
  35142. return value ? "true" : "false";
  35143. }
  35144. if (value instanceof BABYLON.Vector2) {
  35145. return value.x + ", " + value.y;
  35146. }
  35147. if (value instanceof BABYLON.Vector3) {
  35148. return value.x + ", " + value.y + ", " + value.z;
  35149. }
  35150. if (value instanceof BABYLON.Color3) {
  35151. return value.r + ", " + value.g + ", " + value.b;
  35152. }
  35153. if (value instanceof BABYLON.Color4) {
  35154. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35155. }
  35156. return value; // string
  35157. };
  35158. Action._GetTargetProperty = function (target) {
  35159. return {
  35160. name: "target",
  35161. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35162. : target instanceof BABYLON.Light ? "LightProperties"
  35163. : target instanceof BABYLON.Camera ? "CameraProperties"
  35164. : "SceneProperties",
  35165. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35166. };
  35167. };
  35168. return Action;
  35169. }());
  35170. BABYLON.Action = Action;
  35171. })(BABYLON || (BABYLON = {}));
  35172. //# sourceMappingURL=babylon.action.js.map
  35173. var BABYLON;
  35174. (function (BABYLON) {
  35175. /**
  35176. * ActionEvent is the event beint sent when an action is triggered.
  35177. */
  35178. var ActionEvent = (function () {
  35179. /**
  35180. * @constructor
  35181. * @param source The mesh or sprite that triggered the action.
  35182. * @param pointerX The X mouse cursor position at the time of the event
  35183. * @param pointerY The Y mouse cursor position at the time of the event
  35184. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35185. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35186. */
  35187. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35188. this.source = source;
  35189. this.pointerX = pointerX;
  35190. this.pointerY = pointerY;
  35191. this.meshUnderPointer = meshUnderPointer;
  35192. this.sourceEvent = sourceEvent;
  35193. this.additionalData = additionalData;
  35194. }
  35195. /**
  35196. * Helper function to auto-create an ActionEvent from a source mesh.
  35197. * @param source The source mesh that triggered the event
  35198. * @param evt {Event} The original (browser) event
  35199. */
  35200. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35201. var scene = source.getScene();
  35202. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35203. };
  35204. /**
  35205. * Helper function to auto-create an ActionEvent from a source mesh.
  35206. * @param source The source sprite that triggered the event
  35207. * @param scene Scene associated with the sprite
  35208. * @param evt {Event} The original (browser) event
  35209. */
  35210. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35211. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35212. };
  35213. /**
  35214. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35215. * @param scene the scene where the event occurred
  35216. * @param evt {Event} The original (browser) event
  35217. */
  35218. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35219. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35220. };
  35221. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35222. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35223. };
  35224. return ActionEvent;
  35225. }());
  35226. BABYLON.ActionEvent = ActionEvent;
  35227. /**
  35228. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35229. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35230. */
  35231. var ActionManager = (function () {
  35232. function ActionManager(scene) {
  35233. // Members
  35234. this.actions = new Array();
  35235. this.hoverCursor = '';
  35236. this._scene = scene;
  35237. scene._actionManagers.push(this);
  35238. }
  35239. Object.defineProperty(ActionManager, "NothingTrigger", {
  35240. get: function () {
  35241. return ActionManager._NothingTrigger;
  35242. },
  35243. enumerable: true,
  35244. configurable: true
  35245. });
  35246. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35247. get: function () {
  35248. return ActionManager._OnPickTrigger;
  35249. },
  35250. enumerable: true,
  35251. configurable: true
  35252. });
  35253. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35254. get: function () {
  35255. return ActionManager._OnLeftPickTrigger;
  35256. },
  35257. enumerable: true,
  35258. configurable: true
  35259. });
  35260. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35261. get: function () {
  35262. return ActionManager._OnRightPickTrigger;
  35263. },
  35264. enumerable: true,
  35265. configurable: true
  35266. });
  35267. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35268. get: function () {
  35269. return ActionManager._OnCenterPickTrigger;
  35270. },
  35271. enumerable: true,
  35272. configurable: true
  35273. });
  35274. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35275. get: function () {
  35276. return ActionManager._OnPickDownTrigger;
  35277. },
  35278. enumerable: true,
  35279. configurable: true
  35280. });
  35281. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35282. get: function () {
  35283. return ActionManager._OnPickUpTrigger;
  35284. },
  35285. enumerable: true,
  35286. configurable: true
  35287. });
  35288. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35289. /// This trigger will only be raised if you also declared a OnPickDown
  35290. get: function () {
  35291. return ActionManager._OnPickOutTrigger;
  35292. },
  35293. enumerable: true,
  35294. configurable: true
  35295. });
  35296. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35297. get: function () {
  35298. return ActionManager._OnLongPressTrigger;
  35299. },
  35300. enumerable: true,
  35301. configurable: true
  35302. });
  35303. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35304. get: function () {
  35305. return ActionManager._OnPointerOverTrigger;
  35306. },
  35307. enumerable: true,
  35308. configurable: true
  35309. });
  35310. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35311. get: function () {
  35312. return ActionManager._OnPointerOutTrigger;
  35313. },
  35314. enumerable: true,
  35315. configurable: true
  35316. });
  35317. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35318. get: function () {
  35319. return ActionManager._OnEveryFrameTrigger;
  35320. },
  35321. enumerable: true,
  35322. configurable: true
  35323. });
  35324. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35325. get: function () {
  35326. return ActionManager._OnIntersectionEnterTrigger;
  35327. },
  35328. enumerable: true,
  35329. configurable: true
  35330. });
  35331. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35332. get: function () {
  35333. return ActionManager._OnIntersectionExitTrigger;
  35334. },
  35335. enumerable: true,
  35336. configurable: true
  35337. });
  35338. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35339. get: function () {
  35340. return ActionManager._OnKeyDownTrigger;
  35341. },
  35342. enumerable: true,
  35343. configurable: true
  35344. });
  35345. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35346. get: function () {
  35347. return ActionManager._OnKeyUpTrigger;
  35348. },
  35349. enumerable: true,
  35350. configurable: true
  35351. });
  35352. // Methods
  35353. ActionManager.prototype.dispose = function () {
  35354. var index = this._scene._actionManagers.indexOf(this);
  35355. if (index > -1) {
  35356. this._scene._actionManagers.splice(index, 1);
  35357. }
  35358. };
  35359. ActionManager.prototype.getScene = function () {
  35360. return this._scene;
  35361. };
  35362. /**
  35363. * Does this action manager handles actions of any of the given triggers
  35364. * @param {number[]} triggers - the triggers to be tested
  35365. * @return {boolean} whether one (or more) of the triggers is handeled
  35366. */
  35367. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35368. for (var index = 0; index < this.actions.length; index++) {
  35369. var action = this.actions[index];
  35370. if (triggers.indexOf(action.trigger) > -1) {
  35371. return true;
  35372. }
  35373. }
  35374. return false;
  35375. };
  35376. /**
  35377. * Does this action manager handles actions of a given trigger
  35378. * @param {number} trigger - the trigger to be tested
  35379. * @return {boolean} whether the trigger is handeled
  35380. */
  35381. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35382. for (var index = 0; index < this.actions.length; index++) {
  35383. var action = this.actions[index];
  35384. if (action.trigger === trigger) {
  35385. return true;
  35386. }
  35387. }
  35388. return false;
  35389. };
  35390. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35391. /**
  35392. * Does this action manager has pointer triggers
  35393. * @return {boolean} whether or not it has pointer triggers
  35394. */
  35395. get: function () {
  35396. for (var index = 0; index < this.actions.length; index++) {
  35397. var action = this.actions[index];
  35398. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35399. return true;
  35400. }
  35401. }
  35402. return false;
  35403. },
  35404. enumerable: true,
  35405. configurable: true
  35406. });
  35407. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35408. /**
  35409. * Does this action manager has pick triggers
  35410. * @return {boolean} whether or not it has pick triggers
  35411. */
  35412. get: function () {
  35413. for (var index = 0; index < this.actions.length; index++) {
  35414. var action = this.actions[index];
  35415. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35416. return true;
  35417. }
  35418. }
  35419. return false;
  35420. },
  35421. enumerable: true,
  35422. configurable: true
  35423. });
  35424. /**
  35425. * Registers an action to this action manager
  35426. * @param {BABYLON.Action} action - the action to be registered
  35427. * @return {BABYLON.Action} the action amended (prepared) after registration
  35428. */
  35429. ActionManager.prototype.registerAction = function (action) {
  35430. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35431. if (this.getScene().actionManager !== this) {
  35432. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35433. return null;
  35434. }
  35435. }
  35436. this.actions.push(action);
  35437. action._actionManager = this;
  35438. action._prepare();
  35439. return action;
  35440. };
  35441. /**
  35442. * Process a specific trigger
  35443. * @param {number} trigger - the trigger to process
  35444. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35445. */
  35446. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35447. for (var index = 0; index < this.actions.length; index++) {
  35448. var action = this.actions[index];
  35449. if (action.trigger === trigger) {
  35450. if (trigger === ActionManager.OnKeyUpTrigger
  35451. || trigger === ActionManager.OnKeyDownTrigger) {
  35452. var parameter = action.getTriggerParameter();
  35453. if (parameter) {
  35454. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35455. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35456. if (actualkey !== parameter.toLowerCase()) {
  35457. continue;
  35458. }
  35459. }
  35460. }
  35461. action._executeCurrent(evt);
  35462. }
  35463. }
  35464. };
  35465. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35466. var properties = propertyPath.split(".");
  35467. for (var index = 0; index < properties.length - 1; index++) {
  35468. target = target[properties[index]];
  35469. }
  35470. return target;
  35471. };
  35472. ActionManager.prototype._getProperty = function (propertyPath) {
  35473. var properties = propertyPath.split(".");
  35474. return properties[properties.length - 1];
  35475. };
  35476. ActionManager.prototype.serialize = function (name) {
  35477. var root = {
  35478. children: [],
  35479. name: name,
  35480. type: 3,
  35481. properties: [] // Empty for root but required
  35482. };
  35483. for (var i = 0; i < this.actions.length; i++) {
  35484. var triggerObject = {
  35485. type: 0,
  35486. children: [],
  35487. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35488. properties: []
  35489. };
  35490. var triggerOptions = this.actions[i].triggerOptions;
  35491. if (triggerOptions && typeof triggerOptions !== "number") {
  35492. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35493. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35494. }
  35495. else {
  35496. var parameter = {};
  35497. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35498. if (triggerOptions.parameter.mesh) {
  35499. parameter._meshId = triggerOptions.parameter.mesh.id;
  35500. }
  35501. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35502. }
  35503. }
  35504. // Serialize child action, recursively
  35505. this.actions[i].serialize(triggerObject);
  35506. // Add serialized trigger
  35507. root.children.push(triggerObject);
  35508. }
  35509. return root;
  35510. };
  35511. ActionManager.Parse = function (parsedActions, object, scene) {
  35512. var actionManager = new BABYLON.ActionManager(scene);
  35513. if (object === null)
  35514. scene.actionManager = actionManager;
  35515. else
  35516. object.actionManager = actionManager;
  35517. // instanciate a new object
  35518. var instanciate = function (name, params) {
  35519. var newInstance = Object.create(BABYLON[name].prototype);
  35520. newInstance.constructor.apply(newInstance, params);
  35521. return newInstance;
  35522. };
  35523. var parseParameter = function (name, value, target, propertyPath) {
  35524. if (propertyPath === null) {
  35525. // String, boolean or float
  35526. var floatValue = parseFloat(value);
  35527. if (value === "true" || value === "false")
  35528. return value === "true";
  35529. else
  35530. return isNaN(floatValue) ? value : floatValue;
  35531. }
  35532. var effectiveTarget = propertyPath.split(".");
  35533. var values = value.split(",");
  35534. // Get effective Target
  35535. for (var i = 0; i < effectiveTarget.length; i++) {
  35536. target = target[effectiveTarget[i]];
  35537. }
  35538. // Return appropriate value with its type
  35539. if (typeof (target) === "boolean")
  35540. return values[0] === "true";
  35541. if (typeof (target) === "string")
  35542. return values[0];
  35543. // Parameters with multiple values such as Vector3 etc.
  35544. var split = new Array();
  35545. for (var i = 0; i < values.length; i++)
  35546. split.push(parseFloat(values[i]));
  35547. if (target instanceof BABYLON.Vector3)
  35548. return BABYLON.Vector3.FromArray(split);
  35549. if (target instanceof BABYLON.Vector4)
  35550. return BABYLON.Vector4.FromArray(split);
  35551. if (target instanceof BABYLON.Color3)
  35552. return BABYLON.Color3.FromArray(split);
  35553. if (target instanceof BABYLON.Color4)
  35554. return BABYLON.Color4.FromArray(split);
  35555. return parseFloat(values[0]);
  35556. };
  35557. // traverse graph per trigger
  35558. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35559. if (combineArray === void 0) { combineArray = null; }
  35560. if (parsedAction.detached)
  35561. return;
  35562. var parameters = new Array();
  35563. var target = null;
  35564. var propertyPath = null;
  35565. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35566. // Parameters
  35567. if (parsedAction.type === 2)
  35568. parameters.push(actionManager);
  35569. else
  35570. parameters.push(trigger);
  35571. if (combine) {
  35572. var actions = new Array();
  35573. for (var j = 0; j < parsedAction.combine.length; j++) {
  35574. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35575. }
  35576. parameters.push(actions);
  35577. }
  35578. else {
  35579. for (var i = 0; i < parsedAction.properties.length; i++) {
  35580. var value = parsedAction.properties[i].value;
  35581. var name = parsedAction.properties[i].name;
  35582. var targetType = parsedAction.properties[i].targetType;
  35583. if (name === "target")
  35584. if (targetType !== null && targetType === "SceneProperties")
  35585. value = target = scene;
  35586. else
  35587. value = target = scene.getNodeByName(value);
  35588. else if (name === "parent")
  35589. value = scene.getNodeByName(value);
  35590. else if (name === "sound")
  35591. value = scene.getSoundByName(value);
  35592. else if (name !== "propertyPath") {
  35593. if (parsedAction.type === 2 && name === "operator")
  35594. value = BABYLON.ValueCondition[value];
  35595. else
  35596. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35597. }
  35598. else {
  35599. propertyPath = value;
  35600. }
  35601. parameters.push(value);
  35602. }
  35603. }
  35604. if (combineArray === null) {
  35605. parameters.push(condition);
  35606. }
  35607. else {
  35608. parameters.push(null);
  35609. }
  35610. // If interpolate value action
  35611. if (parsedAction.name === "InterpolateValueAction") {
  35612. var param = parameters[parameters.length - 2];
  35613. parameters[parameters.length - 1] = param;
  35614. parameters[parameters.length - 2] = condition;
  35615. }
  35616. // Action or condition(s) and not CombineAction
  35617. var newAction = instanciate(parsedAction.name, parameters);
  35618. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35619. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35620. if (action)
  35621. action.then(nothing);
  35622. else
  35623. actionManager.registerAction(nothing);
  35624. action = nothing;
  35625. }
  35626. if (combineArray === null) {
  35627. if (newAction instanceof BABYLON.Condition) {
  35628. condition = newAction;
  35629. newAction = action;
  35630. }
  35631. else {
  35632. condition = null;
  35633. if (action)
  35634. action.then(newAction);
  35635. else
  35636. actionManager.registerAction(newAction);
  35637. }
  35638. }
  35639. else {
  35640. combineArray.push(newAction);
  35641. }
  35642. for (var i = 0; i < parsedAction.children.length; i++)
  35643. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35644. };
  35645. // triggers
  35646. for (var i = 0; i < parsedActions.children.length; i++) {
  35647. var triggerParams;
  35648. var trigger = parsedActions.children[i];
  35649. if (trigger.properties.length > 0) {
  35650. var param = trigger.properties[0].value;
  35651. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35652. if (value._meshId) {
  35653. value.mesh = scene.getMeshByID(value._meshId);
  35654. }
  35655. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35656. }
  35657. else
  35658. triggerParams = BABYLON.ActionManager[trigger.name];
  35659. for (var j = 0; j < trigger.children.length; j++) {
  35660. if (!trigger.detached)
  35661. traverse(trigger.children[j], triggerParams, null, null);
  35662. }
  35663. }
  35664. };
  35665. ActionManager.GetTriggerName = function (trigger) {
  35666. switch (trigger) {
  35667. case 0: return "NothingTrigger";
  35668. case 1: return "OnPickTrigger";
  35669. case 2: return "OnLeftPickTrigger";
  35670. case 3: return "OnRightPickTrigger";
  35671. case 4: return "OnCenterPickTrigger";
  35672. case 5: return "OnPickDownTrigger";
  35673. case 6: return "OnPickUpTrigger";
  35674. case 7: return "OnLongPressTrigger";
  35675. case 8: return "OnPointerOverTrigger";
  35676. case 9: return "OnPointerOutTrigger";
  35677. case 10: return "OnEveryFrameTrigger";
  35678. case 11: return "OnIntersectionEnterTrigger";
  35679. case 12: return "OnIntersectionExitTrigger";
  35680. case 13: return "OnKeyDownTrigger";
  35681. case 14: return "OnKeyUpTrigger";
  35682. case 15: return "OnPickOutTrigger";
  35683. default: return "";
  35684. }
  35685. };
  35686. // Statics
  35687. ActionManager._NothingTrigger = 0;
  35688. ActionManager._OnPickTrigger = 1;
  35689. ActionManager._OnLeftPickTrigger = 2;
  35690. ActionManager._OnRightPickTrigger = 3;
  35691. ActionManager._OnCenterPickTrigger = 4;
  35692. ActionManager._OnPickDownTrigger = 5;
  35693. ActionManager._OnPickUpTrigger = 6;
  35694. ActionManager._OnLongPressTrigger = 7;
  35695. ActionManager._OnPointerOverTrigger = 8;
  35696. ActionManager._OnPointerOutTrigger = 9;
  35697. ActionManager._OnEveryFrameTrigger = 10;
  35698. ActionManager._OnIntersectionEnterTrigger = 11;
  35699. ActionManager._OnIntersectionExitTrigger = 12;
  35700. ActionManager._OnKeyDownTrigger = 13;
  35701. ActionManager._OnKeyUpTrigger = 14;
  35702. ActionManager._OnPickOutTrigger = 15;
  35703. ActionManager.DragMovementThreshold = 10; // in pixels
  35704. ActionManager.LongPressDelay = 500; // in milliseconds
  35705. return ActionManager;
  35706. }());
  35707. BABYLON.ActionManager = ActionManager;
  35708. })(BABYLON || (BABYLON = {}));
  35709. //# sourceMappingURL=babylon.actionManager.js.map
  35710. var BABYLON;
  35711. (function (BABYLON) {
  35712. var InterpolateValueAction = (function (_super) {
  35713. __extends(InterpolateValueAction, _super);
  35714. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35715. if (duration === void 0) { duration = 1000; }
  35716. _super.call(this, triggerOptions, condition);
  35717. this.propertyPath = propertyPath;
  35718. this.value = value;
  35719. this.duration = duration;
  35720. this.stopOtherAnimations = stopOtherAnimations;
  35721. this.onInterpolationDone = onInterpolationDone;
  35722. this._target = this._effectiveTarget = target;
  35723. }
  35724. InterpolateValueAction.prototype._prepare = function () {
  35725. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35726. this._property = this._getProperty(this.propertyPath);
  35727. };
  35728. InterpolateValueAction.prototype.execute = function () {
  35729. var scene = this._actionManager.getScene();
  35730. var keys = [
  35731. {
  35732. frame: 0,
  35733. value: this._effectiveTarget[this._property]
  35734. }, {
  35735. frame: 100,
  35736. value: this.value
  35737. }
  35738. ];
  35739. var dataType;
  35740. if (typeof this.value === "number") {
  35741. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35742. }
  35743. else if (this.value instanceof BABYLON.Color3) {
  35744. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35745. }
  35746. else if (this.value instanceof BABYLON.Vector3) {
  35747. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35748. }
  35749. else if (this.value instanceof BABYLON.Matrix) {
  35750. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35751. }
  35752. else if (this.value instanceof BABYLON.Quaternion) {
  35753. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35754. }
  35755. else {
  35756. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35757. return;
  35758. }
  35759. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35760. animation.setKeys(keys);
  35761. if (this.stopOtherAnimations) {
  35762. scene.stopAnimation(this._effectiveTarget);
  35763. }
  35764. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35765. };
  35766. InterpolateValueAction.prototype.serialize = function (parent) {
  35767. return _super.prototype._serialize.call(this, {
  35768. name: "InterpolateValueAction",
  35769. properties: [
  35770. BABYLON.Action._GetTargetProperty(this._target),
  35771. { name: "propertyPath", value: this.propertyPath },
  35772. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35773. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35774. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35775. ]
  35776. }, parent);
  35777. };
  35778. return InterpolateValueAction;
  35779. }(BABYLON.Action));
  35780. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35781. })(BABYLON || (BABYLON = {}));
  35782. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  35783. var BABYLON;
  35784. (function (BABYLON) {
  35785. var SwitchBooleanAction = (function (_super) {
  35786. __extends(SwitchBooleanAction, _super);
  35787. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35788. _super.call(this, triggerOptions, condition);
  35789. this.propertyPath = propertyPath;
  35790. this._target = this._effectiveTarget = target;
  35791. }
  35792. SwitchBooleanAction.prototype._prepare = function () {
  35793. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35794. this._property = this._getProperty(this.propertyPath);
  35795. };
  35796. SwitchBooleanAction.prototype.execute = function () {
  35797. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35798. };
  35799. SwitchBooleanAction.prototype.serialize = function (parent) {
  35800. return _super.prototype._serialize.call(this, {
  35801. name: "SwitchBooleanAction",
  35802. properties: [
  35803. BABYLON.Action._GetTargetProperty(this._target),
  35804. { name: "propertyPath", value: this.propertyPath }
  35805. ]
  35806. }, parent);
  35807. };
  35808. return SwitchBooleanAction;
  35809. }(BABYLON.Action));
  35810. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35811. var SetStateAction = (function (_super) {
  35812. __extends(SetStateAction, _super);
  35813. function SetStateAction(triggerOptions, target, value, condition) {
  35814. _super.call(this, triggerOptions, condition);
  35815. this.value = value;
  35816. this._target = target;
  35817. }
  35818. SetStateAction.prototype.execute = function () {
  35819. this._target.state = this.value;
  35820. };
  35821. SetStateAction.prototype.serialize = function (parent) {
  35822. return _super.prototype._serialize.call(this, {
  35823. name: "SetStateAction",
  35824. properties: [
  35825. BABYLON.Action._GetTargetProperty(this._target),
  35826. { name: "value", value: this.value }
  35827. ]
  35828. }, parent);
  35829. };
  35830. return SetStateAction;
  35831. }(BABYLON.Action));
  35832. BABYLON.SetStateAction = SetStateAction;
  35833. var SetValueAction = (function (_super) {
  35834. __extends(SetValueAction, _super);
  35835. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35836. _super.call(this, triggerOptions, condition);
  35837. this.propertyPath = propertyPath;
  35838. this.value = value;
  35839. this._target = this._effectiveTarget = target;
  35840. }
  35841. SetValueAction.prototype._prepare = function () {
  35842. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35843. this._property = this._getProperty(this.propertyPath);
  35844. };
  35845. SetValueAction.prototype.execute = function () {
  35846. this._effectiveTarget[this._property] = this.value;
  35847. if (this._target.markAsDirty) {
  35848. this._target.markAsDirty(this._property);
  35849. }
  35850. };
  35851. SetValueAction.prototype.serialize = function (parent) {
  35852. return _super.prototype._serialize.call(this, {
  35853. name: "SetValueAction",
  35854. properties: [
  35855. BABYLON.Action._GetTargetProperty(this._target),
  35856. { name: "propertyPath", value: this.propertyPath },
  35857. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35858. ]
  35859. }, parent);
  35860. };
  35861. return SetValueAction;
  35862. }(BABYLON.Action));
  35863. BABYLON.SetValueAction = SetValueAction;
  35864. var IncrementValueAction = (function (_super) {
  35865. __extends(IncrementValueAction, _super);
  35866. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  35867. _super.call(this, triggerOptions, condition);
  35868. this.propertyPath = propertyPath;
  35869. this.value = value;
  35870. this._target = this._effectiveTarget = target;
  35871. }
  35872. IncrementValueAction.prototype._prepare = function () {
  35873. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35874. this._property = this._getProperty(this.propertyPath);
  35875. if (typeof this._effectiveTarget[this._property] !== "number") {
  35876. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  35877. }
  35878. };
  35879. IncrementValueAction.prototype.execute = function () {
  35880. this._effectiveTarget[this._property] += this.value;
  35881. if (this._target.markAsDirty) {
  35882. this._target.markAsDirty(this._property);
  35883. }
  35884. };
  35885. IncrementValueAction.prototype.serialize = function (parent) {
  35886. return _super.prototype._serialize.call(this, {
  35887. name: "IncrementValueAction",
  35888. properties: [
  35889. BABYLON.Action._GetTargetProperty(this._target),
  35890. { name: "propertyPath", value: this.propertyPath },
  35891. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35892. ]
  35893. }, parent);
  35894. };
  35895. return IncrementValueAction;
  35896. }(BABYLON.Action));
  35897. BABYLON.IncrementValueAction = IncrementValueAction;
  35898. var PlayAnimationAction = (function (_super) {
  35899. __extends(PlayAnimationAction, _super);
  35900. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  35901. _super.call(this, triggerOptions, condition);
  35902. this.from = from;
  35903. this.to = to;
  35904. this.loop = loop;
  35905. this._target = target;
  35906. }
  35907. PlayAnimationAction.prototype._prepare = function () {
  35908. };
  35909. PlayAnimationAction.prototype.execute = function () {
  35910. var scene = this._actionManager.getScene();
  35911. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  35912. };
  35913. PlayAnimationAction.prototype.serialize = function (parent) {
  35914. return _super.prototype._serialize.call(this, {
  35915. name: "PlayAnimationAction",
  35916. properties: [
  35917. BABYLON.Action._GetTargetProperty(this._target),
  35918. { name: "from", value: String(this.from) },
  35919. { name: "to", value: String(this.to) },
  35920. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  35921. ]
  35922. }, parent);
  35923. };
  35924. return PlayAnimationAction;
  35925. }(BABYLON.Action));
  35926. BABYLON.PlayAnimationAction = PlayAnimationAction;
  35927. var StopAnimationAction = (function (_super) {
  35928. __extends(StopAnimationAction, _super);
  35929. function StopAnimationAction(triggerOptions, target, condition) {
  35930. _super.call(this, triggerOptions, condition);
  35931. this._target = target;
  35932. }
  35933. StopAnimationAction.prototype._prepare = function () {
  35934. };
  35935. StopAnimationAction.prototype.execute = function () {
  35936. var scene = this._actionManager.getScene();
  35937. scene.stopAnimation(this._target);
  35938. };
  35939. StopAnimationAction.prototype.serialize = function (parent) {
  35940. return _super.prototype._serialize.call(this, {
  35941. name: "StopAnimationAction",
  35942. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  35943. }, parent);
  35944. };
  35945. return StopAnimationAction;
  35946. }(BABYLON.Action));
  35947. BABYLON.StopAnimationAction = StopAnimationAction;
  35948. var DoNothingAction = (function (_super) {
  35949. __extends(DoNothingAction, _super);
  35950. function DoNothingAction(triggerOptions, condition) {
  35951. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  35952. _super.call(this, triggerOptions, condition);
  35953. }
  35954. DoNothingAction.prototype.execute = function () {
  35955. };
  35956. DoNothingAction.prototype.serialize = function (parent) {
  35957. return _super.prototype._serialize.call(this, {
  35958. name: "DoNothingAction",
  35959. properties: []
  35960. }, parent);
  35961. };
  35962. return DoNothingAction;
  35963. }(BABYLON.Action));
  35964. BABYLON.DoNothingAction = DoNothingAction;
  35965. var CombineAction = (function (_super) {
  35966. __extends(CombineAction, _super);
  35967. function CombineAction(triggerOptions, children, condition) {
  35968. _super.call(this, triggerOptions, condition);
  35969. this.children = children;
  35970. }
  35971. CombineAction.prototype._prepare = function () {
  35972. for (var index = 0; index < this.children.length; index++) {
  35973. this.children[index]._actionManager = this._actionManager;
  35974. this.children[index]._prepare();
  35975. }
  35976. };
  35977. CombineAction.prototype.execute = function (evt) {
  35978. for (var index = 0; index < this.children.length; index++) {
  35979. this.children[index].execute(evt);
  35980. }
  35981. };
  35982. CombineAction.prototype.serialize = function (parent) {
  35983. var serializationObject = _super.prototype._serialize.call(this, {
  35984. name: "CombineAction",
  35985. properties: [],
  35986. combine: []
  35987. }, parent);
  35988. for (var i = 0; i < this.children.length; i++) {
  35989. serializationObject.combine.push(this.children[i].serialize(null));
  35990. }
  35991. return serializationObject;
  35992. };
  35993. return CombineAction;
  35994. }(BABYLON.Action));
  35995. BABYLON.CombineAction = CombineAction;
  35996. var ExecuteCodeAction = (function (_super) {
  35997. __extends(ExecuteCodeAction, _super);
  35998. function ExecuteCodeAction(triggerOptions, func, condition) {
  35999. _super.call(this, triggerOptions, condition);
  36000. this.func = func;
  36001. }
  36002. ExecuteCodeAction.prototype.execute = function (evt) {
  36003. this.func(evt);
  36004. };
  36005. return ExecuteCodeAction;
  36006. }(BABYLON.Action));
  36007. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36008. var SetParentAction = (function (_super) {
  36009. __extends(SetParentAction, _super);
  36010. function SetParentAction(triggerOptions, target, parent, condition) {
  36011. _super.call(this, triggerOptions, condition);
  36012. this._target = target;
  36013. this._parent = parent;
  36014. }
  36015. SetParentAction.prototype._prepare = function () {
  36016. };
  36017. SetParentAction.prototype.execute = function () {
  36018. if (this._target.parent === this._parent) {
  36019. return;
  36020. }
  36021. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36022. invertParentWorldMatrix.invert();
  36023. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36024. this._target.parent = this._parent;
  36025. };
  36026. SetParentAction.prototype.serialize = function (parent) {
  36027. return _super.prototype._serialize.call(this, {
  36028. name: "SetParentAction",
  36029. properties: [
  36030. BABYLON.Action._GetTargetProperty(this._target),
  36031. BABYLON.Action._GetTargetProperty(this._parent),
  36032. ]
  36033. }, parent);
  36034. };
  36035. return SetParentAction;
  36036. }(BABYLON.Action));
  36037. BABYLON.SetParentAction = SetParentAction;
  36038. var PlaySoundAction = (function (_super) {
  36039. __extends(PlaySoundAction, _super);
  36040. function PlaySoundAction(triggerOptions, sound, condition) {
  36041. _super.call(this, triggerOptions, condition);
  36042. this._sound = sound;
  36043. }
  36044. PlaySoundAction.prototype._prepare = function () {
  36045. };
  36046. PlaySoundAction.prototype.execute = function () {
  36047. if (this._sound !== undefined)
  36048. this._sound.play();
  36049. };
  36050. PlaySoundAction.prototype.serialize = function (parent) {
  36051. return _super.prototype._serialize.call(this, {
  36052. name: "PlaySoundAction",
  36053. properties: [{ name: "sound", value: this._sound.name }]
  36054. }, parent);
  36055. };
  36056. return PlaySoundAction;
  36057. }(BABYLON.Action));
  36058. BABYLON.PlaySoundAction = PlaySoundAction;
  36059. var StopSoundAction = (function (_super) {
  36060. __extends(StopSoundAction, _super);
  36061. function StopSoundAction(triggerOptions, sound, condition) {
  36062. _super.call(this, triggerOptions, condition);
  36063. this._sound = sound;
  36064. }
  36065. StopSoundAction.prototype._prepare = function () {
  36066. };
  36067. StopSoundAction.prototype.execute = function () {
  36068. if (this._sound !== undefined)
  36069. this._sound.stop();
  36070. };
  36071. StopSoundAction.prototype.serialize = function (parent) {
  36072. return _super.prototype._serialize.call(this, {
  36073. name: "StopSoundAction",
  36074. properties: [{ name: "sound", value: this._sound.name }]
  36075. }, parent);
  36076. };
  36077. return StopSoundAction;
  36078. }(BABYLON.Action));
  36079. BABYLON.StopSoundAction = StopSoundAction;
  36080. })(BABYLON || (BABYLON = {}));
  36081. //# sourceMappingURL=babylon.directActions.js.map
  36082. var BABYLON;
  36083. (function (BABYLON) {
  36084. var Geometry = (function () {
  36085. function Geometry(id, scene, vertexData, updatable, mesh) {
  36086. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36087. this._totalVertices = 0;
  36088. this._isDisposed = false;
  36089. this.id = id;
  36090. this._engine = scene.getEngine();
  36091. this._meshes = [];
  36092. this._scene = scene;
  36093. //Init vertex buffer cache
  36094. this._vertexBuffers = {};
  36095. this._indices = [];
  36096. // vertexData
  36097. if (vertexData) {
  36098. this.setAllVerticesData(vertexData, updatable);
  36099. }
  36100. else {
  36101. this._totalVertices = 0;
  36102. this._indices = [];
  36103. }
  36104. // applyToMesh
  36105. if (mesh) {
  36106. if (mesh instanceof BABYLON.LinesMesh) {
  36107. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  36108. this.updateExtend();
  36109. }
  36110. this.applyToMesh(mesh);
  36111. mesh.computeWorldMatrix(true);
  36112. }
  36113. }
  36114. Object.defineProperty(Geometry.prototype, "boundingBias", {
  36115. /**
  36116. * 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
  36117. * @returns The Bias Vector
  36118. */
  36119. get: function () {
  36120. return this._boundingBias;
  36121. },
  36122. set: function (value) {
  36123. if (this._boundingBias && this._boundingBias.equals(value)) {
  36124. return;
  36125. }
  36126. this._boundingBias = value.clone();
  36127. this.updateBoundingInfo(true, null);
  36128. },
  36129. enumerable: true,
  36130. configurable: true
  36131. });
  36132. Object.defineProperty(Geometry.prototype, "extend", {
  36133. get: function () {
  36134. return this._extend;
  36135. },
  36136. enumerable: true,
  36137. configurable: true
  36138. });
  36139. Geometry.prototype.getScene = function () {
  36140. return this._scene;
  36141. };
  36142. Geometry.prototype.getEngine = function () {
  36143. return this._engine;
  36144. };
  36145. Geometry.prototype.isReady = function () {
  36146. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  36147. };
  36148. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  36149. get: function () {
  36150. for (var index = 0; index < this._meshes.length; index++) {
  36151. if (!this._meshes[index].doNotSerialize) {
  36152. return false;
  36153. }
  36154. }
  36155. return true;
  36156. },
  36157. enumerable: true,
  36158. configurable: true
  36159. });
  36160. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36161. vertexData.applyToGeometry(this, updatable);
  36162. this.notifyUpdate();
  36163. };
  36164. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  36165. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  36166. this.setVerticesBuffer(buffer);
  36167. };
  36168. Geometry.prototype.setVerticesBuffer = function (buffer) {
  36169. var kind = buffer.getKind();
  36170. if (this._vertexBuffers[kind]) {
  36171. this._vertexBuffers[kind].dispose();
  36172. }
  36173. this._vertexBuffers[kind] = buffer;
  36174. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36175. var data = buffer.getData();
  36176. var stride = buffer.getStrideSize();
  36177. this._totalVertices = data.length / stride;
  36178. this.updateExtend(data, stride);
  36179. var meshes = this._meshes;
  36180. var numOfMeshes = meshes.length;
  36181. for (var index = 0; index < numOfMeshes; index++) {
  36182. var mesh = meshes[index];
  36183. mesh._resetPointsArrayCache();
  36184. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36185. mesh._createGlobalSubMesh();
  36186. mesh.computeWorldMatrix(true);
  36187. }
  36188. }
  36189. this.notifyUpdate(kind);
  36190. };
  36191. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  36192. var vertexBuffer = this.getVertexBuffer(kind);
  36193. if (!vertexBuffer) {
  36194. return;
  36195. }
  36196. vertexBuffer.updateDirectly(data, offset);
  36197. this.notifyUpdate(kind);
  36198. };
  36199. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  36200. var vertexBuffer = this.getVertexBuffer(kind);
  36201. if (!vertexBuffer) {
  36202. return;
  36203. }
  36204. vertexBuffer.update(data);
  36205. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36206. var stride = vertexBuffer.getStrideSize();
  36207. this._totalVertices = data.length / stride;
  36208. this.updateBoundingInfo(updateExtends, data);
  36209. }
  36210. this.notifyUpdate(kind);
  36211. };
  36212. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  36213. if (updateExtends) {
  36214. this.updateExtend(data);
  36215. }
  36216. var meshes = this._meshes;
  36217. var numOfMeshes = meshes.length;
  36218. for (var index = 0; index < numOfMeshes; index++) {
  36219. var mesh = meshes[index];
  36220. mesh._resetPointsArrayCache();
  36221. if (updateExtends) {
  36222. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36223. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36224. var subMesh = mesh.subMeshes[subIndex];
  36225. subMesh.refreshBoundingInfo();
  36226. }
  36227. }
  36228. }
  36229. };
  36230. Geometry.prototype.getTotalVertices = function () {
  36231. if (!this.isReady()) {
  36232. return 0;
  36233. }
  36234. return this._totalVertices;
  36235. };
  36236. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  36237. var vertexBuffer = this.getVertexBuffer(kind);
  36238. if (!vertexBuffer) {
  36239. return null;
  36240. }
  36241. var orig = vertexBuffer.getData();
  36242. if (!copyWhenShared || this._meshes.length === 1) {
  36243. return orig;
  36244. }
  36245. else {
  36246. var len = orig.length;
  36247. var copy = [];
  36248. for (var i = 0; i < len; i++) {
  36249. copy.push(orig[i]);
  36250. }
  36251. return copy;
  36252. }
  36253. };
  36254. Geometry.prototype.getVertexBuffer = function (kind) {
  36255. if (!this.isReady()) {
  36256. return null;
  36257. }
  36258. return this._vertexBuffers[kind];
  36259. };
  36260. Geometry.prototype.getVertexBuffers = function () {
  36261. if (!this.isReady()) {
  36262. return null;
  36263. }
  36264. return this._vertexBuffers;
  36265. };
  36266. Geometry.prototype.isVerticesDataPresent = function (kind) {
  36267. if (!this._vertexBuffers) {
  36268. if (this._delayInfo) {
  36269. return this._delayInfo.indexOf(kind) !== -1;
  36270. }
  36271. return false;
  36272. }
  36273. return this._vertexBuffers[kind] !== undefined;
  36274. };
  36275. Geometry.prototype.getVerticesDataKinds = function () {
  36276. var result = [];
  36277. var kind;
  36278. if (!this._vertexBuffers && this._delayInfo) {
  36279. for (kind in this._delayInfo) {
  36280. result.push(kind);
  36281. }
  36282. }
  36283. else {
  36284. for (kind in this._vertexBuffers) {
  36285. result.push(kind);
  36286. }
  36287. }
  36288. return result;
  36289. };
  36290. Geometry.prototype.setIndices = function (indices, totalVertices) {
  36291. if (this._indexBuffer) {
  36292. this._engine._releaseBuffer(this._indexBuffer);
  36293. }
  36294. this._indices = indices;
  36295. if (this._meshes.length !== 0 && this._indices) {
  36296. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36297. }
  36298. if (totalVertices !== undefined) {
  36299. this._totalVertices = totalVertices;
  36300. }
  36301. var meshes = this._meshes;
  36302. var numOfMeshes = meshes.length;
  36303. for (var index = 0; index < numOfMeshes; index++) {
  36304. meshes[index]._createGlobalSubMesh();
  36305. }
  36306. this.notifyUpdate();
  36307. };
  36308. Geometry.prototype.getTotalIndices = function () {
  36309. if (!this.isReady()) {
  36310. return 0;
  36311. }
  36312. return this._indices.length;
  36313. };
  36314. Geometry.prototype.getIndices = function (copyWhenShared) {
  36315. if (!this.isReady()) {
  36316. return null;
  36317. }
  36318. var orig = this._indices;
  36319. if (!copyWhenShared || this._meshes.length === 1) {
  36320. return orig;
  36321. }
  36322. else {
  36323. var len = orig.length;
  36324. var copy = [];
  36325. for (var i = 0; i < len; i++) {
  36326. copy.push(orig[i]);
  36327. }
  36328. return copy;
  36329. }
  36330. };
  36331. Geometry.prototype.getIndexBuffer = function () {
  36332. if (!this.isReady()) {
  36333. return null;
  36334. }
  36335. return this._indexBuffer;
  36336. };
  36337. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  36338. var meshes = this._meshes;
  36339. var index = meshes.indexOf(mesh);
  36340. if (index === -1) {
  36341. return;
  36342. }
  36343. for (var kind in this._vertexBuffers) {
  36344. this._vertexBuffers[kind].dispose();
  36345. }
  36346. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  36347. this._indexBuffer = null;
  36348. }
  36349. meshes.splice(index, 1);
  36350. mesh._geometry = null;
  36351. if (meshes.length === 0 && shouldDispose) {
  36352. this.dispose();
  36353. }
  36354. };
  36355. Geometry.prototype.applyToMesh = function (mesh) {
  36356. if (mesh._geometry === this) {
  36357. return;
  36358. }
  36359. var previousGeometry = mesh._geometry;
  36360. if (previousGeometry) {
  36361. previousGeometry.releaseForMesh(mesh);
  36362. }
  36363. var meshes = this._meshes;
  36364. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  36365. mesh._geometry = this;
  36366. this._scene.pushGeometry(this);
  36367. meshes.push(mesh);
  36368. if (this.isReady()) {
  36369. this._applyToMesh(mesh);
  36370. }
  36371. else {
  36372. mesh._boundingInfo = this._boundingInfo;
  36373. }
  36374. };
  36375. Geometry.prototype.updateExtend = function (data, stride) {
  36376. if (data === void 0) { data = null; }
  36377. if (!data) {
  36378. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  36379. }
  36380. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  36381. };
  36382. Geometry.prototype._applyToMesh = function (mesh) {
  36383. var numOfMeshes = this._meshes.length;
  36384. // vertexBuffers
  36385. for (var kind in this._vertexBuffers) {
  36386. if (numOfMeshes === 1) {
  36387. this._vertexBuffers[kind].create();
  36388. }
  36389. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  36390. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36391. mesh._resetPointsArrayCache();
  36392. if (!this._extend) {
  36393. this.updateExtend(this._vertexBuffers[kind].getData());
  36394. }
  36395. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36396. mesh._createGlobalSubMesh();
  36397. //bounding info was just created again, world matrix should be applied again.
  36398. mesh._updateBoundingInfo();
  36399. }
  36400. }
  36401. // indexBuffer
  36402. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  36403. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36404. }
  36405. if (this._indexBuffer) {
  36406. this._indexBuffer.references = numOfMeshes;
  36407. }
  36408. };
  36409. Geometry.prototype.notifyUpdate = function (kind) {
  36410. if (this.onGeometryUpdated) {
  36411. this.onGeometryUpdated(this, kind);
  36412. }
  36413. };
  36414. Geometry.prototype.load = function (scene, onLoaded) {
  36415. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36416. return;
  36417. }
  36418. if (this.isReady()) {
  36419. if (onLoaded) {
  36420. onLoaded();
  36421. }
  36422. return;
  36423. }
  36424. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36425. this._queueLoad(scene, onLoaded);
  36426. };
  36427. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36428. var _this = this;
  36429. scene._addPendingData(this);
  36430. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  36431. _this._delayLoadingFunction(JSON.parse(data), _this);
  36432. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36433. _this._delayInfo = [];
  36434. scene._removePendingData(_this);
  36435. var meshes = _this._meshes;
  36436. var numOfMeshes = meshes.length;
  36437. for (var index = 0; index < numOfMeshes; index++) {
  36438. _this._applyToMesh(meshes[index]);
  36439. }
  36440. if (onLoaded) {
  36441. onLoaded();
  36442. }
  36443. }, function () { }, scene.database);
  36444. };
  36445. /**
  36446. * Invert the geometry to move from a right handed system to a left handed one.
  36447. */
  36448. Geometry.prototype.toLeftHanded = function () {
  36449. // Flip faces
  36450. var tIndices = this.getIndices(false);
  36451. if (tIndices != null && tIndices.length > 0) {
  36452. for (var i = 0; i < tIndices.length; i += 3) {
  36453. var tTemp = tIndices[i + 0];
  36454. tIndices[i + 0] = tIndices[i + 2];
  36455. tIndices[i + 2] = tTemp;
  36456. }
  36457. this.setIndices(tIndices);
  36458. }
  36459. // Negate position.z
  36460. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36461. if (tPositions != null && tPositions.length > 0) {
  36462. for (var i = 0; i < tPositions.length; i += 3) {
  36463. tPositions[i + 2] = -tPositions[i + 2];
  36464. }
  36465. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36466. }
  36467. // Negate normal.z
  36468. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36469. if (tNormals != null && tNormals.length > 0) {
  36470. for (var i = 0; i < tNormals.length; i += 3) {
  36471. tNormals[i + 2] = -tNormals[i + 2];
  36472. }
  36473. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36474. }
  36475. };
  36476. Geometry.prototype.isDisposed = function () {
  36477. return this._isDisposed;
  36478. };
  36479. Geometry.prototype.dispose = function () {
  36480. var meshes = this._meshes;
  36481. var numOfMeshes = meshes.length;
  36482. var index;
  36483. for (index = 0; index < numOfMeshes; index++) {
  36484. this.releaseForMesh(meshes[index]);
  36485. }
  36486. this._meshes = [];
  36487. for (var kind in this._vertexBuffers) {
  36488. this._vertexBuffers[kind].dispose();
  36489. }
  36490. this._vertexBuffers = {};
  36491. this._totalVertices = 0;
  36492. if (this._indexBuffer) {
  36493. this._engine._releaseBuffer(this._indexBuffer);
  36494. }
  36495. this._indexBuffer = null;
  36496. this._indices = [];
  36497. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36498. this.delayLoadingFile = null;
  36499. this._delayLoadingFunction = null;
  36500. this._delayInfo = [];
  36501. this._boundingInfo = null;
  36502. this._scene.removeGeometry(this);
  36503. this._isDisposed = true;
  36504. };
  36505. Geometry.prototype.copy = function (id) {
  36506. var vertexData = new BABYLON.VertexData();
  36507. vertexData.indices = [];
  36508. var indices = this.getIndices();
  36509. for (var index = 0; index < indices.length; index++) {
  36510. vertexData.indices.push(indices[index]);
  36511. }
  36512. var updatable = false;
  36513. var stopChecking = false;
  36514. var kind;
  36515. for (kind in this._vertexBuffers) {
  36516. // using slice() to make a copy of the array and not just reference it
  36517. var data = this.getVerticesData(kind);
  36518. if (data instanceof Float32Array) {
  36519. vertexData.set(new Float32Array(data), kind);
  36520. }
  36521. else {
  36522. vertexData.set(data.slice(0), kind);
  36523. }
  36524. if (!stopChecking) {
  36525. updatable = this.getVertexBuffer(kind).isUpdatable();
  36526. stopChecking = !updatable;
  36527. }
  36528. }
  36529. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  36530. geometry.delayLoadState = this.delayLoadState;
  36531. geometry.delayLoadingFile = this.delayLoadingFile;
  36532. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36533. for (kind in this._delayInfo) {
  36534. geometry._delayInfo = geometry._delayInfo || [];
  36535. geometry._delayInfo.push(kind);
  36536. }
  36537. // Bounding info
  36538. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36539. return geometry;
  36540. };
  36541. Geometry.prototype.serialize = function () {
  36542. var serializationObject = {};
  36543. serializationObject.id = this.id;
  36544. if (BABYLON.Tags.HasTags(this)) {
  36545. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36546. }
  36547. return serializationObject;
  36548. };
  36549. Geometry.prototype.serializeVerticeData = function () {
  36550. var serializationObject = this.serialize();
  36551. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36552. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36553. }
  36554. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36555. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36556. }
  36557. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36558. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36559. }
  36560. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36561. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  36562. }
  36563. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36564. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  36565. }
  36566. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36567. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  36568. }
  36569. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36570. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  36571. }
  36572. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36573. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  36574. }
  36575. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36576. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36577. }
  36578. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36579. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36580. serializationObject.matricesIndices._isExpanded = true;
  36581. }
  36582. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36583. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  36584. }
  36585. serializationObject.indices = this.getIndices();
  36586. return serializationObject;
  36587. };
  36588. // Statics
  36589. Geometry.ExtractFromMesh = function (mesh, id) {
  36590. var geometry = mesh._geometry;
  36591. if (!geometry) {
  36592. return null;
  36593. }
  36594. return geometry.copy(id);
  36595. };
  36596. /**
  36597. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36598. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36599. * Be aware Math.random() could cause collisions, but:
  36600. * "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"
  36601. */
  36602. Geometry.RandomId = function () {
  36603. return BABYLON.Tools.RandomId();
  36604. };
  36605. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  36606. var scene = mesh.getScene();
  36607. // Geometry
  36608. var geometryId = parsedGeometry.geometryId;
  36609. if (geometryId) {
  36610. var geometry = scene.getGeometryByID(geometryId);
  36611. if (geometry) {
  36612. geometry.applyToMesh(mesh);
  36613. }
  36614. }
  36615. else if (parsedGeometry instanceof ArrayBuffer) {
  36616. var binaryInfo = mesh._binaryInfo;
  36617. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36618. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36619. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36620. }
  36621. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36622. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36623. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36624. }
  36625. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36626. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36627. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36628. }
  36629. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36630. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36631. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36632. }
  36633. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36634. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36635. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36636. }
  36637. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36638. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36639. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36640. }
  36641. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36642. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36643. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36644. }
  36645. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36646. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36647. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36648. }
  36649. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36650. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36651. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36652. }
  36653. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36654. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36655. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36656. }
  36657. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36658. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36659. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36660. }
  36661. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36662. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36663. mesh.setIndices(indicesData);
  36664. }
  36665. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36666. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36667. mesh.subMeshes = [];
  36668. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36669. var materialIndex = subMeshesData[(i * 5) + 0];
  36670. var verticesStart = subMeshesData[(i * 5) + 1];
  36671. var verticesCount = subMeshesData[(i * 5) + 2];
  36672. var indexStart = subMeshesData[(i * 5) + 3];
  36673. var indexCount = subMeshesData[(i * 5) + 4];
  36674. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36675. }
  36676. }
  36677. }
  36678. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36679. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  36680. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  36681. if (parsedGeometry.uvs) {
  36682. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  36683. }
  36684. if (parsedGeometry.uvs2) {
  36685. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  36686. }
  36687. if (parsedGeometry.uvs3) {
  36688. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  36689. }
  36690. if (parsedGeometry.uvs4) {
  36691. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  36692. }
  36693. if (parsedGeometry.uvs5) {
  36694. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  36695. }
  36696. if (parsedGeometry.uvs6) {
  36697. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  36698. }
  36699. if (parsedGeometry.colors) {
  36700. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  36701. }
  36702. if (parsedGeometry.matricesIndices) {
  36703. if (!parsedGeometry.matricesIndices._isExpanded) {
  36704. var floatIndices = [];
  36705. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36706. var matricesIndex = parsedGeometry.matricesIndices[i];
  36707. floatIndices.push(matricesIndex & 0x000000FF);
  36708. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36709. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36710. floatIndices.push(matricesIndex >> 24);
  36711. }
  36712. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  36713. }
  36714. else {
  36715. delete parsedGeometry.matricesIndices._isExpanded;
  36716. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  36717. }
  36718. }
  36719. if (parsedGeometry.matricesIndicesExtra) {
  36720. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36721. var floatIndices = [];
  36722. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36723. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36724. floatIndices.push(matricesIndex & 0x000000FF);
  36725. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36726. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36727. floatIndices.push(matricesIndex >> 24);
  36728. }
  36729. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  36730. }
  36731. else {
  36732. delete parsedGeometry.matricesIndices._isExpanded;
  36733. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  36734. }
  36735. }
  36736. if (parsedGeometry.matricesWeights) {
  36737. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  36738. }
  36739. if (parsedGeometry.matricesWeightsExtra) {
  36740. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  36741. }
  36742. mesh.setIndices(parsedGeometry.indices);
  36743. }
  36744. // SubMeshes
  36745. if (parsedGeometry.subMeshes) {
  36746. mesh.subMeshes = [];
  36747. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36748. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36749. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36750. }
  36751. }
  36752. // Flat shading
  36753. if (mesh._shouldGenerateFlatShading) {
  36754. mesh.convertToFlatShadedMesh();
  36755. delete mesh._shouldGenerateFlatShading;
  36756. }
  36757. // Update
  36758. mesh.computeWorldMatrix(true);
  36759. // Octree
  36760. if (scene['_selectionOctree']) {
  36761. scene['_selectionOctree'].addMesh(mesh);
  36762. }
  36763. };
  36764. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36765. if (scene.getGeometryByID(parsedVertexData.id)) {
  36766. return null; // null since geometry could be something else than a box...
  36767. }
  36768. var geometry = new Geometry(parsedVertexData.id, scene);
  36769. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36770. if (parsedVertexData.delayLoadingFile) {
  36771. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36772. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36773. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36774. geometry._delayInfo = [];
  36775. if (parsedVertexData.hasUVs) {
  36776. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36777. }
  36778. if (parsedVertexData.hasUVs2) {
  36779. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36780. }
  36781. if (parsedVertexData.hasUVs3) {
  36782. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36783. }
  36784. if (parsedVertexData.hasUVs4) {
  36785. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36786. }
  36787. if (parsedVertexData.hasUVs5) {
  36788. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36789. }
  36790. if (parsedVertexData.hasUVs6) {
  36791. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36792. }
  36793. if (parsedVertexData.hasColors) {
  36794. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36795. }
  36796. if (parsedVertexData.hasMatricesIndices) {
  36797. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36798. }
  36799. if (parsedVertexData.hasMatricesWeights) {
  36800. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36801. }
  36802. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36803. }
  36804. else {
  36805. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36806. }
  36807. scene.pushGeometry(geometry, true);
  36808. return geometry;
  36809. };
  36810. return Geometry;
  36811. }());
  36812. BABYLON.Geometry = Geometry;
  36813. /////// Primitives //////////////////////////////////////////////
  36814. var Geometry;
  36815. (function (Geometry) {
  36816. var Primitives;
  36817. (function (Primitives) {
  36818. /// Abstract class
  36819. var _Primitive = (function (_super) {
  36820. __extends(_Primitive, _super);
  36821. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  36822. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  36823. this._canBeRegenerated = _canBeRegenerated;
  36824. this._beingRegenerated = true;
  36825. this.regenerate();
  36826. this._beingRegenerated = false;
  36827. }
  36828. _Primitive.prototype.canBeRegenerated = function () {
  36829. return this._canBeRegenerated;
  36830. };
  36831. _Primitive.prototype.regenerate = function () {
  36832. if (!this._canBeRegenerated) {
  36833. return;
  36834. }
  36835. this._beingRegenerated = true;
  36836. this.setAllVerticesData(this._regenerateVertexData(), false);
  36837. this._beingRegenerated = false;
  36838. };
  36839. _Primitive.prototype.asNewGeometry = function (id) {
  36840. return _super.prototype.copy.call(this, id);
  36841. };
  36842. // overrides
  36843. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  36844. if (!this._beingRegenerated) {
  36845. return;
  36846. }
  36847. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36848. };
  36849. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  36850. if (!this._beingRegenerated) {
  36851. return;
  36852. }
  36853. _super.prototype.setVerticesData.call(this, kind, data, false);
  36854. };
  36855. // to override
  36856. // protected
  36857. _Primitive.prototype._regenerateVertexData = function () {
  36858. throw new Error("Abstract method");
  36859. };
  36860. _Primitive.prototype.copy = function (id) {
  36861. throw new Error("Must be overriden in sub-classes.");
  36862. };
  36863. _Primitive.prototype.serialize = function () {
  36864. var serializationObject = _super.prototype.serialize.call(this);
  36865. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36866. return serializationObject;
  36867. };
  36868. return _Primitive;
  36869. }(Geometry));
  36870. Primitives._Primitive = _Primitive;
  36871. var Ribbon = (function (_super) {
  36872. __extends(Ribbon, _super);
  36873. // Members
  36874. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  36875. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36876. _super.call(this, id, scene, canBeRegenerated, mesh);
  36877. this.pathArray = pathArray;
  36878. this.closeArray = closeArray;
  36879. this.closePath = closePath;
  36880. this.offset = offset;
  36881. this.side = side;
  36882. }
  36883. Ribbon.prototype._regenerateVertexData = function () {
  36884. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36885. };
  36886. Ribbon.prototype.copy = function (id) {
  36887. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  36888. };
  36889. return Ribbon;
  36890. }(_Primitive));
  36891. Primitives.Ribbon = Ribbon;
  36892. var Box = (function (_super) {
  36893. __extends(Box, _super);
  36894. // Members
  36895. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  36896. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36897. _super.call(this, id, scene, canBeRegenerated, mesh);
  36898. this.size = size;
  36899. this.side = side;
  36900. }
  36901. Box.prototype._regenerateVertexData = function () {
  36902. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36903. };
  36904. Box.prototype.copy = function (id) {
  36905. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36906. };
  36907. Box.prototype.serialize = function () {
  36908. var serializationObject = _super.prototype.serialize.call(this);
  36909. serializationObject.size = this.size;
  36910. return serializationObject;
  36911. };
  36912. Box.Parse = function (parsedBox, scene) {
  36913. if (scene.getGeometryByID(parsedBox.id)) {
  36914. return null; // null since geometry could be something else than a box...
  36915. }
  36916. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36917. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36918. scene.pushGeometry(box, true);
  36919. return box;
  36920. };
  36921. return Box;
  36922. }(_Primitive));
  36923. Primitives.Box = Box;
  36924. var Sphere = (function (_super) {
  36925. __extends(Sphere, _super);
  36926. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  36927. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36928. _super.call(this, id, scene, canBeRegenerated, mesh);
  36929. this.segments = segments;
  36930. this.diameter = diameter;
  36931. this.side = side;
  36932. }
  36933. Sphere.prototype._regenerateVertexData = function () {
  36934. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36935. };
  36936. Sphere.prototype.copy = function (id) {
  36937. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36938. };
  36939. Sphere.prototype.serialize = function () {
  36940. var serializationObject = _super.prototype.serialize.call(this);
  36941. serializationObject.segments = this.segments;
  36942. serializationObject.diameter = this.diameter;
  36943. return serializationObject;
  36944. };
  36945. Sphere.Parse = function (parsedSphere, scene) {
  36946. if (scene.getGeometryByID(parsedSphere.id)) {
  36947. return null; // null since geometry could be something else than a sphere...
  36948. }
  36949. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36950. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36951. scene.pushGeometry(sphere, true);
  36952. return sphere;
  36953. };
  36954. return Sphere;
  36955. }(_Primitive));
  36956. Primitives.Sphere = Sphere;
  36957. var Disc = (function (_super) {
  36958. __extends(Disc, _super);
  36959. // Members
  36960. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  36961. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36962. _super.call(this, id, scene, canBeRegenerated, mesh);
  36963. this.radius = radius;
  36964. this.tessellation = tessellation;
  36965. this.side = side;
  36966. }
  36967. Disc.prototype._regenerateVertexData = function () {
  36968. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36969. };
  36970. Disc.prototype.copy = function (id) {
  36971. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36972. };
  36973. return Disc;
  36974. }(_Primitive));
  36975. Primitives.Disc = Disc;
  36976. var Cylinder = (function (_super) {
  36977. __extends(Cylinder, _super);
  36978. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  36979. if (subdivisions === void 0) { subdivisions = 1; }
  36980. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36981. _super.call(this, id, scene, canBeRegenerated, mesh);
  36982. this.height = height;
  36983. this.diameterTop = diameterTop;
  36984. this.diameterBottom = diameterBottom;
  36985. this.tessellation = tessellation;
  36986. this.subdivisions = subdivisions;
  36987. this.side = side;
  36988. }
  36989. Cylinder.prototype._regenerateVertexData = function () {
  36990. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36991. };
  36992. Cylinder.prototype.copy = function (id) {
  36993. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36994. };
  36995. Cylinder.prototype.serialize = function () {
  36996. var serializationObject = _super.prototype.serialize.call(this);
  36997. serializationObject.height = this.height;
  36998. serializationObject.diameterTop = this.diameterTop;
  36999. serializationObject.diameterBottom = this.diameterBottom;
  37000. serializationObject.tessellation = this.tessellation;
  37001. return serializationObject;
  37002. };
  37003. Cylinder.Parse = function (parsedCylinder, scene) {
  37004. if (scene.getGeometryByID(parsedCylinder.id)) {
  37005. return null; // null since geometry could be something else than a cylinder...
  37006. }
  37007. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  37008. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  37009. scene.pushGeometry(cylinder, true);
  37010. return cylinder;
  37011. };
  37012. return Cylinder;
  37013. }(_Primitive));
  37014. Primitives.Cylinder = Cylinder;
  37015. var Torus = (function (_super) {
  37016. __extends(Torus, _super);
  37017. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  37018. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37019. _super.call(this, id, scene, canBeRegenerated, mesh);
  37020. this.diameter = diameter;
  37021. this.thickness = thickness;
  37022. this.tessellation = tessellation;
  37023. this.side = side;
  37024. }
  37025. Torus.prototype._regenerateVertexData = function () {
  37026. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  37027. };
  37028. Torus.prototype.copy = function (id) {
  37029. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  37030. };
  37031. Torus.prototype.serialize = function () {
  37032. var serializationObject = _super.prototype.serialize.call(this);
  37033. serializationObject.diameter = this.diameter;
  37034. serializationObject.thickness = this.thickness;
  37035. serializationObject.tessellation = this.tessellation;
  37036. return serializationObject;
  37037. };
  37038. Torus.Parse = function (parsedTorus, scene) {
  37039. if (scene.getGeometryByID(parsedTorus.id)) {
  37040. return null; // null since geometry could be something else than a torus...
  37041. }
  37042. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  37043. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  37044. scene.pushGeometry(torus, true);
  37045. return torus;
  37046. };
  37047. return Torus;
  37048. }(_Primitive));
  37049. Primitives.Torus = Torus;
  37050. var Ground = (function (_super) {
  37051. __extends(Ground, _super);
  37052. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  37053. _super.call(this, id, scene, canBeRegenerated, mesh);
  37054. this.width = width;
  37055. this.height = height;
  37056. this.subdivisions = subdivisions;
  37057. }
  37058. Ground.prototype._regenerateVertexData = function () {
  37059. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  37060. };
  37061. Ground.prototype.copy = function (id) {
  37062. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  37063. };
  37064. Ground.prototype.serialize = function () {
  37065. var serializationObject = _super.prototype.serialize.call(this);
  37066. serializationObject.width = this.width;
  37067. serializationObject.height = this.height;
  37068. serializationObject.subdivisions = this.subdivisions;
  37069. return serializationObject;
  37070. };
  37071. Ground.Parse = function (parsedGround, scene) {
  37072. if (scene.getGeometryByID(parsedGround.id)) {
  37073. return null; // null since geometry could be something else than a ground...
  37074. }
  37075. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  37076. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  37077. scene.pushGeometry(ground, true);
  37078. return ground;
  37079. };
  37080. return Ground;
  37081. }(_Primitive));
  37082. Primitives.Ground = Ground;
  37083. var TiledGround = (function (_super) {
  37084. __extends(TiledGround, _super);
  37085. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  37086. _super.call(this, id, scene, canBeRegenerated, mesh);
  37087. this.xmin = xmin;
  37088. this.zmin = zmin;
  37089. this.xmax = xmax;
  37090. this.zmax = zmax;
  37091. this.subdivisions = subdivisions;
  37092. this.precision = precision;
  37093. }
  37094. TiledGround.prototype._regenerateVertexData = function () {
  37095. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37096. };
  37097. TiledGround.prototype.copy = function (id) {
  37098. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37099. };
  37100. return TiledGround;
  37101. }(_Primitive));
  37102. Primitives.TiledGround = TiledGround;
  37103. var Plane = (function (_super) {
  37104. __extends(Plane, _super);
  37105. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  37106. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37107. _super.call(this, id, scene, canBeRegenerated, mesh);
  37108. this.size = size;
  37109. this.side = side;
  37110. }
  37111. Plane.prototype._regenerateVertexData = function () {
  37112. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37113. };
  37114. Plane.prototype.copy = function (id) {
  37115. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37116. };
  37117. Plane.prototype.serialize = function () {
  37118. var serializationObject = _super.prototype.serialize.call(this);
  37119. serializationObject.size = this.size;
  37120. return serializationObject;
  37121. };
  37122. Plane.Parse = function (parsedPlane, scene) {
  37123. if (scene.getGeometryByID(parsedPlane.id)) {
  37124. return null; // null since geometry could be something else than a ground...
  37125. }
  37126. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37127. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37128. scene.pushGeometry(plane, true);
  37129. return plane;
  37130. };
  37131. return Plane;
  37132. }(_Primitive));
  37133. Primitives.Plane = Plane;
  37134. var TorusKnot = (function (_super) {
  37135. __extends(TorusKnot, _super);
  37136. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  37137. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37138. _super.call(this, id, scene, canBeRegenerated, mesh);
  37139. this.radius = radius;
  37140. this.tube = tube;
  37141. this.radialSegments = radialSegments;
  37142. this.tubularSegments = tubularSegments;
  37143. this.p = p;
  37144. this.q = q;
  37145. this.side = side;
  37146. }
  37147. TorusKnot.prototype._regenerateVertexData = function () {
  37148. 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 });
  37149. };
  37150. TorusKnot.prototype.copy = function (id) {
  37151. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37152. };
  37153. TorusKnot.prototype.serialize = function () {
  37154. var serializationObject = _super.prototype.serialize.call(this);
  37155. serializationObject.radius = this.radius;
  37156. serializationObject.tube = this.tube;
  37157. serializationObject.radialSegments = this.radialSegments;
  37158. serializationObject.tubularSegments = this.tubularSegments;
  37159. serializationObject.p = this.p;
  37160. serializationObject.q = this.q;
  37161. return serializationObject;
  37162. };
  37163. ;
  37164. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  37165. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37166. return null; // null since geometry could be something else than a ground...
  37167. }
  37168. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37169. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37170. scene.pushGeometry(torusKnot, true);
  37171. return torusKnot;
  37172. };
  37173. return TorusKnot;
  37174. }(_Primitive));
  37175. Primitives.TorusKnot = TorusKnot;
  37176. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  37177. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  37178. })(BABYLON || (BABYLON = {}));
  37179. //# sourceMappingURL=babylon.geometry.js.map
  37180. var BABYLON;
  37181. (function (BABYLON) {
  37182. var GroundMesh = (function (_super) {
  37183. __extends(GroundMesh, _super);
  37184. function GroundMesh(name, scene) {
  37185. _super.call(this, name, scene);
  37186. this.generateOctree = false;
  37187. this._worldInverse = new BABYLON.Matrix();
  37188. }
  37189. GroundMesh.prototype.getClassName = function () {
  37190. return "GroundMesh";
  37191. };
  37192. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37193. get: function () {
  37194. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37195. },
  37196. enumerable: true,
  37197. configurable: true
  37198. });
  37199. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37200. get: function () {
  37201. return this._subdivisionsX;
  37202. },
  37203. enumerable: true,
  37204. configurable: true
  37205. });
  37206. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37207. get: function () {
  37208. return this._subdivisionsY;
  37209. },
  37210. enumerable: true,
  37211. configurable: true
  37212. });
  37213. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37214. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37215. this._subdivisionsX = chunksCount;
  37216. this._subdivisionsY = chunksCount;
  37217. this.subdivide(chunksCount);
  37218. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37219. };
  37220. /**
  37221. * Returns a height (y) value in the Worl system :
  37222. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37223. * Returns the ground y position if (x, z) are outside the ground surface.
  37224. * Not pertinent if the ground is rotated.
  37225. */
  37226. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37227. // express x and y in the ground local system
  37228. x -= this.position.x;
  37229. z -= this.position.z;
  37230. x /= this.scaling.x;
  37231. z /= this.scaling.z;
  37232. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37233. return this.position.y;
  37234. }
  37235. if (!this._heightQuads || this._heightQuads.length == 0) {
  37236. this._initHeightQuads();
  37237. this._computeHeightQuads();
  37238. }
  37239. var facet = this._getFacetAt(x, z);
  37240. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37241. // return y in the World system
  37242. return y * this.scaling.y + this.position.y;
  37243. };
  37244. /**
  37245. * Returns a normalized vector (Vector3) orthogonal to the ground
  37246. * at the ground coordinates (x, z) expressed in the World system.
  37247. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  37248. * Not pertinent if the ground is rotated.
  37249. */
  37250. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37251. var normal = new BABYLON.Vector3(0, 1, 0);
  37252. this.getNormalAtCoordinatesToRef(x, z, normal);
  37253. return normal;
  37254. };
  37255. /**
  37256. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37257. * at the ground coordinates (x, z) expressed in the World system.
  37258. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37259. * Not pertinent if the ground is rotated.
  37260. */
  37261. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37262. // express x and y in the ground local system
  37263. x -= this.position.x;
  37264. z -= this.position.z;
  37265. x /= this.scaling.x;
  37266. z /= this.scaling.z;
  37267. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37268. return;
  37269. }
  37270. if (!this._heightQuads || this._heightQuads.length == 0) {
  37271. this._initHeightQuads();
  37272. this._computeHeightQuads();
  37273. }
  37274. var facet = this._getFacetAt(x, z);
  37275. ref.x = facet.x;
  37276. ref.y = facet.y;
  37277. ref.z = facet.z;
  37278. };
  37279. /**
  37280. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37281. * if the ground has been updated.
  37282. * This can be used in the render loop
  37283. */
  37284. GroundMesh.prototype.updateCoordinateHeights = function () {
  37285. if (!this._heightQuads || this._heightQuads.length == 0) {
  37286. this._initHeightQuads();
  37287. }
  37288. this._computeHeightQuads();
  37289. };
  37290. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37291. GroundMesh.prototype._getFacetAt = function (x, z) {
  37292. // retrieve col and row from x, z coordinates in the ground local system
  37293. var subdivisionsX = this._subdivisionsX;
  37294. var subdivisionsY = this._subdivisionsY;
  37295. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37296. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37297. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37298. var facet;
  37299. if (z < quad.slope.x * x + quad.slope.y) {
  37300. facet = quad.facet1;
  37301. }
  37302. else {
  37303. facet = quad.facet2;
  37304. }
  37305. return facet;
  37306. };
  37307. // Creates and populates the heightMap array with "facet" elements :
  37308. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37309. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37310. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37311. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37312. GroundMesh.prototype._initHeightQuads = function () {
  37313. var subdivisionsX = this._subdivisionsX;
  37314. var subdivisionsY = this._subdivisionsY;
  37315. this._heightQuads = new Array();
  37316. for (var row = 0; row < subdivisionsY; row++) {
  37317. for (var col = 0; col < subdivisionsX; col++) {
  37318. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  37319. this._heightQuads[row * subdivisionsX + col] = quad;
  37320. }
  37321. }
  37322. };
  37323. // Compute each quad element values and update the the heightMap array :
  37324. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37325. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37326. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37327. GroundMesh.prototype._computeHeightQuads = function () {
  37328. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37329. var v1 = BABYLON.Tmp.Vector3[3];
  37330. var v2 = BABYLON.Tmp.Vector3[2];
  37331. var v3 = BABYLON.Tmp.Vector3[1];
  37332. var v4 = BABYLON.Tmp.Vector3[0];
  37333. var v1v2 = BABYLON.Tmp.Vector3[4];
  37334. var v1v3 = BABYLON.Tmp.Vector3[5];
  37335. var v1v4 = BABYLON.Tmp.Vector3[6];
  37336. var norm1 = BABYLON.Tmp.Vector3[7];
  37337. var norm2 = BABYLON.Tmp.Vector3[8];
  37338. var i = 0;
  37339. var j = 0;
  37340. var k = 0;
  37341. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37342. var h = 0;
  37343. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37344. var d2 = 0;
  37345. var subdivisionsX = this._subdivisionsX;
  37346. var subdivisionsY = this._subdivisionsY;
  37347. for (var row = 0; row < subdivisionsY; row++) {
  37348. for (var col = 0; col < subdivisionsX; col++) {
  37349. i = col * 3;
  37350. j = row * (subdivisionsX + 1) * 3;
  37351. k = (row + 1) * (subdivisionsX + 1) * 3;
  37352. v1.x = positions[j + i];
  37353. v1.y = positions[j + i + 1];
  37354. v1.z = positions[j + i + 2];
  37355. v2.x = positions[j + i + 3];
  37356. v2.y = positions[j + i + 4];
  37357. v2.z = positions[j + i + 5];
  37358. v3.x = positions[k + i];
  37359. v3.y = positions[k + i + 1];
  37360. v3.z = positions[k + i + 2];
  37361. v4.x = positions[k + i + 3];
  37362. v4.y = positions[k + i + 4];
  37363. v4.z = positions[k + i + 5];
  37364. // 2D slope V1V4
  37365. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37366. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37367. // facet equations :
  37368. // we compute each facet normal vector
  37369. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37370. // we compute the value d by applying the equation to v1 which belongs to the plane
  37371. // then we store the facet equation in a Vector4
  37372. v2.subtractToRef(v1, v1v2);
  37373. v3.subtractToRef(v1, v1v3);
  37374. v4.subtractToRef(v1, v1v4);
  37375. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37376. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37377. norm1.normalize();
  37378. norm2.normalize();
  37379. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37380. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37381. var quad = this._heightQuads[row * subdivisionsX + col];
  37382. quad.slope.copyFromFloats(cd, h);
  37383. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37384. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37385. }
  37386. }
  37387. };
  37388. return GroundMesh;
  37389. }(BABYLON.Mesh));
  37390. BABYLON.GroundMesh = GroundMesh;
  37391. })(BABYLON || (BABYLON = {}));
  37392. //# sourceMappingURL=babylon.groundMesh.js.map
  37393. var BABYLON;
  37394. (function (BABYLON) {
  37395. var LinesMesh = (function (_super) {
  37396. __extends(LinesMesh, _super);
  37397. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  37398. if (parent === void 0) { parent = null; }
  37399. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  37400. this.color = new BABYLON.Color3(1, 1, 1);
  37401. this.alpha = 1;
  37402. this._positionBuffer = {};
  37403. if (source) {
  37404. this.color = source.color.clone();
  37405. this.alpha = source.alpha;
  37406. }
  37407. this._intersectionThreshold = 0.1;
  37408. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  37409. attributes: [BABYLON.VertexBuffer.PositionKind],
  37410. uniforms: ["worldViewProjection", "color"],
  37411. needAlphaBlending: true
  37412. });
  37413. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37414. }
  37415. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37416. /**
  37417. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37418. * This margin is expressed in world space coordinates, so its value may vary.
  37419. * Default value is 0.1
  37420. * @returns the intersection Threshold value.
  37421. */
  37422. get: function () {
  37423. return this._intersectionThreshold;
  37424. },
  37425. /**
  37426. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37427. * This margin is expressed in world space coordinates, so its value may vary.
  37428. * @param value the new threshold to apply
  37429. */
  37430. set: function (value) {
  37431. if (this._intersectionThreshold === value) {
  37432. return;
  37433. }
  37434. this._intersectionThreshold = value;
  37435. if (this.geometry) {
  37436. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37437. }
  37438. },
  37439. enumerable: true,
  37440. configurable: true
  37441. });
  37442. LinesMesh.prototype.getClassName = function () {
  37443. return "LinesMesh";
  37444. };
  37445. Object.defineProperty(LinesMesh.prototype, "material", {
  37446. get: function () {
  37447. return this._colorShader;
  37448. },
  37449. enumerable: true,
  37450. configurable: true
  37451. });
  37452. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37453. get: function () {
  37454. return false;
  37455. },
  37456. enumerable: true,
  37457. configurable: true
  37458. });
  37459. LinesMesh.prototype.createInstance = function (name) {
  37460. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37461. return null;
  37462. };
  37463. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37464. var engine = this.getScene().getEngine();
  37465. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37466. // VBOs
  37467. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37468. // Color
  37469. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37470. };
  37471. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37472. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37473. return;
  37474. }
  37475. var engine = this.getScene().getEngine();
  37476. // Draw order
  37477. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37478. };
  37479. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37480. this._colorShader.dispose();
  37481. _super.prototype.dispose.call(this, doNotRecurse);
  37482. };
  37483. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37484. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37485. };
  37486. return LinesMesh;
  37487. }(BABYLON.Mesh));
  37488. BABYLON.LinesMesh = LinesMesh;
  37489. })(BABYLON || (BABYLON = {}));
  37490. //# sourceMappingURL=babylon.linesMesh.js.map
  37491. var BABYLON;
  37492. (function (BABYLON) {
  37493. var DefaultLoadingScreen = (function () {
  37494. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  37495. var _this = this;
  37496. if (_loadingText === void 0) { _loadingText = ""; }
  37497. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  37498. this._renderingCanvas = _renderingCanvas;
  37499. this._loadingText = _loadingText;
  37500. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  37501. // Resize
  37502. this._resizeLoadingUI = function () {
  37503. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  37504. _this._loadingDiv.style.position = "absolute";
  37505. _this._loadingDiv.style.left = canvasRect.left + "px";
  37506. _this._loadingDiv.style.top = canvasRect.top + "px";
  37507. _this._loadingDiv.style.width = canvasRect.width + "px";
  37508. _this._loadingDiv.style.height = canvasRect.height + "px";
  37509. };
  37510. }
  37511. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  37512. var _this = this;
  37513. if (this._loadingDiv) {
  37514. // Do not add a loading screen if there is already one
  37515. return;
  37516. }
  37517. this._loadingDiv = document.createElement("div");
  37518. this._loadingDiv.id = "babylonjsLoadingDiv";
  37519. this._loadingDiv.style.opacity = "0";
  37520. this._loadingDiv.style.transition = "opacity 1.5s ease";
  37521. // Loading text
  37522. this._loadingTextDiv = document.createElement("div");
  37523. this._loadingTextDiv.style.position = "absolute";
  37524. this._loadingTextDiv.style.left = "0";
  37525. this._loadingTextDiv.style.top = "50%";
  37526. this._loadingTextDiv.style.marginTop = "80px";
  37527. this._loadingTextDiv.style.width = "100%";
  37528. this._loadingTextDiv.style.height = "20px";
  37529. this._loadingTextDiv.style.fontFamily = "Arial";
  37530. this._loadingTextDiv.style.fontSize = "14px";
  37531. this._loadingTextDiv.style.color = "white";
  37532. this._loadingTextDiv.style.textAlign = "center";
  37533. this._loadingTextDiv.innerHTML = "Loading";
  37534. this._loadingDiv.appendChild(this._loadingTextDiv);
  37535. //set the predefined text
  37536. this._loadingTextDiv.innerHTML = this._loadingText;
  37537. // Loading img
  37538. var imgBack = new Image();
  37539. 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==";
  37540. imgBack.style.position = "absolute";
  37541. imgBack.style.left = "50%";
  37542. imgBack.style.top = "50%";
  37543. imgBack.style.marginLeft = "-50px";
  37544. imgBack.style.marginTop = "-50px";
  37545. imgBack.style.transition = "transform 1.0s ease";
  37546. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  37547. var deg = 360;
  37548. var onTransitionEnd = function () {
  37549. deg += 360;
  37550. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  37551. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  37552. };
  37553. imgBack.addEventListener("transitionend", onTransitionEnd);
  37554. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  37555. this._loadingDiv.appendChild(imgBack);
  37556. // front image
  37557. var imgFront = new Image();
  37558. 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=";
  37559. imgFront.style.position = "absolute";
  37560. imgFront.style.left = "50%";
  37561. imgFront.style.top = "50%";
  37562. imgFront.style.marginLeft = "-50px";
  37563. imgFront.style.marginTop = "-50px";
  37564. this._loadingDiv.appendChild(imgFront);
  37565. this._resizeLoadingUI();
  37566. window.addEventListener("resize", this._resizeLoadingUI);
  37567. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37568. document.body.appendChild(this._loadingDiv);
  37569. setTimeout(function () {
  37570. _this._loadingDiv.style.opacity = "1";
  37571. imgBack.style.transform = "rotateZ(360deg)";
  37572. imgBack.style.webkitTransform = "rotateZ(360deg)";
  37573. }, 0);
  37574. };
  37575. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  37576. var _this = this;
  37577. if (!this._loadingDiv) {
  37578. return;
  37579. }
  37580. var onTransitionEnd = function () {
  37581. if (!_this._loadingDiv) {
  37582. return;
  37583. }
  37584. document.body.removeChild(_this._loadingDiv);
  37585. window.removeEventListener("resize", _this._resizeLoadingUI);
  37586. _this._loadingDiv = null;
  37587. };
  37588. this._loadingDiv.style.opacity = "0";
  37589. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  37590. };
  37591. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  37592. set: function (text) {
  37593. this._loadingText = text;
  37594. if (this._loadingTextDiv) {
  37595. this._loadingTextDiv.innerHTML = this._loadingText;
  37596. }
  37597. },
  37598. enumerable: true,
  37599. configurable: true
  37600. });
  37601. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  37602. get: function () {
  37603. return this._loadingDivBackgroundColor;
  37604. },
  37605. set: function (color) {
  37606. this._loadingDivBackgroundColor = color;
  37607. if (!this._loadingDiv) {
  37608. return;
  37609. }
  37610. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37611. },
  37612. enumerable: true,
  37613. configurable: true
  37614. });
  37615. return DefaultLoadingScreen;
  37616. }());
  37617. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  37618. })(BABYLON || (BABYLON = {}));
  37619. //# sourceMappingURL=babylon.loadingScreen.js.map
  37620. var BABYLON;
  37621. (function (BABYLON) {
  37622. var AudioEngine = (function () {
  37623. function AudioEngine() {
  37624. this._audioContext = null;
  37625. this._audioContextInitialized = false;
  37626. this.canUseWebAudio = false;
  37627. this.WarnedWebAudioUnsupported = false;
  37628. this.unlocked = false;
  37629. this.isMP3supported = false;
  37630. this.isOGGsupported = false;
  37631. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  37632. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  37633. this.canUseWebAudio = true;
  37634. }
  37635. var audioElem = document.createElement('audio');
  37636. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  37637. this.isMP3supported = true;
  37638. }
  37639. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  37640. this.isOGGsupported = true;
  37641. }
  37642. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  37643. this._unlockiOSaudio();
  37644. }
  37645. else {
  37646. this.unlocked = true;
  37647. }
  37648. }
  37649. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  37650. get: function () {
  37651. if (!this._audioContextInitialized) {
  37652. this._initializeAudioContext();
  37653. }
  37654. return this._audioContext;
  37655. },
  37656. enumerable: true,
  37657. configurable: true
  37658. });
  37659. AudioEngine.prototype._unlockiOSaudio = function () {
  37660. var _this = this;
  37661. var unlockaudio = function () {
  37662. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  37663. var source = _this.audioContext.createBufferSource();
  37664. source.buffer = buffer;
  37665. source.connect(_this.audioContext.destination);
  37666. source.start(0);
  37667. setTimeout(function () {
  37668. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  37669. _this.unlocked = true;
  37670. window.removeEventListener('touchend', unlockaudio, false);
  37671. if (_this.onAudioUnlocked) {
  37672. _this.onAudioUnlocked();
  37673. }
  37674. }
  37675. }, 0);
  37676. };
  37677. window.addEventListener('touchend', unlockaudio, false);
  37678. };
  37679. AudioEngine.prototype._initializeAudioContext = function () {
  37680. try {
  37681. if (this.canUseWebAudio) {
  37682. this._audioContext = new AudioContext();
  37683. // create a global volume gain node
  37684. this.masterGain = this._audioContext.createGain();
  37685. this.masterGain.gain.value = 1;
  37686. this.masterGain.connect(this._audioContext.destination);
  37687. this._audioContextInitialized = true;
  37688. }
  37689. }
  37690. catch (e) {
  37691. this.canUseWebAudio = false;
  37692. BABYLON.Tools.Error("Web Audio: " + e.message);
  37693. }
  37694. };
  37695. AudioEngine.prototype.dispose = function () {
  37696. if (this.canUseWebAudio && this._audioContextInitialized) {
  37697. if (this._connectedAnalyser) {
  37698. this._connectedAnalyser.stopDebugCanvas();
  37699. this._connectedAnalyser.dispose();
  37700. this.masterGain.disconnect();
  37701. this.masterGain.connect(this._audioContext.destination);
  37702. this._connectedAnalyser = null;
  37703. }
  37704. this.masterGain.gain.value = 1;
  37705. }
  37706. this.WarnedWebAudioUnsupported = false;
  37707. };
  37708. AudioEngine.prototype.getGlobalVolume = function () {
  37709. if (this.canUseWebAudio && this._audioContextInitialized) {
  37710. return this.masterGain.gain.value;
  37711. }
  37712. else {
  37713. return -1;
  37714. }
  37715. };
  37716. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  37717. if (this.canUseWebAudio && this._audioContextInitialized) {
  37718. this.masterGain.gain.value = newVolume;
  37719. }
  37720. };
  37721. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  37722. if (this._connectedAnalyser) {
  37723. this._connectedAnalyser.stopDebugCanvas();
  37724. }
  37725. if (this.canUseWebAudio && this._audioContextInitialized) {
  37726. this._connectedAnalyser = analyser;
  37727. this.masterGain.disconnect();
  37728. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  37729. }
  37730. };
  37731. return AudioEngine;
  37732. }());
  37733. BABYLON.AudioEngine = AudioEngine;
  37734. })(BABYLON || (BABYLON = {}));
  37735. //# sourceMappingURL=babylon.audioEngine.js.map
  37736. var BABYLON;
  37737. (function (BABYLON) {
  37738. var Sound = (function () {
  37739. /**
  37740. * Create a sound and attach it to a scene
  37741. * @param name Name of your sound
  37742. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  37743. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  37744. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  37745. */
  37746. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  37747. var _this = this;
  37748. this.autoplay = false;
  37749. this.loop = false;
  37750. this.useCustomAttenuation = false;
  37751. this.spatialSound = false;
  37752. this.refDistance = 1;
  37753. this.rolloffFactor = 1;
  37754. this.maxDistance = 100;
  37755. this.distanceModel = "linear";
  37756. this._panningModel = "equalpower";
  37757. this._playbackRate = 1;
  37758. this._streaming = false;
  37759. this._startTime = 0;
  37760. this._startOffset = 0;
  37761. this._position = BABYLON.Vector3.Zero();
  37762. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  37763. this._volume = 1;
  37764. this._isLoaded = false;
  37765. this._isReadyToPlay = false;
  37766. this.isPlaying = false;
  37767. this.isPaused = false;
  37768. this._isDirectional = false;
  37769. // Used if you'd like to create a directional sound.
  37770. // If not set, the sound will be omnidirectional
  37771. this._coneInnerAngle = 360;
  37772. this._coneOuterAngle = 360;
  37773. this._coneOuterGain = 0;
  37774. this._isOutputConnected = false;
  37775. this._urlType = "Unknown";
  37776. this.name = name;
  37777. this._scene = scene;
  37778. this._readyToPlayCallback = readyToPlayCallback;
  37779. // Default custom attenuation function is a linear attenuation
  37780. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  37781. if (currentDistance < maxDistance) {
  37782. return currentVolume * (1 - currentDistance / maxDistance);
  37783. }
  37784. else {
  37785. return 0;
  37786. }
  37787. };
  37788. if (options) {
  37789. this.autoplay = options.autoplay || false;
  37790. this.loop = options.loop || false;
  37791. // if volume === 0, we need another way to check this option
  37792. if (options.volume !== undefined) {
  37793. this._volume = options.volume;
  37794. }
  37795. this.spatialSound = options.spatialSound || false;
  37796. this.maxDistance = options.maxDistance || 100;
  37797. this.useCustomAttenuation = options.useCustomAttenuation || false;
  37798. this.rolloffFactor = options.rolloffFactor || 1;
  37799. this.refDistance = options.refDistance || 1;
  37800. this.distanceModel = options.distanceModel || "linear";
  37801. this._playbackRate = options.playbackRate || 1;
  37802. this._streaming = options.streaming || false;
  37803. }
  37804. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37805. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  37806. this._soundGain.gain.value = this._volume;
  37807. this._inputAudioNode = this._soundGain;
  37808. this._ouputAudioNode = this._soundGain;
  37809. if (this.spatialSound) {
  37810. this._createSpatialParameters();
  37811. }
  37812. this._scene.mainSoundTrack.AddSound(this);
  37813. var validParameter = true;
  37814. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  37815. if (urlOrArrayBuffer) {
  37816. if (typeof (urlOrArrayBuffer) === "string")
  37817. this._urlType = "String";
  37818. if (Array.isArray(urlOrArrayBuffer))
  37819. this._urlType = "Array";
  37820. if (urlOrArrayBuffer instanceof ArrayBuffer)
  37821. this._urlType = "ArrayBuffer";
  37822. var urls = [];
  37823. var codecSupportedFound = false;
  37824. switch (this._urlType) {
  37825. case "ArrayBuffer":
  37826. if (urlOrArrayBuffer.byteLength > 0) {
  37827. codecSupportedFound = true;
  37828. this._soundLoaded(urlOrArrayBuffer);
  37829. }
  37830. break;
  37831. case "String":
  37832. urls.push(urlOrArrayBuffer);
  37833. case "Array":
  37834. if (urls.length === 0)
  37835. urls = urlOrArrayBuffer;
  37836. // If we found a supported format, we load it immediately and stop the loop
  37837. for (var i = 0; i < urls.length; i++) {
  37838. var url = urls[i];
  37839. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  37840. codecSupportedFound = true;
  37841. }
  37842. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  37843. codecSupportedFound = true;
  37844. }
  37845. if (url.indexOf(".wav", url.length - 4) !== -1) {
  37846. codecSupportedFound = true;
  37847. }
  37848. if (codecSupportedFound) {
  37849. // Loading sound using XHR2
  37850. if (!this._streaming) {
  37851. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  37852. }
  37853. else {
  37854. this._htmlAudioElement = new Audio(url);
  37855. this._htmlAudioElement.controls = false;
  37856. this._htmlAudioElement.loop = this.loop;
  37857. this._htmlAudioElement.crossOrigin = "anonymous";
  37858. this._htmlAudioElement.preload = "auto";
  37859. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  37860. _this._isReadyToPlay = true;
  37861. if (_this.autoplay) {
  37862. _this.play();
  37863. }
  37864. if (_this._readyToPlayCallback) {
  37865. _this._readyToPlayCallback();
  37866. }
  37867. });
  37868. document.body.appendChild(this._htmlAudioElement);
  37869. }
  37870. break;
  37871. }
  37872. }
  37873. break;
  37874. default:
  37875. validParameter = false;
  37876. break;
  37877. }
  37878. if (!validParameter) {
  37879. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  37880. }
  37881. else {
  37882. if (!codecSupportedFound) {
  37883. this._isReadyToPlay = true;
  37884. // Simulating a ready to play event to avoid breaking code path
  37885. if (this._readyToPlayCallback) {
  37886. window.setTimeout(function () {
  37887. _this._readyToPlayCallback();
  37888. }, 1000);
  37889. }
  37890. }
  37891. }
  37892. }
  37893. }
  37894. else {
  37895. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  37896. this._scene.mainSoundTrack.AddSound(this);
  37897. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  37898. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  37899. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  37900. }
  37901. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  37902. if (this._readyToPlayCallback) {
  37903. window.setTimeout(function () {
  37904. _this._readyToPlayCallback();
  37905. }, 1000);
  37906. }
  37907. }
  37908. }
  37909. Sound.prototype.dispose = function () {
  37910. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  37911. if (this.isPlaying) {
  37912. this.stop();
  37913. }
  37914. this._isReadyToPlay = false;
  37915. if (this.soundTrackId === -1) {
  37916. this._scene.mainSoundTrack.RemoveSound(this);
  37917. }
  37918. else {
  37919. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  37920. }
  37921. if (this._soundGain) {
  37922. this._soundGain.disconnect();
  37923. this._soundGain = null;
  37924. }
  37925. if (this._soundPanner) {
  37926. this._soundPanner.disconnect();
  37927. this._soundPanner = null;
  37928. }
  37929. if (this._soundSource) {
  37930. this._soundSource.disconnect();
  37931. this._soundSource = null;
  37932. }
  37933. this._audioBuffer = null;
  37934. if (this._htmlAudioElement) {
  37935. this._htmlAudioElement.pause();
  37936. this._htmlAudioElement.src = "";
  37937. document.body.removeChild(this._htmlAudioElement);
  37938. }
  37939. if (this._connectedMesh) {
  37940. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37941. this._connectedMesh = null;
  37942. }
  37943. }
  37944. };
  37945. Sound.prototype._soundLoaded = function (audioData) {
  37946. var _this = this;
  37947. this._isLoaded = true;
  37948. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  37949. _this._audioBuffer = buffer;
  37950. _this._isReadyToPlay = true;
  37951. if (_this.autoplay) {
  37952. _this.play();
  37953. }
  37954. if (_this._readyToPlayCallback) {
  37955. _this._readyToPlayCallback();
  37956. }
  37957. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  37958. };
  37959. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  37960. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37961. this._audioBuffer = audioBuffer;
  37962. this._isReadyToPlay = true;
  37963. }
  37964. };
  37965. Sound.prototype.updateOptions = function (options) {
  37966. if (options) {
  37967. this.loop = options.loop || this.loop;
  37968. this.maxDistance = options.maxDistance || this.maxDistance;
  37969. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  37970. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  37971. this.refDistance = options.refDistance || this.refDistance;
  37972. this.distanceModel = options.distanceModel || this.distanceModel;
  37973. this._playbackRate = options.playbackRate || this._playbackRate;
  37974. this._updateSpatialParameters();
  37975. if (this.isPlaying) {
  37976. if (this._streaming) {
  37977. this._htmlAudioElement.playbackRate = this._playbackRate;
  37978. }
  37979. else {
  37980. this._soundSource.playbackRate.value = this._playbackRate;
  37981. }
  37982. }
  37983. }
  37984. };
  37985. Sound.prototype._createSpatialParameters = function () {
  37986. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37987. if (this._scene.headphone) {
  37988. this._panningModel = "HRTF";
  37989. }
  37990. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  37991. this._updateSpatialParameters();
  37992. this._soundPanner.connect(this._ouputAudioNode);
  37993. this._inputAudioNode = this._soundPanner;
  37994. }
  37995. };
  37996. Sound.prototype._updateSpatialParameters = function () {
  37997. if (this.spatialSound) {
  37998. if (this.useCustomAttenuation) {
  37999. // Tricks to disable in a way embedded Web Audio attenuation
  38000. this._soundPanner.distanceModel = "linear";
  38001. this._soundPanner.maxDistance = Number.MAX_VALUE;
  38002. this._soundPanner.refDistance = 1;
  38003. this._soundPanner.rolloffFactor = 1;
  38004. this._soundPanner.panningModel = this._panningModel;
  38005. }
  38006. else {
  38007. this._soundPanner.distanceModel = this.distanceModel;
  38008. this._soundPanner.maxDistance = this.maxDistance;
  38009. this._soundPanner.refDistance = this.refDistance;
  38010. this._soundPanner.rolloffFactor = this.rolloffFactor;
  38011. this._soundPanner.panningModel = this._panningModel;
  38012. }
  38013. }
  38014. };
  38015. Sound.prototype.switchPanningModelToHRTF = function () {
  38016. this._panningModel = "HRTF";
  38017. this._switchPanningModel();
  38018. };
  38019. Sound.prototype.switchPanningModelToEqualPower = function () {
  38020. this._panningModel = "equalpower";
  38021. this._switchPanningModel();
  38022. };
  38023. Sound.prototype._switchPanningModel = function () {
  38024. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38025. this._soundPanner.panningModel = this._panningModel;
  38026. }
  38027. };
  38028. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  38029. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38030. if (this._isOutputConnected) {
  38031. this._ouputAudioNode.disconnect();
  38032. }
  38033. this._ouputAudioNode.connect(soundTrackAudioNode);
  38034. this._isOutputConnected = true;
  38035. }
  38036. };
  38037. /**
  38038. * Transform this sound into a directional source
  38039. * @param coneInnerAngle Size of the inner cone in degree
  38040. * @param coneOuterAngle Size of the outer cone in degree
  38041. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  38042. */
  38043. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  38044. if (coneOuterAngle < coneInnerAngle) {
  38045. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  38046. return;
  38047. }
  38048. this._coneInnerAngle = coneInnerAngle;
  38049. this._coneOuterAngle = coneOuterAngle;
  38050. this._coneOuterGain = coneOuterGain;
  38051. this._isDirectional = true;
  38052. if (this.isPlaying && this.loop) {
  38053. this.stop();
  38054. this.play();
  38055. }
  38056. };
  38057. Sound.prototype.setPosition = function (newPosition) {
  38058. this._position = newPosition;
  38059. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38060. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38061. }
  38062. };
  38063. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  38064. this._localDirection = newLocalDirection;
  38065. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  38066. this._updateDirection();
  38067. }
  38068. };
  38069. Sound.prototype._updateDirection = function () {
  38070. var mat = this._connectedMesh.getWorldMatrix();
  38071. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  38072. direction.normalize();
  38073. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  38074. };
  38075. Sound.prototype.updateDistanceFromListener = function () {
  38076. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  38077. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  38078. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  38079. }
  38080. };
  38081. Sound.prototype.setAttenuationFunction = function (callback) {
  38082. this._customAttenuationFunction = callback;
  38083. };
  38084. /**
  38085. * Play the sound
  38086. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  38087. * @param offset (optional) Start the sound setting it at a specific time
  38088. */
  38089. Sound.prototype.play = function (time, offset) {
  38090. var _this = this;
  38091. if (this._isReadyToPlay && this._scene.audioEnabled) {
  38092. try {
  38093. if (this._startOffset < 0) {
  38094. time = -this._startOffset;
  38095. this._startOffset = 0;
  38096. }
  38097. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38098. if (!this._soundSource || !this._streamingSource) {
  38099. if (this.spatialSound) {
  38100. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38101. if (this._isDirectional) {
  38102. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  38103. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  38104. this._soundPanner.coneOuterGain = this._coneOuterGain;
  38105. if (this._connectedMesh) {
  38106. this._updateDirection();
  38107. }
  38108. else {
  38109. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  38110. }
  38111. }
  38112. }
  38113. }
  38114. if (this._streaming) {
  38115. if (!this._streamingSource) {
  38116. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  38117. this._htmlAudioElement.onended = function () { _this._onended(); };
  38118. this._htmlAudioElement.playbackRate = this._playbackRate;
  38119. }
  38120. this._streamingSource.disconnect();
  38121. this._streamingSource.connect(this._inputAudioNode);
  38122. this._htmlAudioElement.play();
  38123. }
  38124. else {
  38125. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  38126. this._soundSource.buffer = this._audioBuffer;
  38127. this._soundSource.connect(this._inputAudioNode);
  38128. this._soundSource.loop = this.loop;
  38129. this._soundSource.playbackRate.value = this._playbackRate;
  38130. this._soundSource.onended = function () { _this._onended(); };
  38131. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  38132. }
  38133. this._startTime = startTime;
  38134. this.isPlaying = true;
  38135. this.isPaused = false;
  38136. }
  38137. catch (ex) {
  38138. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  38139. }
  38140. }
  38141. };
  38142. Sound.prototype._onended = function () {
  38143. this.isPlaying = false;
  38144. if (this.onended) {
  38145. this.onended();
  38146. }
  38147. };
  38148. /**
  38149. * Stop the sound
  38150. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  38151. */
  38152. Sound.prototype.stop = function (time) {
  38153. if (this.isPlaying) {
  38154. if (this._streaming) {
  38155. this._htmlAudioElement.pause();
  38156. // Test needed for Firefox or it will generate an Invalid State Error
  38157. if (this._htmlAudioElement.currentTime > 0) {
  38158. this._htmlAudioElement.currentTime = 0;
  38159. }
  38160. }
  38161. else {
  38162. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38163. this._soundSource.stop(stopTime);
  38164. this._soundSource.onended = null;
  38165. if (!this.isPaused) {
  38166. this._startOffset = 0;
  38167. }
  38168. }
  38169. this.isPlaying = false;
  38170. }
  38171. };
  38172. Sound.prototype.pause = function () {
  38173. if (this.isPlaying) {
  38174. this.isPaused = true;
  38175. if (this._streaming) {
  38176. this._htmlAudioElement.pause();
  38177. }
  38178. else {
  38179. this.stop(0);
  38180. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  38181. }
  38182. }
  38183. };
  38184. Sound.prototype.setVolume = function (newVolume, time) {
  38185. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38186. if (time) {
  38187. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  38188. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  38189. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  38190. }
  38191. else {
  38192. this._soundGain.gain.value = newVolume;
  38193. }
  38194. }
  38195. this._volume = newVolume;
  38196. };
  38197. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  38198. this._playbackRate = newPlaybackRate;
  38199. if (this.isPlaying) {
  38200. if (this._streaming) {
  38201. this._htmlAudioElement.playbackRate = this._playbackRate;
  38202. }
  38203. else {
  38204. this._soundSource.playbackRate.value = this._playbackRate;
  38205. }
  38206. }
  38207. };
  38208. Sound.prototype.getVolume = function () {
  38209. return this._volume;
  38210. };
  38211. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  38212. var _this = this;
  38213. if (this._connectedMesh) {
  38214. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38215. this._registerFunc = null;
  38216. }
  38217. this._connectedMesh = meshToConnectTo;
  38218. if (!this.spatialSound) {
  38219. this.spatialSound = true;
  38220. this._createSpatialParameters();
  38221. if (this.isPlaying && this.loop) {
  38222. this.stop();
  38223. this.play();
  38224. }
  38225. }
  38226. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  38227. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  38228. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  38229. };
  38230. Sound.prototype.detachFromMesh = function () {
  38231. if (this._connectedMesh) {
  38232. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38233. this._registerFunc = null;
  38234. this._connectedMesh = null;
  38235. }
  38236. };
  38237. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  38238. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  38239. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  38240. this._updateDirection();
  38241. }
  38242. };
  38243. Sound.prototype.clone = function () {
  38244. var _this = this;
  38245. if (!this._streaming) {
  38246. var setBufferAndRun = function () {
  38247. if (_this._isReadyToPlay) {
  38248. clonedSound._audioBuffer = _this.getAudioBuffer();
  38249. clonedSound._isReadyToPlay = true;
  38250. if (clonedSound.autoplay) {
  38251. clonedSound.play();
  38252. }
  38253. }
  38254. else {
  38255. window.setTimeout(setBufferAndRun, 300);
  38256. }
  38257. };
  38258. var currentOptions = {
  38259. autoplay: this.autoplay, loop: this.loop,
  38260. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  38261. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  38262. refDistance: this.refDistance, distanceModel: this.distanceModel
  38263. };
  38264. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  38265. if (this.useCustomAttenuation) {
  38266. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  38267. }
  38268. clonedSound.setPosition(this._position);
  38269. clonedSound.setPlaybackRate(this._playbackRate);
  38270. setBufferAndRun();
  38271. return clonedSound;
  38272. }
  38273. else {
  38274. return null;
  38275. }
  38276. };
  38277. Sound.prototype.getAudioBuffer = function () {
  38278. return this._audioBuffer;
  38279. };
  38280. Sound.prototype.serialize = function () {
  38281. var serializationObject = {
  38282. name: this.name,
  38283. url: this.name,
  38284. autoplay: this.autoplay,
  38285. loop: this.loop,
  38286. volume: this._volume,
  38287. spatialSound: this.spatialSound,
  38288. maxDistance: this.maxDistance,
  38289. rolloffFactor: this.rolloffFactor,
  38290. refDistance: this.refDistance,
  38291. distanceModel: this.distanceModel,
  38292. playbackRate: this._playbackRate,
  38293. panningModel: this._panningModel,
  38294. soundTrackId: this.soundTrackId
  38295. };
  38296. if (this.spatialSound) {
  38297. if (this._connectedMesh)
  38298. serializationObject.connectedMeshId = this._connectedMesh.id;
  38299. serializationObject.position = this._position.asArray();
  38300. serializationObject.refDistance = this.refDistance;
  38301. serializationObject.distanceModel = this.distanceModel;
  38302. serializationObject.isDirectional = this._isDirectional;
  38303. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  38304. serializationObject.coneInnerAngle = this._coneInnerAngle;
  38305. serializationObject.coneOuterAngle = this._coneOuterAngle;
  38306. serializationObject.coneOuterGain = this._coneOuterGain;
  38307. }
  38308. return serializationObject;
  38309. };
  38310. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  38311. var soundName = parsedSound.name;
  38312. var soundUrl;
  38313. if (parsedSound.url) {
  38314. soundUrl = rootUrl + parsedSound.url;
  38315. }
  38316. else {
  38317. soundUrl = rootUrl + soundName;
  38318. }
  38319. var options = {
  38320. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  38321. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  38322. rolloffFactor: parsedSound.rolloffFactor,
  38323. refDistance: parsedSound.refDistance,
  38324. distanceModel: parsedSound.distanceModel,
  38325. playbackRate: parsedSound.playbackRate
  38326. };
  38327. var newSound;
  38328. if (!sourceSound) {
  38329. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  38330. scene._addPendingData(newSound);
  38331. }
  38332. else {
  38333. var setBufferAndRun = function () {
  38334. if (sourceSound._isReadyToPlay) {
  38335. newSound._audioBuffer = sourceSound.getAudioBuffer();
  38336. newSound._isReadyToPlay = true;
  38337. if (newSound.autoplay) {
  38338. newSound.play();
  38339. }
  38340. }
  38341. else {
  38342. window.setTimeout(setBufferAndRun, 300);
  38343. }
  38344. };
  38345. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  38346. setBufferAndRun();
  38347. }
  38348. if (parsedSound.position) {
  38349. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  38350. newSound.setPosition(soundPosition);
  38351. }
  38352. if (parsedSound.isDirectional) {
  38353. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  38354. if (parsedSound.localDirectionToMesh) {
  38355. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  38356. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  38357. }
  38358. }
  38359. if (parsedSound.connectedMeshId) {
  38360. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  38361. if (connectedMesh) {
  38362. newSound.attachToMesh(connectedMesh);
  38363. }
  38364. }
  38365. return newSound;
  38366. };
  38367. return Sound;
  38368. }());
  38369. BABYLON.Sound = Sound;
  38370. })(BABYLON || (BABYLON = {}));
  38371. //# sourceMappingURL=babylon.sound.js.map
  38372. var BABYLON;
  38373. (function (BABYLON) {
  38374. var SoundTrack = (function () {
  38375. function SoundTrack(scene, options) {
  38376. this.id = -1;
  38377. this._isMainTrack = false;
  38378. this._isInitialized = false;
  38379. this._scene = scene;
  38380. this.soundCollection = new Array();
  38381. this._options = options;
  38382. if (!this._isMainTrack) {
  38383. this._scene.soundTracks.push(this);
  38384. this.id = this._scene.soundTracks.length - 1;
  38385. }
  38386. }
  38387. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  38388. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38389. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  38390. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  38391. if (this._options) {
  38392. if (this._options.volume) {
  38393. this._outputAudioNode.gain.value = this._options.volume;
  38394. }
  38395. if (this._options.mainTrack) {
  38396. this._isMainTrack = this._options.mainTrack;
  38397. }
  38398. }
  38399. this._isInitialized = true;
  38400. }
  38401. };
  38402. SoundTrack.prototype.dispose = function () {
  38403. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38404. if (this._connectedAnalyser) {
  38405. this._connectedAnalyser.stopDebugCanvas();
  38406. }
  38407. while (this.soundCollection.length) {
  38408. this.soundCollection[0].dispose();
  38409. }
  38410. if (this._outputAudioNode) {
  38411. this._outputAudioNode.disconnect();
  38412. }
  38413. this._outputAudioNode = null;
  38414. }
  38415. };
  38416. SoundTrack.prototype.AddSound = function (sound) {
  38417. if (!this._isInitialized) {
  38418. this._initializeSoundTrackAudioGraph();
  38419. }
  38420. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38421. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  38422. }
  38423. if (sound.soundTrackId) {
  38424. if (sound.soundTrackId === -1) {
  38425. this._scene.mainSoundTrack.RemoveSound(sound);
  38426. }
  38427. else {
  38428. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  38429. }
  38430. }
  38431. this.soundCollection.push(sound);
  38432. sound.soundTrackId = this.id;
  38433. };
  38434. SoundTrack.prototype.RemoveSound = function (sound) {
  38435. var index = this.soundCollection.indexOf(sound);
  38436. if (index !== -1) {
  38437. this.soundCollection.splice(index, 1);
  38438. }
  38439. };
  38440. SoundTrack.prototype.setVolume = function (newVolume) {
  38441. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38442. this._outputAudioNode.gain.value = newVolume;
  38443. }
  38444. };
  38445. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  38446. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38447. for (var i = 0; i < this.soundCollection.length; i++) {
  38448. this.soundCollection[i].switchPanningModelToHRTF();
  38449. }
  38450. }
  38451. };
  38452. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  38453. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38454. for (var i = 0; i < this.soundCollection.length; i++) {
  38455. this.soundCollection[i].switchPanningModelToEqualPower();
  38456. }
  38457. }
  38458. };
  38459. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  38460. if (this._connectedAnalyser) {
  38461. this._connectedAnalyser.stopDebugCanvas();
  38462. }
  38463. this._connectedAnalyser = analyser;
  38464. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38465. this._outputAudioNode.disconnect();
  38466. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  38467. }
  38468. };
  38469. return SoundTrack;
  38470. }());
  38471. BABYLON.SoundTrack = SoundTrack;
  38472. })(BABYLON || (BABYLON = {}));
  38473. //# sourceMappingURL=babylon.soundtrack.js.map
  38474. var BABYLON;
  38475. (function (BABYLON) {
  38476. /**
  38477. * Special Glow Blur post process only blurring the alpha channel
  38478. * It enforces keeping the most luminous color in the color channel.
  38479. */
  38480. var GlowBlurPostProcess = (function (_super) {
  38481. __extends(GlowBlurPostProcess, _super);
  38482. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  38483. var _this = this;
  38484. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38485. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  38486. this.direction = direction;
  38487. this.blurWidth = blurWidth;
  38488. this.onApplyObservable.add(function (effect) {
  38489. effect.setFloat2("screenSize", _this.width, _this.height);
  38490. effect.setVector2("direction", _this.direction);
  38491. effect.setFloat("blurWidth", _this.blurWidth);
  38492. });
  38493. }
  38494. return GlowBlurPostProcess;
  38495. }(BABYLON.PostProcess));
  38496. /**
  38497. * The highlight layer Helps adding a glow effect around a mesh.
  38498. *
  38499. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  38500. * glowy meshes to your scene.
  38501. *
  38502. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  38503. */
  38504. var HighlightLayer = (function () {
  38505. /**
  38506. * Instantiates a new highlight Layer and references it to the scene..
  38507. * @param name The name of the layer
  38508. * @param scene The scene to use the layer in
  38509. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  38510. */
  38511. function HighlightLayer(name, scene, options) {
  38512. this._vertexBuffers = {};
  38513. this._mainTextureDesiredSize = { width: 0, height: 0 };
  38514. this._meshes = {};
  38515. this._maxSize = 0;
  38516. this._shouldRender = false;
  38517. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  38518. this._excludedMeshes = {};
  38519. /**
  38520. * Specifies whether or not the inner glow is ACTIVE in the layer.
  38521. */
  38522. this.innerGlow = true;
  38523. /**
  38524. * Specifies whether or not the outer glow is ACTIVE in the layer.
  38525. */
  38526. this.outerGlow = true;
  38527. /**
  38528. * Specifies wether the highlight layer is enabled or not.
  38529. */
  38530. this.isEnabled = true;
  38531. /**
  38532. * An event triggered when the highlight layer has been disposed.
  38533. * @type {BABYLON.Observable}
  38534. */
  38535. this.onDisposeObservable = new BABYLON.Observable();
  38536. /**
  38537. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  38538. * @type {BABYLON.Observable}
  38539. */
  38540. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  38541. /**
  38542. * An event triggered when the highlight layer is being blurred.
  38543. * @type {BABYLON.Observable}
  38544. */
  38545. this.onBeforeBlurObservable = new BABYLON.Observable();
  38546. /**
  38547. * An event triggered when the highlight layer has been blurred.
  38548. * @type {BABYLON.Observable}
  38549. */
  38550. this.onAfterBlurObservable = new BABYLON.Observable();
  38551. /**
  38552. * An event triggered when the glowing blurred texture is being merged in the scene.
  38553. * @type {BABYLON.Observable}
  38554. */
  38555. this.onBeforeComposeObservable = new BABYLON.Observable();
  38556. /**
  38557. * An event triggered when the glowing blurred texture has been merged in the scene.
  38558. * @type {BABYLON.Observable}
  38559. */
  38560. this.onAfterComposeObservable = new BABYLON.Observable();
  38561. /**
  38562. * An event triggered when the highlight layer changes its size.
  38563. * @type {BABYLON.Observable}
  38564. */
  38565. this.onSizeChangedObservable = new BABYLON.Observable();
  38566. this._scene = scene;
  38567. var engine = scene.getEngine();
  38568. this._engine = engine;
  38569. this._maxSize = this._engine.getCaps().maxTextureSize;
  38570. this._scene.highlightLayers.push(this);
  38571. // Warn on stencil.
  38572. if (!this._engine.isStencilEnable) {
  38573. 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 }");
  38574. }
  38575. // Adapt options
  38576. this._options = options || {
  38577. mainTextureRatio: 0.25,
  38578. blurTextureSizeRatio: 0.5,
  38579. blurHorizontalSize: 1,
  38580. blurVerticalSize: 1,
  38581. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  38582. };
  38583. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  38584. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  38585. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  38586. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  38587. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  38588. // VBO
  38589. var vertices = [];
  38590. vertices.push(1, 1);
  38591. vertices.push(-1, 1);
  38592. vertices.push(-1, -1);
  38593. vertices.push(1, -1);
  38594. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38595. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38596. // Indices
  38597. var indices = [];
  38598. indices.push(0);
  38599. indices.push(1);
  38600. indices.push(2);
  38601. indices.push(0);
  38602. indices.push(2);
  38603. indices.push(3);
  38604. this._indexBuffer = engine.createIndexBuffer(indices);
  38605. // Effect
  38606. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  38607. // Render target
  38608. this.setMainTextureSize();
  38609. // Create Textures and post processes
  38610. this.createTextureAndPostProcesses();
  38611. }
  38612. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  38613. /**
  38614. * Gets the horizontal size of the blur.
  38615. */
  38616. get: function () {
  38617. return this._horizontalBlurPostprocess.blurWidth;
  38618. },
  38619. /**
  38620. * Specifies the horizontal size of the blur.
  38621. */
  38622. set: function (value) {
  38623. this._horizontalBlurPostprocess.blurWidth = value;
  38624. },
  38625. enumerable: true,
  38626. configurable: true
  38627. });
  38628. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  38629. /**
  38630. * Gets the vertical size of the blur.
  38631. */
  38632. get: function () {
  38633. return this._verticalBlurPostprocess.blurWidth;
  38634. },
  38635. /**
  38636. * Specifies the vertical size of the blur.
  38637. */
  38638. set: function (value) {
  38639. this._verticalBlurPostprocess.blurWidth = value;
  38640. },
  38641. enumerable: true,
  38642. configurable: true
  38643. });
  38644. Object.defineProperty(HighlightLayer.prototype, "camera", {
  38645. /**
  38646. * Gets the camera attached to the layer.
  38647. */
  38648. get: function () {
  38649. return this._options.camera;
  38650. },
  38651. enumerable: true,
  38652. configurable: true
  38653. });
  38654. /**
  38655. * Creates the render target textures and post processes used in the highlight layer.
  38656. */
  38657. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  38658. var _this = this;
  38659. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  38660. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  38661. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  38662. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  38663. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  38664. width: this._mainTextureDesiredSize.width,
  38665. height: this._mainTextureDesiredSize.height
  38666. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38667. this._mainTexture.activeCamera = this._options.camera;
  38668. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38669. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38670. this._mainTexture.anisotropicFilteringLevel = 1;
  38671. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38672. this._mainTexture.renderParticles = false;
  38673. this._mainTexture.renderList = null;
  38674. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  38675. width: blurTextureWidth,
  38676. height: blurTextureHeight
  38677. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38678. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38679. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38680. this._blurTexture.anisotropicFilteringLevel = 16;
  38681. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38682. this._blurTexture.renderParticles = false;
  38683. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38684. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  38685. effect.setTexture("textureSampler", _this._mainTexture);
  38686. });
  38687. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  38688. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38689. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38690. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38691. });
  38692. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38693. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38694. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38695. });
  38696. }
  38697. else {
  38698. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38699. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38700. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38701. });
  38702. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38703. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38704. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38705. });
  38706. }
  38707. this._mainTexture.onAfterUnbindObservable.add(function () {
  38708. _this.onBeforeBlurObservable.notifyObservers(_this);
  38709. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  38710. _this.onAfterBlurObservable.notifyObservers(_this);
  38711. });
  38712. // Custom render function
  38713. var renderSubMesh = function (subMesh) {
  38714. var mesh = subMesh.getRenderingMesh();
  38715. var scene = _this._scene;
  38716. var engine = scene.getEngine();
  38717. // Culling
  38718. engine.setState(subMesh.getMaterial().backFaceCulling);
  38719. // Managing instances
  38720. var batch = mesh._getInstancesRenderList(subMesh._id);
  38721. if (batch.mustReturn) {
  38722. return;
  38723. }
  38724. // Excluded Mesh
  38725. if (_this._excludedMeshes[mesh.id]) {
  38726. return;
  38727. }
  38728. ;
  38729. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38730. var highlightLayerMesh = _this._meshes[mesh.id];
  38731. var material = subMesh.getMaterial();
  38732. var emissiveTexture = null;
  38733. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  38734. emissiveTexture = material.emissiveTexture;
  38735. }
  38736. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  38737. engine.enableEffect(_this._glowMapGenerationEffect);
  38738. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  38739. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  38740. if (highlightLayerMesh) {
  38741. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  38742. }
  38743. else {
  38744. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  38745. }
  38746. // Alpha test
  38747. if (material && material.needAlphaTesting()) {
  38748. var alphaTexture = material.getAlphaTestTexture();
  38749. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  38750. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38751. }
  38752. // Glow emissive only
  38753. if (emissiveTexture) {
  38754. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  38755. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  38756. }
  38757. // Bones
  38758. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38759. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38760. }
  38761. // Draw
  38762. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  38763. }
  38764. else {
  38765. // Need to reset refresh rate of the shadowMap
  38766. _this._mainTexture.resetRefreshCounter();
  38767. }
  38768. };
  38769. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38770. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  38771. var index;
  38772. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38773. renderSubMesh(opaqueSubMeshes.data[index]);
  38774. }
  38775. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38776. renderSubMesh(alphaTestSubMeshes.data[index]);
  38777. }
  38778. for (index = 0; index < transparentSubMeshes.length; index++) {
  38779. renderSubMesh(transparentSubMeshes.data[index]);
  38780. }
  38781. };
  38782. this._mainTexture.onClearObservable.add(function (engine) {
  38783. engine.clear(HighlightLayer.neutralColor, true, true, true);
  38784. });
  38785. };
  38786. /**
  38787. * Checks for the readiness of the element composing the layer.
  38788. * @param subMesh the mesh to check for
  38789. * @param useInstances specify wether or not to use instances to render the mesh
  38790. * @param emissiveTexture the associated emissive texture used to generate the glow
  38791. * @return true if ready otherwise, false
  38792. */
  38793. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  38794. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  38795. return false;
  38796. }
  38797. var defines = [];
  38798. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38799. var mesh = subMesh.getMesh();
  38800. var material = subMesh.getMaterial();
  38801. var uv1 = false;
  38802. var uv2 = false;
  38803. // Alpha test
  38804. if (material && material.needAlphaTesting()) {
  38805. var alphaTexture = material.getAlphaTestTexture();
  38806. if (alphaTexture) {
  38807. defines.push("#define ALPHATEST");
  38808. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38809. alphaTexture.coordinatesIndex === 1) {
  38810. defines.push("#define DIFFUSEUV2");
  38811. uv2 = true;
  38812. }
  38813. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38814. defines.push("#define DIFFUSEUV1");
  38815. uv1 = true;
  38816. }
  38817. }
  38818. }
  38819. // Emissive
  38820. if (emissiveTexture) {
  38821. defines.push("#define EMISSIVE");
  38822. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38823. emissiveTexture.coordinatesIndex === 1) {
  38824. defines.push("#define EMISSIVEUV2");
  38825. uv2 = true;
  38826. }
  38827. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38828. defines.push("#define EMISSIVEUV1");
  38829. uv1 = true;
  38830. }
  38831. }
  38832. if (uv1) {
  38833. attribs.push(BABYLON.VertexBuffer.UVKind);
  38834. defines.push("#define UV1");
  38835. }
  38836. if (uv2) {
  38837. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38838. defines.push("#define UV2");
  38839. }
  38840. // Bones
  38841. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38842. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38843. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38844. if (mesh.numBoneInfluencers > 4) {
  38845. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38846. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38847. }
  38848. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38849. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38850. }
  38851. else {
  38852. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38853. }
  38854. // Instances
  38855. if (useInstances) {
  38856. defines.push("#define INSTANCES");
  38857. attribs.push("world0");
  38858. attribs.push("world1");
  38859. attribs.push("world2");
  38860. attribs.push("world3");
  38861. }
  38862. // Get correct effect
  38863. var join = defines.join("\n");
  38864. if (this._cachedDefines !== join) {
  38865. this._cachedDefines = join;
  38866. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  38867. }
  38868. return this._glowMapGenerationEffect.isReady();
  38869. };
  38870. /**
  38871. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  38872. */
  38873. HighlightLayer.prototype.render = function () {
  38874. var currentEffect = this._glowMapMergeEffect;
  38875. // Check
  38876. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  38877. return;
  38878. var engine = this._scene.getEngine();
  38879. this.onBeforeComposeObservable.notifyObservers(this);
  38880. // Render
  38881. engine.enableEffect(currentEffect);
  38882. engine.setState(false);
  38883. // Cache
  38884. var previousStencilBuffer = engine.getStencilBuffer();
  38885. var previousStencilFunction = engine.getStencilFunction();
  38886. var previousStencilMask = engine.getStencilMask();
  38887. var previousAlphaMode = engine.getAlphaMode();
  38888. // Texture
  38889. currentEffect.setTexture("textureSampler", this._blurTexture);
  38890. // VBOs
  38891. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38892. // Draw order
  38893. engine.setAlphaMode(this._options.alphaBlendingMode);
  38894. engine.setStencilMask(0x00);
  38895. engine.setStencilBuffer(true);
  38896. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  38897. if (this.outerGlow) {
  38898. currentEffect.setFloat("offset", 0);
  38899. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  38900. engine.draw(true, 0, 6);
  38901. }
  38902. if (this.innerGlow) {
  38903. currentEffect.setFloat("offset", 1);
  38904. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  38905. engine.draw(true, 0, 6);
  38906. }
  38907. // Restore Cache
  38908. engine.setStencilFunction(previousStencilFunction);
  38909. engine.setStencilMask(previousStencilMask);
  38910. engine.setAlphaMode(previousAlphaMode);
  38911. engine.setStencilBuffer(previousStencilBuffer);
  38912. this.onAfterComposeObservable.notifyObservers(this);
  38913. // Handle size changes.
  38914. var size = this._mainTexture.getSize();
  38915. this.setMainTextureSize();
  38916. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  38917. // Recreate RTT and post processes on size change.
  38918. this.onSizeChangedObservable.notifyObservers(this);
  38919. this.disposeTextureAndPostProcesses();
  38920. this.createTextureAndPostProcesses();
  38921. }
  38922. };
  38923. /**
  38924. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  38925. * @param mesh The mesh to exclude from the highlight layer
  38926. */
  38927. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  38928. var meshExcluded = this._excludedMeshes[mesh.id];
  38929. if (!meshExcluded) {
  38930. this._excludedMeshes[mesh.id] = {
  38931. mesh: mesh,
  38932. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  38933. mesh.getEngine().setStencilBuffer(false);
  38934. }),
  38935. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  38936. mesh.getEngine().setStencilBuffer(true);
  38937. }),
  38938. };
  38939. }
  38940. };
  38941. /**
  38942. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  38943. * @param mesh The mesh to highlight
  38944. */
  38945. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  38946. var meshExcluded = this._excludedMeshes[mesh.id];
  38947. if (meshExcluded) {
  38948. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  38949. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  38950. }
  38951. this._excludedMeshes[mesh.id] = undefined;
  38952. };
  38953. /**
  38954. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  38955. * @param mesh The mesh to highlight
  38956. * @param color The color of the highlight
  38957. * @param glowEmissiveOnly Extract the glow from the emissive texture
  38958. */
  38959. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  38960. var _this = this;
  38961. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  38962. var meshHighlight = this._meshes[mesh.id];
  38963. if (meshHighlight) {
  38964. meshHighlight.color = color;
  38965. }
  38966. else {
  38967. this._meshes[mesh.id] = {
  38968. mesh: mesh,
  38969. color: color,
  38970. // Lambda required for capture due to Observable this context
  38971. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  38972. if (_this._excludedMeshes[mesh.id]) {
  38973. _this.defaultStencilReference(mesh);
  38974. }
  38975. else {
  38976. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  38977. }
  38978. }),
  38979. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  38980. glowEmissiveOnly: glowEmissiveOnly
  38981. };
  38982. }
  38983. this._shouldRender = true;
  38984. };
  38985. /**
  38986. * Remove a mesh from the highlight layer in order to make it stop glowing.
  38987. * @param mesh The mesh to highlight
  38988. */
  38989. HighlightLayer.prototype.removeMesh = function (mesh) {
  38990. var meshHighlight = this._meshes[mesh.id];
  38991. if (meshHighlight) {
  38992. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  38993. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  38994. }
  38995. this._meshes[mesh.id] = undefined;
  38996. this._shouldRender = false;
  38997. for (var meshHighlightToCheck in this._meshes) {
  38998. if (meshHighlightToCheck) {
  38999. this._shouldRender = true;
  39000. break;
  39001. }
  39002. }
  39003. };
  39004. /**
  39005. * Returns true if the layer contains information to display, otherwise false.
  39006. */
  39007. HighlightLayer.prototype.shouldRender = function () {
  39008. return this.isEnabled && this._shouldRender;
  39009. };
  39010. /**
  39011. * Sets the main texture desired size which is the closest power of two
  39012. * of the engine canvas size.
  39013. */
  39014. HighlightLayer.prototype.setMainTextureSize = function () {
  39015. if (this._options.mainTextureFixedSize) {
  39016. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  39017. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  39018. }
  39019. else {
  39020. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  39021. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  39022. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  39023. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  39024. }
  39025. };
  39026. /**
  39027. * Force the stencil to the normal expected value for none glowing parts
  39028. */
  39029. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  39030. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  39031. };
  39032. /**
  39033. * Dispose only the render target textures and post process.
  39034. */
  39035. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  39036. this._blurTexture.dispose();
  39037. this._mainTexture.dispose();
  39038. this._downSamplePostprocess.dispose();
  39039. this._horizontalBlurPostprocess.dispose();
  39040. this._verticalBlurPostprocess.dispose();
  39041. };
  39042. /**
  39043. * Dispose the highlight layer and free resources.
  39044. */
  39045. HighlightLayer.prototype.dispose = function () {
  39046. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39047. if (vertexBuffer) {
  39048. vertexBuffer.dispose();
  39049. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39050. }
  39051. if (this._indexBuffer) {
  39052. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39053. this._indexBuffer = null;
  39054. }
  39055. // Clean textures and post processes
  39056. this.disposeTextureAndPostProcesses();
  39057. // Clean mesh references
  39058. for (var id in this._meshes) {
  39059. var meshHighlight = this._meshes[id];
  39060. if (meshHighlight && meshHighlight.mesh) {
  39061. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39062. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39063. }
  39064. }
  39065. this._meshes = null;
  39066. for (var id in this._excludedMeshes) {
  39067. var meshHighlight = this._excludedMeshes[id];
  39068. if (meshHighlight) {
  39069. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  39070. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  39071. }
  39072. }
  39073. this._excludedMeshes = null;
  39074. // Remove from scene
  39075. var index = this._scene.highlightLayers.indexOf(this, 0);
  39076. if (index > -1) {
  39077. this._scene.highlightLayers.splice(index, 1);
  39078. }
  39079. // Callback
  39080. this.onDisposeObservable.notifyObservers(this);
  39081. this.onDisposeObservable.clear();
  39082. this.onBeforeRenderMainTextureObservable.clear();
  39083. this.onBeforeBlurObservable.clear();
  39084. this.onBeforeComposeObservable.clear();
  39085. this.onAfterComposeObservable.clear();
  39086. this.onSizeChangedObservable.clear();
  39087. };
  39088. /**
  39089. * The neutral color used during the preparation of the glow effect.
  39090. * This is black by default as the blend operation is a blend operation.
  39091. */
  39092. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  39093. /**
  39094. * Stencil value used for glowing meshes.
  39095. */
  39096. HighlightLayer.glowingMeshStencilReference = 0x02;
  39097. /**
  39098. * Stencil value used for the other meshes in the scene.
  39099. */
  39100. HighlightLayer.normalMeshStencilReference = 0x01;
  39101. return HighlightLayer;
  39102. }());
  39103. BABYLON.HighlightLayer = HighlightLayer;
  39104. })(BABYLON || (BABYLON = {}));
  39105. //# sourceMappingURL=babylon.highlightlayer.js.map
  39106. var BABYLON;
  39107. (function (BABYLON) {
  39108. var SIMDVector3 = (function () {
  39109. function SIMDVector3() {
  39110. }
  39111. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  39112. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  39113. };
  39114. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  39115. var m = transformation.m;
  39116. var m0 = SIMD.Float32x4.load(m, 0);
  39117. var m1 = SIMD.Float32x4.load(m, 4);
  39118. var m2 = SIMD.Float32x4.load(m, 8);
  39119. var m3 = SIMD.Float32x4.load(m, 12);
  39120. 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));
  39121. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  39122. result.x = SIMD.Float32x4.extractLane(r, 0);
  39123. result.y = SIMD.Float32x4.extractLane(r, 1);
  39124. result.z = SIMD.Float32x4.extractLane(r, 2);
  39125. };
  39126. return SIMDVector3;
  39127. }());
  39128. var SIMDMatrix = (function () {
  39129. function SIMDMatrix() {
  39130. }
  39131. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  39132. var tm = this.m;
  39133. var om = other.m;
  39134. var m0 = SIMD.Float32x4.load(om, 0);
  39135. var m1 = SIMD.Float32x4.load(om, 4);
  39136. var m2 = SIMD.Float32x4.load(om, 8);
  39137. var m3 = SIMD.Float32x4.load(om, 12);
  39138. for (var i = 0; i < 16; i += 4) {
  39139. 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)))));
  39140. }
  39141. return this;
  39142. };
  39143. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  39144. var src = this.m;
  39145. var dest = other.m;
  39146. // Load the 4 rows
  39147. var src0 = SIMD.Float32x4.load(src, 0);
  39148. var src1 = SIMD.Float32x4.load(src, 4);
  39149. var src2 = SIMD.Float32x4.load(src, 8);
  39150. var src3 = SIMD.Float32x4.load(src, 12);
  39151. // Transpose the source matrix. Sort of. Not a true transpose operation
  39152. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  39153. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  39154. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  39155. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  39156. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  39157. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  39158. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  39159. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  39160. // This is a true transposition, but it will lead to an incorrect result
  39161. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  39162. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  39163. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39164. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39165. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  39166. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  39167. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39168. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39169. // ----
  39170. tmp1 = SIMD.Float32x4.mul(row2, row3);
  39171. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39172. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  39173. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  39174. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39175. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  39176. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  39177. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  39178. // ----
  39179. tmp1 = SIMD.Float32x4.mul(row1, row2);
  39180. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39181. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  39182. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  39183. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39184. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  39185. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  39186. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  39187. // ----
  39188. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  39189. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39190. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  39191. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  39192. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  39193. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39194. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  39195. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  39196. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  39197. // ----
  39198. tmp1 = SIMD.Float32x4.mul(row0, row1);
  39199. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39200. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39201. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  39202. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39203. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39204. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  39205. // ----
  39206. tmp1 = SIMD.Float32x4.mul(row0, row3);
  39207. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39208. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  39209. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  39210. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39211. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  39212. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  39213. // ----
  39214. tmp1 = SIMD.Float32x4.mul(row0, row2);
  39215. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39216. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  39217. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  39218. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39219. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  39220. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  39221. // Compute determinant
  39222. var det = SIMD.Float32x4.mul(row0, minor0);
  39223. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  39224. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  39225. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  39226. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  39227. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  39228. // These shuffles aren't necessary if the faulty transposition is done
  39229. // up at the top of this function.
  39230. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  39231. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  39232. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  39233. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  39234. // Compute final values by multiplying with 1/det
  39235. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  39236. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  39237. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  39238. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  39239. return this;
  39240. };
  39241. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  39242. var out = result.m;
  39243. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  39244. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  39245. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  39246. // cc.kmVec3Subtract(f, pCenter, pEye);
  39247. var f = SIMD.Float32x4.sub(center, eye);
  39248. // cc.kmVec3Normalize(f, f);
  39249. var tmp = SIMD.Float32x4.mul(f, f);
  39250. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39251. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39252. // cc.kmVec3Assign(up, pUp);
  39253. // cc.kmVec3Normalize(up, up);
  39254. tmp = SIMD.Float32x4.mul(up, up);
  39255. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39256. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39257. // cc.kmVec3Cross(s, f, up);
  39258. 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)));
  39259. // cc.kmVec3Normalize(s, s);
  39260. tmp = SIMD.Float32x4.mul(s, s);
  39261. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39262. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39263. // cc.kmVec3Cross(u, s, f);
  39264. 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)));
  39265. // cc.kmVec3Normalize(s, s);
  39266. tmp = SIMD.Float32x4.mul(s, s);
  39267. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39268. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39269. var zero = SIMD.Float32x4.splat(0.0);
  39270. s = SIMD.Float32x4.neg(s);
  39271. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  39272. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  39273. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  39274. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  39275. 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);
  39276. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  39277. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  39278. 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)))));
  39279. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  39280. 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)))));
  39281. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  39282. 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)))));
  39283. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  39284. 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)))));
  39285. };
  39286. return SIMDMatrix;
  39287. }());
  39288. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  39289. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  39290. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  39291. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  39292. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  39293. var SIMDHelper = (function () {
  39294. function SIMDHelper() {
  39295. }
  39296. Object.defineProperty(SIMDHelper, "IsEnabled", {
  39297. get: function () {
  39298. return SIMDHelper._isEnabled;
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. SIMDHelper.DisableSIMD = function () {
  39304. // Replace functions
  39305. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  39306. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  39307. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  39308. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  39309. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  39310. SIMDHelper._isEnabled = false;
  39311. };
  39312. SIMDHelper.EnableSIMD = function () {
  39313. if (self.SIMD === undefined) {
  39314. return;
  39315. }
  39316. // check if polyfills needed
  39317. if (!self.Math.fround) {
  39318. self.Math.fround = (function (array) { return function (x) {
  39319. return array[0] = x, array[0];
  39320. }; })(new Float32Array(1));
  39321. }
  39322. if (!self.Math.imul) {
  39323. self.Math.imul = function (a, b) {
  39324. var ah = (a >>> 16) & 0xffff;
  39325. var al = a & 0xffff;
  39326. var bh = (b >>> 16) & 0xffff;
  39327. var bl = b & 0xffff;
  39328. // the shift by 0 fixes the sign on the high part
  39329. // the final |0 converts the unsigned value into a signed value
  39330. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  39331. };
  39332. }
  39333. // Replace functions
  39334. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  39335. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  39336. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  39337. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  39338. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  39339. SIMDHelper._isEnabled = true;
  39340. };
  39341. SIMDHelper._isEnabled = false;
  39342. return SIMDHelper;
  39343. }());
  39344. BABYLON.SIMDHelper = SIMDHelper;
  39345. })(BABYLON || (BABYLON = {}));
  39346. //# sourceMappingURL=babylon.math.SIMD.js.map
  39347. var BABYLON;
  39348. (function (BABYLON) {
  39349. /**
  39350. * This class describe a rectangle that were added to the map.
  39351. * You have access to its coordinates either in pixel or normalized (UV)
  39352. */
  39353. var PackedRect = (function () {
  39354. function PackedRect(root, parent, pos, size) {
  39355. this._pos = pos;
  39356. this._size = size;
  39357. this._root = root;
  39358. this._parent = parent;
  39359. this._contentSize = null;
  39360. this._bottomNode = null;
  39361. this._leftNode = null;
  39362. this._initialSize = null;
  39363. this._rightNode = null;
  39364. }
  39365. Object.defineProperty(PackedRect.prototype, "pos", {
  39366. /**
  39367. * @returns the position of this node into the map
  39368. */
  39369. get: function () {
  39370. return this._pos;
  39371. },
  39372. enumerable: true,
  39373. configurable: true
  39374. });
  39375. Object.defineProperty(PackedRect.prototype, "contentSize", {
  39376. /**
  39377. * @returns the size of the rectangle this node handles
  39378. */
  39379. get: function () {
  39380. return this._contentSize;
  39381. },
  39382. enumerable: true,
  39383. configurable: true
  39384. });
  39385. Object.defineProperty(PackedRect.prototype, "UVs", {
  39386. /**
  39387. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  39388. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  39389. */
  39390. get: function () {
  39391. return this.getUVsForCustomSize(this._root._size);
  39392. },
  39393. enumerable: true,
  39394. configurable: true
  39395. });
  39396. /**
  39397. * 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.
  39398. * This method will return the UVs for this part by given the custom size of what you really use
  39399. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  39400. */
  39401. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  39402. var mainWidth = this._root._size.width;
  39403. var mainHeight = this._root._size.height;
  39404. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  39405. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  39406. var uvs = new Array();
  39407. uvs.push(topLeft);
  39408. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  39409. uvs.push(rightBottom);
  39410. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  39411. return uvs;
  39412. };
  39413. /**
  39414. * Free this rectangle from the map.
  39415. * Call this method when you no longer need the rectangle to be in the map.
  39416. */
  39417. PackedRect.prototype.freeContent = function () {
  39418. if (!this.contentSize) {
  39419. return;
  39420. }
  39421. this._contentSize = null;
  39422. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  39423. this.attemptDefrag();
  39424. };
  39425. Object.defineProperty(PackedRect.prototype, "isUsed", {
  39426. get: function () {
  39427. return this._contentSize != null || this._leftNode != null;
  39428. },
  39429. enumerable: true,
  39430. configurable: true
  39431. });
  39432. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  39433. var node = this.findNode(contentSize);
  39434. // Not enough space...
  39435. if (!node) {
  39436. return null;
  39437. }
  39438. node.splitNode(contentSize);
  39439. return node;
  39440. };
  39441. PackedRect.prototype.findNode = function (size) {
  39442. var resNode = null;
  39443. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  39444. if (this.isUsed) {
  39445. if (this._leftNode) {
  39446. resNode = this._leftNode.findNode(size);
  39447. }
  39448. if (!resNode && this._rightNode) {
  39449. resNode = this._rightNode.findNode(size);
  39450. }
  39451. if (!resNode && this._bottomNode) {
  39452. resNode = this._bottomNode.findNode(size);
  39453. }
  39454. }
  39455. else if (this._initialSize) {
  39456. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  39457. resNode = this;
  39458. }
  39459. else {
  39460. return null;
  39461. }
  39462. }
  39463. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  39464. resNode = this;
  39465. }
  39466. return resNode;
  39467. };
  39468. PackedRect.prototype.splitNode = function (contentSize) {
  39469. // 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)
  39470. if (!this._contentSize && this._initialSize) {
  39471. this._contentSize = contentSize.clone();
  39472. 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));
  39473. return this._leftNode.splitNode(contentSize);
  39474. }
  39475. else {
  39476. this._contentSize = contentSize.clone();
  39477. this._initialSize = contentSize.clone();
  39478. if (contentSize.width !== this._size.width) {
  39479. 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));
  39480. }
  39481. if (contentSize.height !== this._size.height) {
  39482. 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));
  39483. }
  39484. return this;
  39485. }
  39486. };
  39487. PackedRect.prototype.attemptDefrag = function () {
  39488. if (!this.isUsed && this.isRecursiveFree) {
  39489. this.clearNode();
  39490. if (this._parent) {
  39491. this._parent.attemptDefrag();
  39492. }
  39493. }
  39494. };
  39495. PackedRect.prototype.clearNode = function () {
  39496. this._initialSize = null;
  39497. this._rightNode = null;
  39498. this._bottomNode = null;
  39499. };
  39500. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  39501. get: function () {
  39502. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  39503. },
  39504. enumerable: true,
  39505. configurable: true
  39506. });
  39507. PackedRect.prototype.evalFreeSize = function (size) {
  39508. var levelSize = 0;
  39509. if (!this.isUsed) {
  39510. if (this._initialSize) {
  39511. levelSize = this._initialSize.surface;
  39512. }
  39513. else {
  39514. levelSize = this._size.surface;
  39515. }
  39516. }
  39517. if (this._rightNode) {
  39518. levelSize += this._rightNode.evalFreeSize(0);
  39519. }
  39520. if (this._bottomNode) {
  39521. levelSize += this._bottomNode.evalFreeSize(0);
  39522. }
  39523. return levelSize + size;
  39524. };
  39525. return PackedRect;
  39526. }());
  39527. BABYLON.PackedRect = PackedRect;
  39528. /**
  39529. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  39530. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  39531. * 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.
  39532. */
  39533. var RectPackingMap = (function (_super) {
  39534. __extends(RectPackingMap, _super);
  39535. /**
  39536. * Create an instance of the object with a dimension using the given size
  39537. * @param size The dimension of the rectangle that will contain all the sub ones.
  39538. */
  39539. function RectPackingMap(size) {
  39540. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  39541. this._root = this;
  39542. }
  39543. /**
  39544. * Add a rectangle, finding the best location to store it into the map
  39545. * @param size the dimension of the rectangle to store
  39546. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  39547. */
  39548. RectPackingMap.prototype.addRect = function (size) {
  39549. var node = this.findAndSplitNode(size);
  39550. return node;
  39551. };
  39552. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  39553. /**
  39554. * Return the current space free normalized between [0;1]
  39555. * @returns {}
  39556. */
  39557. get: function () {
  39558. var freeSize = 0;
  39559. freeSize = this.evalFreeSize(freeSize);
  39560. return freeSize / (this._size.width * this._size.height);
  39561. },
  39562. enumerable: true,
  39563. configurable: true
  39564. });
  39565. return RectPackingMap;
  39566. }(PackedRect));
  39567. BABYLON.RectPackingMap = RectPackingMap;
  39568. })(BABYLON || (BABYLON = {}));
  39569. //# sourceMappingURL=babylon.rectPackingMap.js.map
  39570. var BABYLON;
  39571. (function (BABYLON) {
  39572. var DynamicFloatArrayElementInfo = (function () {
  39573. function DynamicFloatArrayElementInfo() {
  39574. }
  39575. return DynamicFloatArrayElementInfo;
  39576. }());
  39577. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  39578. /**
  39579. * 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.
  39580. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  39581. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  39582. * 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.
  39583. * 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.
  39584. * 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".
  39585. */
  39586. var DynamicFloatArray = (function () {
  39587. /**
  39588. * Construct an instance of the dynamic float array
  39589. * @param stride size of one element in float (i.e. not bytes!)
  39590. * @param initialElementCount the number of available entries at construction
  39591. */
  39592. function DynamicFloatArray(stride, initialElementCount) {
  39593. this.compareValueOffset = null;
  39594. this.sortingAscending = true;
  39595. this._stride = stride;
  39596. this.buffer = new Float32Array(stride * initialElementCount);
  39597. this._lastUsed = 0;
  39598. this._firstFree = 0;
  39599. this._allEntries = new Array(initialElementCount);
  39600. this._freeEntries = new Array(initialElementCount);
  39601. for (var i = 0; i < initialElementCount; i++) {
  39602. var element = new DynamicFloatArrayElementInfo();
  39603. element.offset = i * stride;
  39604. this._allEntries[i] = element;
  39605. this._freeEntries[initialElementCount - i - 1] = element;
  39606. }
  39607. }
  39608. /**
  39609. * Allocate an element in the array.
  39610. * @return the element info instance that contains the offset into the main buffer of the element's location.
  39611. * Beware, this offset may change when you call pack()
  39612. */
  39613. DynamicFloatArray.prototype.allocElement = function () {
  39614. if (this._freeEntries.length === 0) {
  39615. this._growBuffer();
  39616. }
  39617. var el = this._freeEntries.pop();
  39618. this._lastUsed = Math.max(el.offset, this._lastUsed);
  39619. if (el.offset === this._firstFree) {
  39620. if (this._freeEntries.length > 0) {
  39621. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  39622. }
  39623. else {
  39624. this._firstFree += this._stride;
  39625. }
  39626. }
  39627. return el;
  39628. };
  39629. /**
  39630. * Free the element corresponding to the given element info
  39631. * @param elInfo the element that describe the allocated element
  39632. */
  39633. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  39634. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  39635. this._freeEntries.push(elInfo);
  39636. };
  39637. /**
  39638. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  39639. * 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().
  39640. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  39641. */
  39642. DynamicFloatArray.prototype.pack = function () {
  39643. // no free slot? no need to pack
  39644. if (this._freeEntries.length === 0) {
  39645. return this.buffer;
  39646. }
  39647. // If the buffer is already packed the last used will always be lower than the first free
  39648. // 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.
  39649. if (this._lastUsed < this._firstFree) {
  39650. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  39651. return elementsBuffer_1;
  39652. }
  39653. var s = this._stride;
  39654. // 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
  39655. var lastFree = new DynamicFloatArrayElementInfo();
  39656. lastFree.offset = this.totalElementCount * s;
  39657. this._freeEntries.push(lastFree);
  39658. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  39659. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39660. var firstFreeSlotOffset = sortedFree[0].offset;
  39661. var freeZoneSize = 1;
  39662. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  39663. var prevOffset = sortedFree[0].offset;
  39664. for (var i = 1; i < sortedFree.length; i++) {
  39665. // 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
  39666. if (firstFreeSlotOffset >= occupiedZoneSize) {
  39667. break;
  39668. }
  39669. var curFree = sortedFree[i];
  39670. var curOffset = curFree.offset;
  39671. // Compute the distance between this offset and the previous
  39672. var distance = curOffset - prevOffset;
  39673. // If the distance is the stride size, they are adjacent, it good, move to the next
  39674. if (distance === s) {
  39675. // Free zone is one element bigger
  39676. ++freeZoneSize;
  39677. // as we're about to iterate to the next, the cur becomes the previous...
  39678. prevOffset = curOffset;
  39679. continue;
  39680. }
  39681. // Distance is bigger, which means there's x element between the previous free and this one
  39682. var usedRange = (distance / s) - 1;
  39683. // Two cases the free zone is smaller than the data to move or bigger
  39684. // Copy what can fit in the free zone
  39685. var curMoveOffset = curOffset - s;
  39686. var copyCount = Math.min(freeZoneSize, usedRange);
  39687. for (var j = 0; j < copyCount; j++) {
  39688. var freeI = firstFreeSlotOffset / s;
  39689. var curI = curMoveOffset / s;
  39690. var moveEl = sortedAll[curI];
  39691. this._moveElement(moveEl, firstFreeSlotOffset);
  39692. var replacedEl = sortedAll[freeI];
  39693. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  39694. replacedEl.offset = curMoveOffset;
  39695. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  39696. sortedAll[freeI] = moveEl;
  39697. sortedAll[curI] = replacedEl;
  39698. curMoveOffset -= s;
  39699. firstFreeSlotOffset += s;
  39700. }
  39701. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  39702. if (freeZoneSize <= usedRange) {
  39703. firstFreeSlotOffset = curMoveOffset + s;
  39704. freeZoneSize = 1 + copyCount;
  39705. }
  39706. else {
  39707. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  39708. }
  39709. // as we're about to iterate to the next, the cur becomes the previous...
  39710. prevOffset = curOffset;
  39711. }
  39712. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  39713. this._lastUsed = firstFreeSlotOffset - s;
  39714. this._firstFree = firstFreeSlotOffset;
  39715. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  39716. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  39717. this._allEntries = sortedAll;
  39718. return elementsBuffer;
  39719. };
  39720. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  39721. for (var i = 0; i < this._stride; i++) {
  39722. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  39723. }
  39724. element.offset = destOffset;
  39725. };
  39726. DynamicFloatArray.prototype._growBuffer = function () {
  39727. // Allocate the new buffer with 50% more entries, copy the content of the current one
  39728. var newElCount = Math.floor(this.totalElementCount * 1.5);
  39729. var newBuffer = new Float32Array(newElCount * this._stride);
  39730. newBuffer.set(this.buffer);
  39731. var curCount = this.totalElementCount;
  39732. var addedCount = newElCount - this.totalElementCount;
  39733. for (var i = 0; i < addedCount; i++) {
  39734. var element = new DynamicFloatArrayElementInfo();
  39735. element.offset = (curCount + i) * this.stride;
  39736. this._allEntries.push(element);
  39737. this._freeEntries[addedCount - i - 1] = element;
  39738. }
  39739. this._firstFree = curCount * this.stride;
  39740. this.buffer = newBuffer;
  39741. };
  39742. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  39743. /**
  39744. * Get the total count of entries that can fit in the current buffer
  39745. * @returns the elements count
  39746. */
  39747. get: function () {
  39748. return this._allEntries.length;
  39749. },
  39750. enumerable: true,
  39751. configurable: true
  39752. });
  39753. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  39754. /**
  39755. * Get the count of free entries that can still be allocated without resizing the buffer
  39756. * @returns the free elements count
  39757. */
  39758. get: function () {
  39759. return this._freeEntries.length;
  39760. },
  39761. enumerable: true,
  39762. configurable: true
  39763. });
  39764. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  39765. /**
  39766. * Get the count of allocated elements
  39767. * @returns the allocated elements count
  39768. */
  39769. get: function () {
  39770. return this._allEntries.length - this._freeEntries.length;
  39771. },
  39772. enumerable: true,
  39773. configurable: true
  39774. });
  39775. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  39776. /**
  39777. * Return the size of one element in float
  39778. * @returns the size in float
  39779. */
  39780. get: function () {
  39781. return this._stride;
  39782. },
  39783. enumerable: true,
  39784. configurable: true
  39785. });
  39786. DynamicFloatArray.prototype.sort = function () {
  39787. var _this = this;
  39788. if (!this.compareValueOffset) {
  39789. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  39790. }
  39791. var count = this.usedElementCount;
  39792. // Do we have to (re)create the sort table?
  39793. if (!this._sortTable || this._sortTable.length < count) {
  39794. // 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...
  39795. var newCount = Math.min(this.totalElementCount, count * 2);
  39796. this._sortTable = new Array(newCount);
  39797. }
  39798. if (!this._sortedTable || this._sortedTable.length !== count) {
  39799. this._sortedTable = new Array(count);
  39800. }
  39801. // Because, you know...
  39802. this.pack();
  39803. //let stride = this.stride;
  39804. //for (let i = 0; i < count; i++) {
  39805. // let si = this._sortTable[i];
  39806. // if (!si) {
  39807. // si = new SortInfo();
  39808. // this._sortTable[i] = si;
  39809. // }
  39810. // si.entry = this._allEntries[i];
  39811. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  39812. // si.swapedOffset = null;
  39813. // this._sortedTable[i] = si;
  39814. //}
  39815. var curOffset = 0;
  39816. var stride = this.stride;
  39817. for (var i = 0; i < count; i++, curOffset += stride) {
  39818. var si = this._sortTable[i];
  39819. if (!si) {
  39820. si = new SortInfo();
  39821. this._sortTable[i] = si;
  39822. }
  39823. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  39824. si.offset = curOffset;
  39825. si.swapedOffset = null;
  39826. this._sortedTable[i] = si;
  39827. }
  39828. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  39829. if (this.sortingAscending) {
  39830. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  39831. }
  39832. else {
  39833. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  39834. }
  39835. var swapElements = function (src, dst) {
  39836. for (var i = 0; i < stride; i++) {
  39837. var tps = _this.buffer[dst + i];
  39838. _this.buffer[dst + i] = _this.buffer[src + i];
  39839. _this.buffer[src + i] = tps;
  39840. }
  39841. };
  39842. // 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:
  39843. // 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),
  39844. // and I still want something with a good algorithm complexity.
  39845. // 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,
  39846. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  39847. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  39848. // 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
  39849. // until we find a SortInfo object without a swapedOffset which means we got the right location
  39850. // 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
  39851. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  39852. for (var i = 0; i < count; i++) {
  39853. // Get the element to move
  39854. var sourceSI = this._sortedTable[i];
  39855. var destSI = this._sortTable[i];
  39856. var sourceOff = sourceSI.offset;
  39857. // If the source changed location, find the new one
  39858. if (sourceSI.swapedOffset) {
  39859. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  39860. var curSI = sourceSI;
  39861. while (curSI.swapedOffset) {
  39862. curSI = this._sortTable[curSI.swapedOffset / stride];
  39863. }
  39864. // Finally get the right location
  39865. sourceOff = curSI.offset;
  39866. }
  39867. // Tag the element being replaced with its new location
  39868. destSI.swapedOffset = sourceOff;
  39869. // Swap elements (only if needed)
  39870. if (sourceOff !== destSI.offset) {
  39871. swapElements(sourceOff, destSI.offset);
  39872. }
  39873. // Update the offset in the corresponding DFAE
  39874. //sourceSI.entry.offset = destSI.entry.offset;
  39875. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  39876. }
  39877. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39878. return true;
  39879. };
  39880. return DynamicFloatArray;
  39881. }());
  39882. BABYLON.DynamicFloatArray = DynamicFloatArray;
  39883. var SortInfo = (function () {
  39884. function SortInfo() {
  39885. this.compareData = this.offset = this.swapedOffset = null;
  39886. }
  39887. return SortInfo;
  39888. }());
  39889. })(BABYLON || (BABYLON = {}));
  39890. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  39891. var BABYLON;
  39892. (function (BABYLON) {
  39893. /**
  39894. * This class given information about a given character.
  39895. */
  39896. var CharInfo = (function () {
  39897. function CharInfo() {
  39898. }
  39899. return CharInfo;
  39900. }());
  39901. BABYLON.CharInfo = CharInfo;
  39902. var FontTexture = (function (_super) {
  39903. __extends(FontTexture, _super);
  39904. /**
  39905. * Create a new instance of the FontTexture class
  39906. * @param name the name of the texture
  39907. * @param font the font to use, use the W3C CSS notation
  39908. * @param scene the scene that owns the texture
  39909. * @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
  39910. * @param samplingMode the texture sampling mode
  39911. * @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.
  39912. */
  39913. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  39914. if (maxCharCount === void 0) { maxCharCount = 200; }
  39915. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39916. if (superSample === void 0) { superSample = false; }
  39917. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39918. _super.call(this, null, scene, true, false, samplingMode);
  39919. this._charInfos = {};
  39920. this._curCharCount = 0;
  39921. this._lastUpdateCharCount = -1;
  39922. this._usedCounter = 1;
  39923. this.name = name;
  39924. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39925. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39926. this._sdfScale = 8;
  39927. this._signedDistanceField = signedDistanceField;
  39928. this._superSample = false;
  39929. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  39930. if (superSample || signedDistanceField) {
  39931. var sfont = this.getSuperSampleFont(font);
  39932. if (sfont) {
  39933. this._superSample = true;
  39934. font = sfont;
  39935. }
  39936. }
  39937. // First canvas creation to determine the size of the texture to create
  39938. this._canvas = document.createElement("canvas");
  39939. this._context = this._canvas.getContext("2d");
  39940. this._context.font = font;
  39941. this._context.fillStyle = "white";
  39942. this._context.textBaseline = "top";
  39943. this._cachedFontId = null;
  39944. var res = this.getFontHeight(font);
  39945. this._lineHeightSuper = res.height + 4;
  39946. this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;
  39947. this._offset = res.offset - 1;
  39948. this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  39949. this._yMargin = this._xMargin;
  39950. var maxCharWidth = this._context.measureText("W").width;
  39951. this._spaceWidthSuper = this._context.measureText(" ").width;
  39952. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  39953. // This is an approximate size, but should always be able to fit at least the maxCharCount
  39954. var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;
  39955. var edge = Math.sqrt(totalEstSurface);
  39956. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  39957. // Create the texture that will store the font characters
  39958. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  39959. var textureSize = this.getSize();
  39960. this.hasAlpha = this._signedDistanceField === false;
  39961. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  39962. this._canvas = document.createElement("canvas");
  39963. this._canvas.width = textureSize.width;
  39964. this._canvas.height = textureSize.height;
  39965. this._context = this._canvas.getContext("2d");
  39966. this._context.textBaseline = "top";
  39967. this._context.font = font;
  39968. this._context.fillStyle = "white";
  39969. this._context.imageSmoothingEnabled = false;
  39970. this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  39971. // 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
  39972. // 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)
  39973. // So you can see this context as an intermediate one, because it is.
  39974. if (this._signedDistanceField) {
  39975. var sdfC = document.createElement("canvas");
  39976. var s = this._sdfScale;
  39977. sdfC.width = maxCharWidth * s;
  39978. sdfC.height = this._lineHeightSuper * s;
  39979. var sdfCtx = sdfC.getContext("2d");
  39980. sdfCtx.scale(s, s);
  39981. sdfCtx.textBaseline = "top";
  39982. sdfCtx.font = font;
  39983. sdfCtx.fillStyle = "white";
  39984. sdfCtx.imageSmoothingEnabled = false;
  39985. this._sdfCanvas = sdfC;
  39986. this._sdfContext = sdfCtx;
  39987. }
  39988. this._currentFreePosition = BABYLON.Vector2.Zero();
  39989. // Add the basic ASCII based characters
  39990. for (var i = 0x20; i < 0x7F; i++) {
  39991. var c = String.fromCharCode(i);
  39992. this.getChar(c);
  39993. }
  39994. this.update();
  39995. }
  39996. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  39997. get: function () {
  39998. return this._superSample;
  39999. },
  40000. enumerable: true,
  40001. configurable: true
  40002. });
  40003. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  40004. get: function () {
  40005. return this._signedDistanceField;
  40006. },
  40007. enumerable: true,
  40008. configurable: true
  40009. });
  40010. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  40011. get: function () {
  40012. return this._spaceWidth;
  40013. },
  40014. enumerable: true,
  40015. configurable: true
  40016. });
  40017. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  40018. get: function () {
  40019. return this._lineHeight;
  40020. },
  40021. enumerable: true,
  40022. configurable: true
  40023. });
  40024. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40025. if (supersample === void 0) { supersample = false; }
  40026. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40027. var s = scene;
  40028. if (!s.__fontTextureCache__) {
  40029. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  40030. }
  40031. var dic = s.__fontTextureCache__;
  40032. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40033. var ft = dic.get(lfn);
  40034. if (ft) {
  40035. ++ft._usedCounter;
  40036. return ft;
  40037. }
  40038. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  40039. ft._cachedFontId = lfn;
  40040. dic.add(lfn, ft);
  40041. return ft;
  40042. };
  40043. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40044. if (supersample === void 0) { supersample = false; }
  40045. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40046. var s = scene;
  40047. var dic = s.__fontTextureCache__;
  40048. if (!dic) {
  40049. return;
  40050. }
  40051. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40052. var font = dic.get(lfn);
  40053. if (--font._usedCounter === 0) {
  40054. dic.remove(lfn);
  40055. font.dispose();
  40056. }
  40057. };
  40058. /**
  40059. * Make sure the given char is present in the font map.
  40060. * @param char the character to get or add
  40061. * @return the CharInfo instance corresponding to the given character
  40062. */
  40063. FontTexture.prototype.getChar = function (char) {
  40064. if (char.length !== 1) {
  40065. return null;
  40066. }
  40067. var info = this._charInfos[char];
  40068. if (info) {
  40069. return info;
  40070. }
  40071. info = new CharInfo();
  40072. var measure = this._context.measureText(char);
  40073. var textureSize = this.getSize();
  40074. // we reached the end of the current line?
  40075. var width = Math.round(measure.width);
  40076. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  40077. this._currentFreePosition.x = 0;
  40078. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  40079. // No more room?
  40080. if (this._currentFreePosition.y > textureSize.height) {
  40081. return this.getChar("!");
  40082. }
  40083. }
  40084. // 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)
  40085. if (this._signedDistanceField) {
  40086. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  40087. this._sdfContext.fillText(char, 0, -this._offset);
  40088. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  40089. var res = this._computeSDFChar(data);
  40090. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  40091. }
  40092. else {
  40093. // Draw the character in the HTML canvas
  40094. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  40095. }
  40096. // Fill the CharInfo object
  40097. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  40098. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  40099. if (this._signedDistanceField) {
  40100. var off = 1 / textureSize.width;
  40101. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  40102. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  40103. }
  40104. info.charWidth = this._superSample ? (width / 2) : width;
  40105. // Add the info structure
  40106. this._charInfos[char] = info;
  40107. this._curCharCount++;
  40108. // Set the next position
  40109. this._currentFreePosition.x += width + this._xMargin;
  40110. return info;
  40111. };
  40112. FontTexture.prototype._computeSDFChar = function (source) {
  40113. var scl = this._sdfScale;
  40114. var sw = source.width;
  40115. var sh = source.height;
  40116. var dw = sw / scl;
  40117. var dh = sh / scl;
  40118. var roffx = 0;
  40119. var roffy = 0;
  40120. // We shouldn't look beyond half of the biggest between width and height
  40121. var radius = scl;
  40122. var br = radius - 1;
  40123. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  40124. var sx = dx * scl;
  40125. var sy = dy * scl;
  40126. // Looking out of the area? return true to make the test going on
  40127. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  40128. return true;
  40129. }
  40130. // Get the pixel we want
  40131. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  40132. var res = (val > 0) === lookVis;
  40133. if (!res) {
  40134. roffx = offX;
  40135. roffy = offY;
  40136. }
  40137. return res;
  40138. };
  40139. var lookupArea = function (dx, dy, lookVis) {
  40140. // 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
  40141. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  40142. lookupSrc(dx, dy, 0, -br, lookVis) &&
  40143. lookupSrc(dx, dy, -br, 0, lookVis) &&
  40144. lookupSrc(dx, dy, br, 0, lookVis)) {
  40145. return 0;
  40146. }
  40147. for (var i = 1; i <= radius; i++) {
  40148. // Quick test N, S, W, E
  40149. 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)) {
  40150. return i * i; // Squared Distance is simple to compute in this case
  40151. }
  40152. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  40153. for (var j = 1; j <= i; j++) {
  40154. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  40155. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  40156. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  40157. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  40158. // We found the nearest texel having and opposite state, store the squared length
  40159. var res_1 = (i * i) + (j * j);
  40160. var count = 1;
  40161. // 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
  40162. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  40163. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  40164. ++count;
  40165. }
  40166. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  40167. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  40168. ++count;
  40169. }
  40170. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  40171. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  40172. ++count;
  40173. }
  40174. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  40175. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  40176. ++count;
  40177. }
  40178. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  40179. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  40180. ++count;
  40181. }
  40182. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  40183. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  40184. ++count;
  40185. }
  40186. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  40187. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  40188. ++count;
  40189. }
  40190. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  40191. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  40192. ++count;
  40193. }
  40194. // Compute the average based on the accumulated distance
  40195. return res_1 / count;
  40196. }
  40197. }
  40198. }
  40199. return 0;
  40200. };
  40201. var tmp = new Array(dw * dh);
  40202. for (var y = 0; y < dh; y++) {
  40203. for (var x = 0; x < dw; x++) {
  40204. var curState = lookupSrc(x, y, 0, 0, true);
  40205. var d = lookupArea(x, y, curState);
  40206. if (d === 0) {
  40207. d = radius * radius * 2;
  40208. }
  40209. tmp[(y * dw) + x] = curState ? d : -d;
  40210. }
  40211. }
  40212. var res = this._context.createImageData(dw, dh);
  40213. var size = dw * dh;
  40214. for (var j = 0; j < size; j++) {
  40215. var d = tmp[j];
  40216. var sign = (d < 0) ? -1 : 1;
  40217. d = Math.sqrt(Math.abs(d)) * sign;
  40218. d *= 127.5 / radius;
  40219. d += 127.5;
  40220. if (d < 0) {
  40221. d = 0;
  40222. }
  40223. else if (d > 255) {
  40224. d = 255;
  40225. }
  40226. d += 0.5;
  40227. res.data[j * 4 + 0] = d;
  40228. res.data[j * 4 + 1] = d;
  40229. res.data[j * 4 + 2] = d;
  40230. res.data[j * 4 + 3] = 255;
  40231. }
  40232. return res;
  40233. };
  40234. FontTexture.prototype.measureText = function (text, tabulationSize) {
  40235. if (tabulationSize === void 0) { tabulationSize = 4; }
  40236. var maxWidth = 0;
  40237. var curWidth = 0;
  40238. var lineCount = 1;
  40239. var charxpos = 0;
  40240. // Parse each char of the string
  40241. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  40242. var char = text_1[_i];
  40243. // Next line feed?
  40244. if (char === "\n") {
  40245. maxWidth = Math.max(maxWidth, curWidth);
  40246. charxpos = 0;
  40247. curWidth = 0;
  40248. ++lineCount;
  40249. continue;
  40250. }
  40251. // Tabulation ?
  40252. if (char === "\t") {
  40253. var nextPos = charxpos + tabulationSize;
  40254. nextPos = nextPos - (nextPos % tabulationSize);
  40255. curWidth += (nextPos - charxpos) * this.spaceWidth;
  40256. charxpos = nextPos;
  40257. continue;
  40258. }
  40259. if (char < " ") {
  40260. continue;
  40261. }
  40262. curWidth += this.getChar(char).charWidth;
  40263. ++charxpos;
  40264. }
  40265. maxWidth = Math.max(maxWidth, curWidth);
  40266. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  40267. };
  40268. FontTexture.prototype.getSuperSampleFont = function (font) {
  40269. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  40270. 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*$/;
  40271. var res = font.toLocaleLowerCase().match(regex);
  40272. if (res == null) {
  40273. return null;
  40274. }
  40275. var size = parseInt(res[4]);
  40276. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  40277. var newFont = "";
  40278. for (var j = 1; j < res.length; j++) {
  40279. if (res[j] != null) {
  40280. newFont += res[j] + " ";
  40281. }
  40282. }
  40283. return newFont;
  40284. };
  40285. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  40286. FontTexture.prototype.getFontHeight = function (font) {
  40287. var fontDraw = document.createElement("canvas");
  40288. var ctx = fontDraw.getContext('2d');
  40289. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  40290. ctx.textBaseline = 'top';
  40291. ctx.fillStyle = 'white';
  40292. ctx.font = font;
  40293. ctx.fillText('jH|', 0, 0);
  40294. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  40295. var start = -1;
  40296. var end = -1;
  40297. for (var row = 0; row < fontDraw.height; row++) {
  40298. for (var column = 0; column < fontDraw.width; column++) {
  40299. var index = (row * fontDraw.width + column) * 4;
  40300. if (pixels[index] === 0) {
  40301. if (column === fontDraw.width - 1 && start !== -1) {
  40302. end = row;
  40303. row = fontDraw.height;
  40304. break;
  40305. }
  40306. continue;
  40307. }
  40308. else {
  40309. if (start === -1) {
  40310. start = row;
  40311. }
  40312. break;
  40313. }
  40314. }
  40315. }
  40316. return { height: (end - start) + 1, offset: start - 1 };
  40317. };
  40318. Object.defineProperty(FontTexture.prototype, "canRescale", {
  40319. get: function () {
  40320. return false;
  40321. },
  40322. enumerable: true,
  40323. configurable: true
  40324. });
  40325. FontTexture.prototype.getContext = function () {
  40326. return this._context;
  40327. };
  40328. /**
  40329. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  40330. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  40331. */
  40332. FontTexture.prototype.update = function () {
  40333. // Update only if there's new char added since the previous update
  40334. if (this._lastUpdateCharCount < this._curCharCount) {
  40335. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  40336. this._lastUpdateCharCount = this._curCharCount;
  40337. }
  40338. };
  40339. // cloning should be prohibited, there's no point to duplicate this texture at all
  40340. FontTexture.prototype.clone = function () {
  40341. return null;
  40342. };
  40343. /**
  40344. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  40345. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  40346. */
  40347. FontTexture.prototype.incCachedFontTextureCounter = function () {
  40348. ++this._usedCounter;
  40349. };
  40350. /**
  40351. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  40352. */
  40353. FontTexture.prototype.decCachedFontTextureCounter = function () {
  40354. var s = this.getScene();
  40355. var dic = s.__fontTextureCache__;
  40356. if (!dic) {
  40357. return;
  40358. }
  40359. if (--this._usedCounter === 0) {
  40360. dic.remove(this._cachedFontId);
  40361. this.dispose();
  40362. }
  40363. };
  40364. return FontTexture;
  40365. }(BABYLON.Texture));
  40366. BABYLON.FontTexture = FontTexture;
  40367. })(BABYLON || (BABYLON = {}));
  40368. //# sourceMappingURL=babylon.fontTexture.js.map
  40369. var BABYLON;
  40370. (function (BABYLON) {
  40371. var MapTexture = (function (_super) {
  40372. __extends(MapTexture, _super);
  40373. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40374. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40375. if (useMipMap === void 0) { useMipMap = false; }
  40376. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  40377. this.name = name;
  40378. this._size = size;
  40379. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40380. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40381. // Create the rectPackMap that will allocate portion of the texture
  40382. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40383. // Create the texture that will store the content
  40384. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40385. }
  40386. /**
  40387. * Allocate a rectangle of a given size in the texture map
  40388. * @param size the size of the rectangle to allocation
  40389. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40390. */
  40391. MapTexture.prototype.allocateRect = function (size) {
  40392. return this._rectPackingMap.addRect(size);
  40393. };
  40394. /**
  40395. * Free a given rectangle from the texture map
  40396. * @param rectInfo the instance corresponding to the rect to free.
  40397. */
  40398. MapTexture.prototype.freeRect = function (rectInfo) {
  40399. if (rectInfo) {
  40400. rectInfo.freeContent();
  40401. }
  40402. };
  40403. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40404. /**
  40405. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40406. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40407. * @returns {}
  40408. */
  40409. get: function () {
  40410. return this._rectPackingMap.freeSpace;
  40411. },
  40412. enumerable: true,
  40413. configurable: true
  40414. });
  40415. /**
  40416. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40417. * 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.
  40418. * Don't forget to call unbindTexture when you're done rendering
  40419. * @param rect the zone to render to
  40420. * @param clear true to clear the portion's color/depth data
  40421. */
  40422. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40423. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40424. };
  40425. /**
  40426. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40427. * 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.
  40428. * Don't forget to call unbindTexture when you're done rendering
  40429. * @param pos the position into the texture
  40430. * @param size the portion to fit the clip space to
  40431. * @param clear true to clear the portion's color/depth data
  40432. */
  40433. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40434. var engine = this.getScene().getEngine();
  40435. engine.bindFramebuffer(this._texture);
  40436. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40437. if (clear) {
  40438. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40439. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40440. }
  40441. };
  40442. /**
  40443. * Unbind the texture map from the rendering engine.
  40444. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40445. * @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.
  40446. */
  40447. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40448. // Dump ?
  40449. if (dumpForDebug) {
  40450. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40451. }
  40452. var engine = this.getScene().getEngine();
  40453. if (this._replacedViewport) {
  40454. engine.setViewport(this._replacedViewport);
  40455. this._replacedViewport = null;
  40456. }
  40457. engine.unBindFramebuffer(this._texture);
  40458. };
  40459. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40460. get: function () {
  40461. return false;
  40462. },
  40463. enumerable: true,
  40464. configurable: true
  40465. });
  40466. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40467. // Anyway, there's not much point to use this method for this kind of texture I guess
  40468. MapTexture.prototype.clone = function () {
  40469. return null;
  40470. };
  40471. return MapTexture;
  40472. }(BABYLON.Texture));
  40473. BABYLON.MapTexture = MapTexture;
  40474. })(BABYLON || (BABYLON = {}));
  40475. //# sourceMappingURL=babylon.mapTexture.js.map
  40476. var BABYLON;
  40477. (function (BABYLON) {
  40478. var ShaderMaterial = (function (_super) {
  40479. __extends(ShaderMaterial, _super);
  40480. function ShaderMaterial(name, scene, shaderPath, options) {
  40481. _super.call(this, name, scene);
  40482. this._textures = {};
  40483. this._textureArrays = {};
  40484. this._floats = {};
  40485. this._floatsArrays = {};
  40486. this._colors3 = {};
  40487. this._colors4 = {};
  40488. this._vectors2 = {};
  40489. this._vectors3 = {};
  40490. this._vectors4 = {};
  40491. this._matrices = {};
  40492. this._matrices3x3 = {};
  40493. this._matrices2x2 = {};
  40494. this._vectors3Arrays = {};
  40495. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40496. this._shaderPath = shaderPath;
  40497. options.needAlphaBlending = options.needAlphaBlending || false;
  40498. options.needAlphaTesting = options.needAlphaTesting || false;
  40499. options.attributes = options.attributes || ["position", "normal", "uv"];
  40500. options.uniforms = options.uniforms || ["worldViewProjection"];
  40501. options.samplers = options.samplers || [];
  40502. options.defines = options.defines || [];
  40503. this._options = options;
  40504. }
  40505. ShaderMaterial.prototype.getClassName = function () {
  40506. return "ShaderMaterial";
  40507. };
  40508. ShaderMaterial.prototype.needAlphaBlending = function () {
  40509. return this._options.needAlphaBlending;
  40510. };
  40511. ShaderMaterial.prototype.needAlphaTesting = function () {
  40512. return this._options.needAlphaTesting;
  40513. };
  40514. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40515. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40516. this._options.uniforms.push(uniformName);
  40517. }
  40518. };
  40519. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40520. if (this._options.samplers.indexOf(name) === -1) {
  40521. this._options.samplers.push(name);
  40522. }
  40523. this._textures[name] = texture;
  40524. return this;
  40525. };
  40526. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40527. if (this._options.samplers.indexOf(name) === -1) {
  40528. this._options.samplers.push(name);
  40529. }
  40530. this._checkUniform(name);
  40531. this._textureArrays[name] = textures;
  40532. return this;
  40533. };
  40534. ShaderMaterial.prototype.setFloat = function (name, value) {
  40535. this._checkUniform(name);
  40536. this._floats[name] = value;
  40537. return this;
  40538. };
  40539. ShaderMaterial.prototype.setFloats = function (name, value) {
  40540. this._checkUniform(name);
  40541. this._floatsArrays[name] = value;
  40542. return this;
  40543. };
  40544. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40545. this._checkUniform(name);
  40546. this._colors3[name] = value;
  40547. return this;
  40548. };
  40549. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40550. this._checkUniform(name);
  40551. this._colors4[name] = value;
  40552. return this;
  40553. };
  40554. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40555. this._checkUniform(name);
  40556. this._vectors2[name] = value;
  40557. return this;
  40558. };
  40559. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40560. this._checkUniform(name);
  40561. this._vectors3[name] = value;
  40562. return this;
  40563. };
  40564. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40565. this._checkUniform(name);
  40566. this._vectors4[name] = value;
  40567. return this;
  40568. };
  40569. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40570. this._checkUniform(name);
  40571. this._matrices[name] = value;
  40572. return this;
  40573. };
  40574. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40575. this._checkUniform(name);
  40576. this._matrices3x3[name] = value;
  40577. return this;
  40578. };
  40579. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40580. this._checkUniform(name);
  40581. this._matrices2x2[name] = value;
  40582. return this;
  40583. };
  40584. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40585. this._checkUniform(name);
  40586. this._vectors3Arrays[name] = value;
  40587. return this;
  40588. };
  40589. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40590. if (!mesh) {
  40591. return true;
  40592. }
  40593. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40594. return false;
  40595. }
  40596. return false;
  40597. };
  40598. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40599. var scene = this.getScene();
  40600. var engine = scene.getEngine();
  40601. if (!this.checkReadyOnEveryCall) {
  40602. if (this._renderId === scene.getRenderId()) {
  40603. if (this._checkCache(scene, mesh, useInstances)) {
  40604. return true;
  40605. }
  40606. }
  40607. }
  40608. // Instances
  40609. var defines = [];
  40610. var fallbacks = new BABYLON.EffectFallbacks();
  40611. if (useInstances) {
  40612. defines.push("#define INSTANCES");
  40613. }
  40614. for (var index = 0; index < this._options.defines.length; index++) {
  40615. defines.push(this._options.defines[index]);
  40616. }
  40617. // Bones
  40618. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40619. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40620. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40621. fallbacks.addCPUSkinningFallback(0, mesh);
  40622. }
  40623. // Alpha test
  40624. if (engine.getAlphaTesting()) {
  40625. defines.push("#define ALPHATEST");
  40626. }
  40627. var previousEffect = this._effect;
  40628. var join = defines.join("\n");
  40629. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  40630. if (!this._effect.isReady()) {
  40631. return false;
  40632. }
  40633. if (previousEffect !== this._effect) {
  40634. scene.resetCachedMaterial();
  40635. }
  40636. this._renderId = scene.getRenderId();
  40637. return true;
  40638. };
  40639. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40640. var scene = this.getScene();
  40641. if (this._options.uniforms.indexOf("world") !== -1) {
  40642. this._effect.setMatrix("world", world);
  40643. }
  40644. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40645. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40646. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40647. }
  40648. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40649. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40650. }
  40651. };
  40652. ShaderMaterial.prototype.bind = function (world, mesh) {
  40653. // Std values
  40654. this.bindOnlyWorldMatrix(world);
  40655. if (this.getScene().getCachedMaterial() !== this) {
  40656. if (this._options.uniforms.indexOf("view") !== -1) {
  40657. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40658. }
  40659. if (this._options.uniforms.indexOf("projection") !== -1) {
  40660. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40661. }
  40662. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40663. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40664. }
  40665. // Bones
  40666. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40667. var name;
  40668. // Texture
  40669. for (name in this._textures) {
  40670. this._effect.setTexture(name, this._textures[name]);
  40671. }
  40672. // Texture arrays
  40673. for (name in this._textureArrays) {
  40674. this._effect.setTextureArray(name, this._textureArrays[name]);
  40675. }
  40676. // Float
  40677. for (name in this._floats) {
  40678. this._effect.setFloat(name, this._floats[name]);
  40679. }
  40680. // Float s
  40681. for (name in this._floatsArrays) {
  40682. this._effect.setArray(name, this._floatsArrays[name]);
  40683. }
  40684. // Color3
  40685. for (name in this._colors3) {
  40686. this._effect.setColor3(name, this._colors3[name]);
  40687. }
  40688. // Color4
  40689. for (name in this._colors4) {
  40690. var color = this._colors4[name];
  40691. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40692. }
  40693. // Vector2
  40694. for (name in this._vectors2) {
  40695. this._effect.setVector2(name, this._vectors2[name]);
  40696. }
  40697. // Vector3
  40698. for (name in this._vectors3) {
  40699. this._effect.setVector3(name, this._vectors3[name]);
  40700. }
  40701. // Vector4
  40702. for (name in this._vectors4) {
  40703. this._effect.setVector4(name, this._vectors4[name]);
  40704. }
  40705. // Matrix
  40706. for (name in this._matrices) {
  40707. this._effect.setMatrix(name, this._matrices[name]);
  40708. }
  40709. // Matrix 3x3
  40710. for (name in this._matrices3x3) {
  40711. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40712. }
  40713. // Matrix 2x2
  40714. for (name in this._matrices2x2) {
  40715. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40716. }
  40717. // Vector3Array
  40718. for (name in this._vectors3Arrays) {
  40719. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40720. }
  40721. }
  40722. _super.prototype.bind.call(this, world, mesh);
  40723. };
  40724. ShaderMaterial.prototype.clone = function (name) {
  40725. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40726. return newShaderMaterial;
  40727. };
  40728. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40729. if (forceDisposeTextures) {
  40730. var name;
  40731. for (name in this._textures) {
  40732. this._textures[name].dispose();
  40733. }
  40734. for (name in this._textureArrays) {
  40735. var array = this._textureArrays[name];
  40736. for (var index = 0; index < array.length; index++) {
  40737. array[index].dispose();
  40738. }
  40739. }
  40740. }
  40741. this._textures = {};
  40742. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40743. };
  40744. ShaderMaterial.prototype.serialize = function () {
  40745. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40746. serializationObject.customType = "BABYLON.ShaderMaterial";
  40747. serializationObject.options = this._options;
  40748. serializationObject.shaderPath = this._shaderPath;
  40749. var name;
  40750. // Texture
  40751. serializationObject.textures = {};
  40752. for (name in this._textures) {
  40753. serializationObject.textures[name] = this._textures[name].serialize();
  40754. }
  40755. // Texture arrays
  40756. serializationObject.textureArrays = {};
  40757. for (name in this._textureArrays) {
  40758. serializationObject.textureArrays[name] = [];
  40759. var array = this._textureArrays[name];
  40760. for (var index = 0; index < array.length; index++) {
  40761. serializationObject.textureArrays[name].push(array[index].serialize());
  40762. }
  40763. }
  40764. // Float
  40765. serializationObject.floats = {};
  40766. for (name in this._floats) {
  40767. serializationObject.floats[name] = this._floats[name];
  40768. }
  40769. // Float s
  40770. serializationObject.floatArrays = {};
  40771. for (name in this._floatsArrays) {
  40772. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40773. }
  40774. // Color3
  40775. serializationObject.colors3 = {};
  40776. for (name in this._colors3) {
  40777. serializationObject.colors3[name] = this._colors3[name].asArray();
  40778. }
  40779. // Color4
  40780. serializationObject.colors4 = {};
  40781. for (name in this._colors4) {
  40782. serializationObject.colors4[name] = this._colors4[name].asArray();
  40783. }
  40784. // Vector2
  40785. serializationObject.vectors2 = {};
  40786. for (name in this._vectors2) {
  40787. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40788. }
  40789. // Vector3
  40790. serializationObject.vectors3 = {};
  40791. for (name in this._vectors3) {
  40792. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40793. }
  40794. // Vector4
  40795. serializationObject.vectors4 = {};
  40796. for (name in this._vectors4) {
  40797. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40798. }
  40799. // Matrix
  40800. serializationObject.matrices = {};
  40801. for (name in this._matrices) {
  40802. serializationObject.matrices[name] = this._matrices[name].asArray();
  40803. }
  40804. // Matrix 3x3
  40805. serializationObject.matrices3x3 = {};
  40806. for (name in this._matrices3x3) {
  40807. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40808. }
  40809. // Matrix 2x2
  40810. serializationObject.matrices2x2 = {};
  40811. for (name in this._matrices2x2) {
  40812. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40813. }
  40814. // Vector3Array
  40815. serializationObject.vectors3Arrays = {};
  40816. for (name in this._vectors3Arrays) {
  40817. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40818. }
  40819. return serializationObject;
  40820. };
  40821. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40822. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40823. var name;
  40824. // Texture
  40825. for (name in source.textures) {
  40826. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40827. }
  40828. // Texture arrays
  40829. for (name in source.textureArrays) {
  40830. var array = source.textureArrays[name];
  40831. var textureArray = new Array();
  40832. for (var index = 0; index < array.length; index++) {
  40833. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40834. }
  40835. material.setTextureArray(name, textureArray);
  40836. }
  40837. // Float
  40838. for (name in source.floats) {
  40839. material.setFloat(name, source.floats[name]);
  40840. }
  40841. // Float s
  40842. for (name in source.floatsArrays) {
  40843. material.setFloats(name, source.floatsArrays[name]);
  40844. }
  40845. // Color3
  40846. for (name in source.colors3) {
  40847. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40848. }
  40849. // Color4
  40850. for (name in source.colors4) {
  40851. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40852. }
  40853. // Vector2
  40854. for (name in source.vectors2) {
  40855. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40856. }
  40857. // Vector3
  40858. for (name in source.vectors3) {
  40859. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40860. }
  40861. // Vector4
  40862. for (name in source.vectors4) {
  40863. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40864. }
  40865. // Matrix
  40866. for (name in source.matrices) {
  40867. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40868. }
  40869. // Matrix 3x3
  40870. for (name in source.matrices3x3) {
  40871. material.setMatrix3x3(name, source.matrices3x3[name]);
  40872. }
  40873. // Matrix 2x2
  40874. for (name in source.matrices2x2) {
  40875. material.setMatrix2x2(name, source.matrices2x2[name]);
  40876. }
  40877. // Vector3Array
  40878. for (name in source.vectors3Arrays) {
  40879. material.setArray3(name, source.vectors3Arrays[name]);
  40880. }
  40881. return material;
  40882. };
  40883. return ShaderMaterial;
  40884. }(BABYLON.Material));
  40885. BABYLON.ShaderMaterial = ShaderMaterial;
  40886. })(BABYLON || (BABYLON = {}));
  40887. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40888. var BABYLON;
  40889. (function (BABYLON) {
  40890. var Internals;
  40891. (function (Internals) {
  40892. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  40893. // All values and structures referenced from:
  40894. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  40895. var DDS_MAGIC = 0x20534444;
  40896. 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;
  40897. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  40898. 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;
  40899. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  40900. function FourCCToInt32(value) {
  40901. return value.charCodeAt(0) +
  40902. (value.charCodeAt(1) << 8) +
  40903. (value.charCodeAt(2) << 16) +
  40904. (value.charCodeAt(3) << 24);
  40905. }
  40906. function Int32ToFourCC(value) {
  40907. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  40908. }
  40909. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  40910. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  40911. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  40912. var headerLengthInt = 31; // The header length in 32 bit ints
  40913. // Offsets into the header array
  40914. var off_magic = 0;
  40915. var off_size = 1;
  40916. var off_flags = 2;
  40917. var off_height = 3;
  40918. var off_width = 4;
  40919. var off_mipmapCount = 7;
  40920. var off_pfFlags = 20;
  40921. var off_pfFourCC = 21;
  40922. var off_RGBbpp = 22;
  40923. var off_RMask = 23;
  40924. var off_GMask = 24;
  40925. var off_BMask = 25;
  40926. var off_AMask = 26;
  40927. var off_caps1 = 27;
  40928. var off_caps2 = 28;
  40929. ;
  40930. var DDSTools = (function () {
  40931. function DDSTools() {
  40932. }
  40933. DDSTools.GetDDSInfo = function (arrayBuffer) {
  40934. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  40935. var mipmapCount = 1;
  40936. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  40937. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40938. }
  40939. return {
  40940. width: header[off_width],
  40941. height: header[off_height],
  40942. mipmapCount: mipmapCount,
  40943. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  40944. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  40945. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  40946. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  40947. };
  40948. };
  40949. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40950. var byteArray = new Uint8Array(dataLength);
  40951. var srcData = new Uint8Array(arrayBuffer);
  40952. var index = 0;
  40953. for (var y = height - 1; y >= 0; y--) {
  40954. for (var x = 0; x < width; x++) {
  40955. var srcPos = dataOffset + (x + y * width) * 4;
  40956. byteArray[index + 2] = srcData[srcPos];
  40957. byteArray[index + 1] = srcData[srcPos + 1];
  40958. byteArray[index] = srcData[srcPos + 2];
  40959. byteArray[index + 3] = srcData[srcPos + 3];
  40960. index += 4;
  40961. }
  40962. }
  40963. return byteArray;
  40964. };
  40965. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40966. var byteArray = new Uint8Array(dataLength);
  40967. var srcData = new Uint8Array(arrayBuffer);
  40968. var index = 0;
  40969. for (var y = height - 1; y >= 0; y--) {
  40970. for (var x = 0; x < width; x++) {
  40971. var srcPos = dataOffset + (x + y * width) * 3;
  40972. byteArray[index + 2] = srcData[srcPos];
  40973. byteArray[index + 1] = srcData[srcPos + 1];
  40974. byteArray[index] = srcData[srcPos + 2];
  40975. index += 3;
  40976. }
  40977. }
  40978. return byteArray;
  40979. };
  40980. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40981. var byteArray = new Uint8Array(dataLength);
  40982. var srcData = new Uint8Array(arrayBuffer);
  40983. var index = 0;
  40984. for (var y = height - 1; y >= 0; y--) {
  40985. for (var x = 0; x < width; x++) {
  40986. var srcPos = dataOffset + (x + y * width);
  40987. byteArray[index] = srcData[srcPos];
  40988. index++;
  40989. }
  40990. }
  40991. return byteArray;
  40992. };
  40993. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  40994. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  40995. if (header[off_magic] != DDS_MAGIC) {
  40996. BABYLON.Tools.Error("Invalid magic number in DDS header");
  40997. return;
  40998. }
  40999. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  41000. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  41001. return;
  41002. }
  41003. if (info.isFourCC) {
  41004. fourCC = header[off_pfFourCC];
  41005. switch (fourCC) {
  41006. case FOURCC_DXT1:
  41007. blockBytes = 8;
  41008. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41009. break;
  41010. case FOURCC_DXT3:
  41011. blockBytes = 16;
  41012. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41013. break;
  41014. case FOURCC_DXT5:
  41015. blockBytes = 16;
  41016. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41017. break;
  41018. default:
  41019. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  41020. return;
  41021. }
  41022. }
  41023. mipmapCount = 1;
  41024. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  41025. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41026. }
  41027. var bpp = header[off_RGBbpp];
  41028. for (var face = 0; face < faces; face++) {
  41029. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41030. width = header[off_width];
  41031. height = header[off_height];
  41032. dataOffset = header[off_size] + 4;
  41033. for (i = 0; i < mipmapCount; ++i) {
  41034. if (info.isRGB) {
  41035. if (bpp === 24) {
  41036. dataLength = width * height * 3;
  41037. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41038. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41039. }
  41040. else {
  41041. dataLength = width * height * 4;
  41042. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41043. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41044. }
  41045. }
  41046. else if (info.isLuminance) {
  41047. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41048. var unpaddedRowSize = width;
  41049. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41050. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41051. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41052. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41053. }
  41054. else {
  41055. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41056. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41057. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41058. }
  41059. dataOffset += dataLength;
  41060. width *= 0.5;
  41061. height *= 0.5;
  41062. width = Math.max(1.0, width);
  41063. height = Math.max(1.0, height);
  41064. }
  41065. }
  41066. };
  41067. return DDSTools;
  41068. }());
  41069. Internals.DDSTools = DDSTools;
  41070. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41071. })(BABYLON || (BABYLON = {}));
  41072. //# sourceMappingURL=babylon.tools.dds.js.map
  41073. var BABYLON;
  41074. (function (BABYLON) {
  41075. var CannonJSPlugin = (function () {
  41076. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41077. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41078. if (iterations === void 0) { iterations = 10; }
  41079. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41080. this.name = "CannonJSPlugin";
  41081. this._physicsMaterials = [];
  41082. this._fixedTimeStep = 1 / 60;
  41083. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41084. this._currentCollisionGroup = 2;
  41085. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41086. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41087. this._tmpPosition = BABYLON.Vector3.Zero();
  41088. this._tmpQuaternion = new BABYLON.Quaternion();
  41089. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41090. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41091. this._tmpUnityRotation = new BABYLON.Quaternion();
  41092. if (!this.isSupported()) {
  41093. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41094. return;
  41095. }
  41096. this.world = new CANNON.World();
  41097. this.world.broadphase = new CANNON.NaiveBroadphase();
  41098. this.world.solver.iterations = iterations;
  41099. }
  41100. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41101. this.world.gravity.copy(gravity);
  41102. };
  41103. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41104. this._fixedTimeStep = timeStep;
  41105. };
  41106. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41107. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41108. };
  41109. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41110. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41111. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41112. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41113. };
  41114. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41115. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41116. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41117. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41118. };
  41119. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41120. //parent-child relationship. Does this impostor has a parent impostor?
  41121. if (impostor.parent) {
  41122. if (impostor.physicsBody) {
  41123. this.removePhysicsBody(impostor);
  41124. //TODO is that needed?
  41125. impostor.forceUpdate();
  41126. }
  41127. return;
  41128. }
  41129. //should a new body be created for this impostor?
  41130. if (impostor.isBodyInitRequired()) {
  41131. var shape = this._createShape(impostor);
  41132. //unregister events, if body is being changed
  41133. var oldBody = impostor.physicsBody;
  41134. if (oldBody) {
  41135. this.removePhysicsBody(impostor);
  41136. }
  41137. //create the body and material
  41138. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41139. var bodyCreationObject = {
  41140. mass: impostor.getParam("mass"),
  41141. material: material
  41142. };
  41143. // A simple extend, in case native options were used.
  41144. var nativeOptions = impostor.getParam("nativeOptions");
  41145. for (var key in nativeOptions) {
  41146. if (nativeOptions.hasOwnProperty(key)) {
  41147. bodyCreationObject[key] = nativeOptions[key];
  41148. }
  41149. }
  41150. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41151. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41152. this.world.addEventListener("preStep", impostor.beforeStep);
  41153. this.world.addEventListener("postStep", impostor.afterStep);
  41154. impostor.physicsBody.addShape(shape);
  41155. this.world.add(impostor.physicsBody);
  41156. //try to keep the body moving in the right direction by taking old properties.
  41157. //Should be tested!
  41158. if (oldBody) {
  41159. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41160. impostor.physicsBody[param].copy(oldBody[param]);
  41161. });
  41162. }
  41163. this._processChildMeshes(impostor);
  41164. }
  41165. //now update the body's transformation
  41166. this._updatePhysicsBodyTransformation(impostor);
  41167. };
  41168. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41169. var _this = this;
  41170. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41171. if (meshChildren.length) {
  41172. var processMesh = function (localPosition, mesh) {
  41173. var childImpostor = mesh.getPhysicsImpostor();
  41174. if (childImpostor) {
  41175. var parent = childImpostor.parent;
  41176. if (parent !== mainImpostor) {
  41177. var localPosition = mesh.position;
  41178. if (childImpostor.physicsBody) {
  41179. _this.removePhysicsBody(childImpostor);
  41180. childImpostor.physicsBody = null;
  41181. }
  41182. childImpostor.parent = mainImpostor;
  41183. childImpostor.resetUpdateFlags();
  41184. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41185. //Add the mass of the children.
  41186. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41187. }
  41188. }
  41189. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41190. };
  41191. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41192. }
  41193. };
  41194. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41195. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41196. this.world.removeEventListener("preStep", impostor.beforeStep);
  41197. this.world.removeEventListener("postStep", impostor.afterStep);
  41198. this.world.remove(impostor.physicsBody);
  41199. };
  41200. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41201. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41202. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41203. if (!mainBody || !connectedBody) {
  41204. return;
  41205. }
  41206. var constraint;
  41207. var jointData = impostorJoint.joint.jointData;
  41208. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41209. var constraintData = {
  41210. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41211. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41212. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41213. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41214. maxForce: jointData.nativeParams.maxForce,
  41215. collideConnected: !!jointData.collision
  41216. };
  41217. //Not needed, Cannon has a collideConnected flag
  41218. /*if (!jointData.collision) {
  41219. //add 1st body to a collision group of its own, if it is not in 1
  41220. if (mainBody.collisionFilterGroup === 1) {
  41221. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  41222. this._currentCollisionGroup <<= 1;
  41223. }
  41224. if (connectedBody.collisionFilterGroup === 1) {
  41225. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  41226. this._currentCollisionGroup <<= 1;
  41227. }
  41228. //add their mask to the collisionFilterMask of each other:
  41229. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  41230. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  41231. }*/
  41232. switch (impostorJoint.joint.type) {
  41233. case BABYLON.PhysicsJoint.HingeJoint:
  41234. case BABYLON.PhysicsJoint.Hinge2Joint:
  41235. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41236. break;
  41237. case BABYLON.PhysicsJoint.DistanceJoint:
  41238. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41239. break;
  41240. case BABYLON.PhysicsJoint.SpringJoint:
  41241. var springData = jointData;
  41242. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41243. restLength: springData.length,
  41244. stiffness: springData.stiffness,
  41245. damping: springData.damping,
  41246. localAnchorA: constraintData.pivotA,
  41247. localAnchorB: constraintData.pivotB
  41248. });
  41249. break;
  41250. case BABYLON.PhysicsJoint.LockJoint:
  41251. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41252. break;
  41253. case BABYLON.PhysicsJoint.PointToPointJoint:
  41254. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41255. default:
  41256. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41257. break;
  41258. }
  41259. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41260. constraint.collideConnected = !!jointData.collision;
  41261. impostorJoint.joint.physicsJoint = constraint;
  41262. //don't add spring as constraint, as it is not one.
  41263. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41264. this.world.addConstraint(constraint);
  41265. }
  41266. else {
  41267. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41268. constraint.applyForce();
  41269. });
  41270. }
  41271. };
  41272. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41273. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41274. };
  41275. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41276. var index;
  41277. var mat;
  41278. for (index = 0; index < this._physicsMaterials.length; index++) {
  41279. mat = this._physicsMaterials[index];
  41280. if (mat.friction === friction && mat.restitution === restitution) {
  41281. return mat;
  41282. }
  41283. }
  41284. var currentMat = new CANNON.Material(name);
  41285. currentMat.friction = friction;
  41286. currentMat.restitution = restitution;
  41287. this._physicsMaterials.push(currentMat);
  41288. return currentMat;
  41289. };
  41290. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41291. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41292. };
  41293. CannonJSPlugin.prototype._createShape = function (impostor) {
  41294. var object = impostor.object;
  41295. var returnValue;
  41296. var extendSize = impostor.getObjectExtendSize();
  41297. switch (impostor.type) {
  41298. case BABYLON.PhysicsEngine.SphereImpostor:
  41299. var radiusX = extendSize.x;
  41300. var radiusY = extendSize.y;
  41301. var radiusZ = extendSize.z;
  41302. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41303. break;
  41304. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41305. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41306. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41307. break;
  41308. case BABYLON.PhysicsImpostor.BoxImpostor:
  41309. var box = extendSize.scale(0.5);
  41310. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41311. break;
  41312. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41313. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41314. returnValue = new CANNON.Plane();
  41315. break;
  41316. case BABYLON.PhysicsImpostor.MeshImpostor:
  41317. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41318. var rawFaces = object.getIndices ? object.getIndices() : [];
  41319. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41320. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41321. break;
  41322. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41323. returnValue = this._createHeightmap(object);
  41324. break;
  41325. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41326. returnValue = new CANNON.Particle();
  41327. break;
  41328. }
  41329. return returnValue;
  41330. };
  41331. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41332. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41333. var matrix = [];
  41334. //For now pointDepth will not be used and will be automatically calculated.
  41335. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41336. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41337. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41338. var elementSize = dim * 2 / arraySize;
  41339. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41340. for (var i = 0; i < pos.length; i = i + 3) {
  41341. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41342. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41343. var y = pos[i + 1] + minY;
  41344. if (!matrix[x]) {
  41345. matrix[x] = [];
  41346. }
  41347. if (!matrix[x][z]) {
  41348. matrix[x][z] = y;
  41349. }
  41350. matrix[x][z] = Math.max(y, matrix[x][z]);
  41351. }
  41352. for (var x = 0; x <= arraySize; ++x) {
  41353. if (!matrix[x]) {
  41354. var loc = 1;
  41355. while (!matrix[(x + loc) % arraySize]) {
  41356. loc++;
  41357. }
  41358. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41359. }
  41360. for (var z = 0; z <= arraySize; ++z) {
  41361. if (!matrix[x][z]) {
  41362. var loc = 1;
  41363. var newValue;
  41364. while (newValue === undefined) {
  41365. newValue = matrix[x][(z + loc++) % arraySize];
  41366. }
  41367. matrix[x][z] = newValue;
  41368. }
  41369. }
  41370. }
  41371. var shape = new CANNON.Heightfield(matrix, {
  41372. elementSize: elementSize
  41373. });
  41374. //For future reference, needed for body transformation
  41375. shape.minY = minY;
  41376. return shape;
  41377. };
  41378. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41379. var object = impostor.object;
  41380. //make sure it is updated...
  41381. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41382. // The delta between the mesh position and the mesh bounding box center
  41383. var center = impostor.getObjectCenter();
  41384. var extendSize = impostor.getObjectExtendSize();
  41385. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41386. this._tmpPosition.copyFrom(center);
  41387. var quaternion = object.rotationQuaternion;
  41388. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41389. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  41390. //-90 DEG in X, precalculated
  41391. quaternion = quaternion.multiply(this._minus90X);
  41392. //Invert! (Precalculated, 90 deg in X)
  41393. //No need to clone. this will never change.
  41394. impostor.setDeltaRotation(this._plus90X);
  41395. }
  41396. //If it is a heightfield, if should be centered.
  41397. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  41398. var mesh = object;
  41399. //calculate the correct body position:
  41400. var rotationQuaternion = mesh.rotationQuaternion;
  41401. mesh.rotationQuaternion = this._tmpUnityRotation;
  41402. mesh.computeWorldMatrix(true);
  41403. //get original center with no rotation
  41404. var c = center.clone();
  41405. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  41406. //rotation is back
  41407. mesh.rotationQuaternion = rotationQuaternion;
  41408. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  41409. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  41410. mesh.setPivotMatrix(p);
  41411. mesh.computeWorldMatrix(true);
  41412. //calculate the translation
  41413. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  41414. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  41415. //add it inverted to the delta
  41416. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  41417. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  41418. mesh.setPivotMatrix(oldPivot);
  41419. mesh.computeWorldMatrix(true);
  41420. }
  41421. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  41422. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  41423. this._tmpPosition.copyFrom(object.position);
  41424. }
  41425. impostor.setDeltaPosition(this._tmpDeltaPosition);
  41426. //Now update the impostor object
  41427. impostor.physicsBody.position.copy(this._tmpPosition);
  41428. impostor.physicsBody.quaternion.copy(quaternion);
  41429. };
  41430. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41431. impostor.object.position.copyFrom(impostor.physicsBody.position);
  41432. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  41433. };
  41434. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41435. impostor.physicsBody.position.copy(newPosition);
  41436. impostor.physicsBody.quaternion.copy(newRotation);
  41437. };
  41438. CannonJSPlugin.prototype.isSupported = function () {
  41439. return window.CANNON !== undefined;
  41440. };
  41441. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41442. impostor.physicsBody.velocity.copy(velocity);
  41443. };
  41444. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41445. impostor.physicsBody.angularVelocity.copy(velocity);
  41446. };
  41447. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41448. var v = impostor.physicsBody.velocity;
  41449. if (!v)
  41450. return null;
  41451. return new BABYLON.Vector3(v.x, v.y, v.z);
  41452. };
  41453. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41454. var v = impostor.physicsBody.angularVelocity;
  41455. if (!v)
  41456. return null;
  41457. return new BABYLON.Vector3(v.x, v.y, v.z);
  41458. };
  41459. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41460. impostor.physicsBody.mass = mass;
  41461. impostor.physicsBody.updateMassProperties();
  41462. };
  41463. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  41464. impostor.physicsBody.sleep();
  41465. };
  41466. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  41467. impostor.physicsBody.wakeUp();
  41468. };
  41469. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41470. joint.physicsJoint.distance = maxDistance;
  41471. };
  41472. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  41473. if (!motorIndex) {
  41474. joint.physicsJoint.enableMotor();
  41475. }
  41476. };
  41477. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  41478. if (!motorIndex) {
  41479. joint.physicsJoint.disableMotor();
  41480. }
  41481. };
  41482. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41483. if (!motorIndex) {
  41484. joint.physicsJoint.enableMotor();
  41485. joint.physicsJoint.setMotorSpeed(speed);
  41486. if (maxForce) {
  41487. this.setLimit(joint, maxForce);
  41488. }
  41489. }
  41490. };
  41491. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  41492. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  41493. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  41494. };
  41495. CannonJSPlugin.prototype.dispose = function () {
  41496. //nothing to do, actually.
  41497. };
  41498. return CannonJSPlugin;
  41499. }());
  41500. BABYLON.CannonJSPlugin = CannonJSPlugin;
  41501. })(BABYLON || (BABYLON = {}));
  41502. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  41503. var BABYLON;
  41504. (function (BABYLON) {
  41505. var OimoJSPlugin = (function () {
  41506. function OimoJSPlugin(iterations) {
  41507. this.name = "OimoJSPlugin";
  41508. this._tmpImpostorsArray = [];
  41509. this._tmpPositionVector = BABYLON.Vector3.Zero();
  41510. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  41511. this.world.worldscale(1);
  41512. this.world.clear();
  41513. //making sure no stats are calculated
  41514. this.world.isNoStat = true;
  41515. }
  41516. OimoJSPlugin.prototype.setGravity = function (gravity) {
  41517. this.world.gravity.copy(gravity);
  41518. };
  41519. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  41520. this.world.timeStep = timeStep;
  41521. };
  41522. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  41523. var _this = this;
  41524. impostors.forEach(function (impostor) {
  41525. impostor.beforeStep();
  41526. });
  41527. this.world.step();
  41528. impostors.forEach(function (impostor) {
  41529. impostor.afterStep();
  41530. //update the ordered impostors array
  41531. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  41532. });
  41533. //check for collisions
  41534. var contact = this.world.contacts;
  41535. while (contact !== null) {
  41536. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  41537. contact = contact.next;
  41538. continue;
  41539. }
  41540. //is this body colliding with any other? get the impostor
  41541. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  41542. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  41543. if (!mainImpostor || !collidingImpostor) {
  41544. contact = contact.next;
  41545. continue;
  41546. }
  41547. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41548. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  41549. contact = contact.next;
  41550. }
  41551. };
  41552. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41553. var mass = impostor.physicsBody.massInfo.mass;
  41554. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  41555. };
  41556. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41557. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  41558. this.applyImpulse(impostor, force, contactPoint);
  41559. };
  41560. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41561. var _this = this;
  41562. //parent-child relationship. Does this impostor has a parent impostor?
  41563. if (impostor.parent) {
  41564. if (impostor.physicsBody) {
  41565. this.removePhysicsBody(impostor);
  41566. //TODO is that needed?
  41567. impostor.forceUpdate();
  41568. }
  41569. return;
  41570. }
  41571. if (impostor.isBodyInitRequired()) {
  41572. var bodyConfig = {
  41573. name: impostor.uniqueId,
  41574. //Oimo must have mass, also for static objects.
  41575. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  41576. size: [],
  41577. type: [],
  41578. pos: [],
  41579. rot: [],
  41580. move: impostor.getParam("mass") !== 0,
  41581. //Supporting older versions of Oimo
  41582. world: this.world
  41583. };
  41584. var impostors = [impostor];
  41585. var addToArray = function (parent) {
  41586. if (!parent.getChildMeshes)
  41587. return;
  41588. parent.getChildMeshes().forEach(function (m) {
  41589. if (m.physicsImpostor) {
  41590. impostors.push(m.physicsImpostor);
  41591. m.physicsImpostor._init();
  41592. }
  41593. });
  41594. };
  41595. addToArray(impostor.object);
  41596. var checkWithEpsilon_1 = function (value) {
  41597. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  41598. };
  41599. impostors.forEach(function (i) {
  41600. //get the correct bounding box
  41601. var oldQuaternion = i.object.rotationQuaternion;
  41602. var rot = new OIMO.Euler().setFromQuaternion({
  41603. x: impostor.object.rotationQuaternion.x,
  41604. y: impostor.object.rotationQuaternion.y,
  41605. z: impostor.object.rotationQuaternion.z,
  41606. s: impostor.object.rotationQuaternion.w
  41607. });
  41608. var extendSize = i.getObjectExtendSize();
  41609. if (i === impostor) {
  41610. var center = impostor.getObjectCenter();
  41611. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  41612. //Can also use Array.prototype.push.apply
  41613. bodyConfig.pos.push(center.x);
  41614. bodyConfig.pos.push(center.y);
  41615. bodyConfig.pos.push(center.z);
  41616. //tmp solution
  41617. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  41618. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  41619. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  41620. }
  41621. else {
  41622. bodyConfig.pos.push(i.object.position.x);
  41623. bodyConfig.pos.push(i.object.position.y);
  41624. bodyConfig.pos.push(i.object.position.z);
  41625. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  41626. bodyConfig.rot.push(0);
  41627. bodyConfig.rot.push(0);
  41628. bodyConfig.rot.push(0);
  41629. }
  41630. // register mesh
  41631. switch (i.type) {
  41632. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41633. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  41634. case BABYLON.PhysicsImpostor.SphereImpostor:
  41635. var radiusX = extendSize.x;
  41636. var radiusY = extendSize.y;
  41637. var radiusZ = extendSize.z;
  41638. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  41639. bodyConfig.type.push('sphere');
  41640. //due to the way oimo works with compounds, add 3 times
  41641. bodyConfig.size.push(size);
  41642. bodyConfig.size.push(size);
  41643. bodyConfig.size.push(size);
  41644. break;
  41645. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41646. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  41647. var sizeY = checkWithEpsilon_1(extendSize.y);
  41648. bodyConfig.type.push('cylinder');
  41649. bodyConfig.size.push(sizeX);
  41650. bodyConfig.size.push(sizeY);
  41651. //due to the way oimo works with compounds, add one more value.
  41652. bodyConfig.size.push(sizeY);
  41653. break;
  41654. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41655. case BABYLON.PhysicsImpostor.BoxImpostor:
  41656. default:
  41657. var sizeX = checkWithEpsilon_1(extendSize.x);
  41658. var sizeY = checkWithEpsilon_1(extendSize.y);
  41659. var sizeZ = checkWithEpsilon_1(extendSize.z);
  41660. bodyConfig.type.push('box');
  41661. bodyConfig.size.push(sizeX);
  41662. bodyConfig.size.push(sizeY);
  41663. bodyConfig.size.push(sizeZ);
  41664. break;
  41665. }
  41666. //actually not needed, but hey...
  41667. i.object.rotationQuaternion = oldQuaternion;
  41668. });
  41669. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  41670. }
  41671. else {
  41672. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  41673. }
  41674. impostor.setDeltaPosition(this._tmpPositionVector);
  41675. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  41676. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  41677. };
  41678. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41679. //impostor.physicsBody.dispose();
  41680. //Same as : (older oimo versions)
  41681. this.world.removeRigidBody(impostor.physicsBody);
  41682. };
  41683. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41684. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41685. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41686. if (!mainBody || !connectedBody) {
  41687. return;
  41688. }
  41689. var jointData = impostorJoint.joint.jointData;
  41690. var options = jointData.nativeParams || {};
  41691. var type;
  41692. var nativeJointData = {
  41693. body1: mainBody,
  41694. body2: connectedBody,
  41695. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  41696. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  41697. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  41698. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  41699. min: options.min,
  41700. max: options.max,
  41701. collision: options.collision || jointData.collision,
  41702. spring: options.spring,
  41703. //supporting older version of Oimo
  41704. world: this.world
  41705. };
  41706. switch (impostorJoint.joint.type) {
  41707. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41708. type = "jointBall";
  41709. break;
  41710. case BABYLON.PhysicsJoint.SpringJoint:
  41711. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  41712. var springData = jointData;
  41713. nativeJointData.min = springData.length || nativeJointData.min;
  41714. //Max should also be set, just make sure it is at least min
  41715. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  41716. case BABYLON.PhysicsJoint.DistanceJoint:
  41717. type = "jointDistance";
  41718. nativeJointData.max = jointData.maxDistance;
  41719. break;
  41720. case BABYLON.PhysicsJoint.PrismaticJoint:
  41721. type = "jointPrisme";
  41722. break;
  41723. case BABYLON.PhysicsJoint.SliderJoint:
  41724. type = "jointSlide";
  41725. break;
  41726. case BABYLON.PhysicsJoint.WheelJoint:
  41727. type = "jointWheel";
  41728. break;
  41729. case BABYLON.PhysicsJoint.HingeJoint:
  41730. default:
  41731. type = "jointHinge";
  41732. break;
  41733. }
  41734. nativeJointData.type = type;
  41735. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  41736. };
  41737. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41738. //Bug in Oimo prevents us from disposing a joint in the playground
  41739. //joint.joint.physicsJoint.dispose();
  41740. //So we will bruteforce it!
  41741. try {
  41742. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  41743. }
  41744. catch (e) {
  41745. BABYLON.Tools.Warn(e);
  41746. }
  41747. };
  41748. OimoJSPlugin.prototype.isSupported = function () {
  41749. return OIMO !== undefined;
  41750. };
  41751. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41752. if (!impostor.physicsBody.sleeping) {
  41753. //TODO check that
  41754. if (impostor.physicsBody.shapes.next) {
  41755. var parentShape = this._getLastShape(impostor.physicsBody);
  41756. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  41757. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  41758. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  41759. }
  41760. else {
  41761. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  41762. }
  41763. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  41764. impostor.object.rotationQuaternion.normalize();
  41765. }
  41766. };
  41767. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41768. var body = impostor.physicsBody;
  41769. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  41770. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  41771. body.syncShapes();
  41772. body.awake();
  41773. };
  41774. OimoJSPlugin.prototype._getLastShape = function (body) {
  41775. var lastShape = body.shapes;
  41776. while (lastShape.next) {
  41777. lastShape = lastShape.next;
  41778. }
  41779. return lastShape;
  41780. };
  41781. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41782. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  41783. };
  41784. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41785. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  41786. };
  41787. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41788. var v = impostor.physicsBody.linearVelocity;
  41789. if (!v)
  41790. return null;
  41791. return new BABYLON.Vector3(v.x, v.y, v.z);
  41792. };
  41793. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41794. var v = impostor.physicsBody.angularVelocity;
  41795. if (!v)
  41796. return null;
  41797. return new BABYLON.Vector3(v.x, v.y, v.z);
  41798. };
  41799. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41800. var staticBody = mass === 0;
  41801. //this will actually set the body's density and not its mass.
  41802. //But this is how oimo treats the mass variable.
  41803. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  41804. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  41805. };
  41806. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  41807. impostor.physicsBody.sleep();
  41808. };
  41809. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  41810. impostor.physicsBody.awake();
  41811. };
  41812. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41813. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  41814. if (minDistance !== void 0) {
  41815. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  41816. }
  41817. };
  41818. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41819. //TODO separate rotational and transational motors.
  41820. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41821. if (motor) {
  41822. motor.setMotor(speed, maxForce);
  41823. }
  41824. };
  41825. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  41826. //TODO separate rotational and transational motors.
  41827. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41828. if (motor) {
  41829. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  41830. }
  41831. };
  41832. OimoJSPlugin.prototype.dispose = function () {
  41833. this.world.clear();
  41834. };
  41835. return OimoJSPlugin;
  41836. }());
  41837. BABYLON.OimoJSPlugin = OimoJSPlugin;
  41838. })(BABYLON || (BABYLON = {}));
  41839. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  41840. var BABYLON;
  41841. (function (BABYLON) {
  41842. var DisplayPassPostProcess = (function (_super) {
  41843. __extends(DisplayPassPostProcess, _super);
  41844. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  41845. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  41846. }
  41847. return DisplayPassPostProcess;
  41848. }(BABYLON.PostProcess));
  41849. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  41850. })(BABYLON || (BABYLON = {}));
  41851. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  41852. var BABYLON;
  41853. (function (BABYLON) {
  41854. var SimplificationSettings = (function () {
  41855. function SimplificationSettings(quality, distance, optimizeMesh) {
  41856. this.quality = quality;
  41857. this.distance = distance;
  41858. this.optimizeMesh = optimizeMesh;
  41859. }
  41860. return SimplificationSettings;
  41861. }());
  41862. BABYLON.SimplificationSettings = SimplificationSettings;
  41863. var SimplificationQueue = (function () {
  41864. function SimplificationQueue() {
  41865. this.running = false;
  41866. this._simplificationArray = [];
  41867. }
  41868. SimplificationQueue.prototype.addTask = function (task) {
  41869. this._simplificationArray.push(task);
  41870. };
  41871. SimplificationQueue.prototype.executeNext = function () {
  41872. var task = this._simplificationArray.pop();
  41873. if (task) {
  41874. this.running = true;
  41875. this.runSimplification(task);
  41876. }
  41877. else {
  41878. this.running = false;
  41879. }
  41880. };
  41881. SimplificationQueue.prototype.runSimplification = function (task) {
  41882. var _this = this;
  41883. if (task.parallelProcessing) {
  41884. //parallel simplifier
  41885. task.settings.forEach(function (setting) {
  41886. var simplifier = _this.getSimplifier(task);
  41887. simplifier.simplify(setting, function (newMesh) {
  41888. task.mesh.addLODLevel(setting.distance, newMesh);
  41889. newMesh.isVisible = true;
  41890. //check if it is the last
  41891. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41892. //all done, run the success callback.
  41893. task.successCallback();
  41894. }
  41895. _this.executeNext();
  41896. });
  41897. });
  41898. }
  41899. else {
  41900. //single simplifier.
  41901. var simplifier = this.getSimplifier(task);
  41902. var runDecimation = function (setting, callback) {
  41903. simplifier.simplify(setting, function (newMesh) {
  41904. task.mesh.addLODLevel(setting.distance, newMesh);
  41905. newMesh.isVisible = true;
  41906. //run the next quality level
  41907. callback();
  41908. });
  41909. };
  41910. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  41911. runDecimation(task.settings[loop.index], function () {
  41912. loop.executeNext();
  41913. });
  41914. }, function () {
  41915. //execution ended, run the success callback.
  41916. if (task.successCallback) {
  41917. task.successCallback();
  41918. }
  41919. _this.executeNext();
  41920. });
  41921. }
  41922. };
  41923. SimplificationQueue.prototype.getSimplifier = function (task) {
  41924. switch (task.simplificationType) {
  41925. case SimplificationType.QUADRATIC:
  41926. default:
  41927. return new QuadraticErrorSimplification(task.mesh);
  41928. }
  41929. };
  41930. return SimplificationQueue;
  41931. }());
  41932. BABYLON.SimplificationQueue = SimplificationQueue;
  41933. /**
  41934. * The implemented types of simplification.
  41935. * At the moment only Quadratic Error Decimation is implemented.
  41936. */
  41937. (function (SimplificationType) {
  41938. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  41939. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  41940. var SimplificationType = BABYLON.SimplificationType;
  41941. var DecimationTriangle = (function () {
  41942. function DecimationTriangle(vertices) {
  41943. this.vertices = vertices;
  41944. this.error = new Array(4);
  41945. this.deleted = false;
  41946. this.isDirty = false;
  41947. this.deletePending = false;
  41948. this.borderFactor = 0;
  41949. }
  41950. return DecimationTriangle;
  41951. }());
  41952. BABYLON.DecimationTriangle = DecimationTriangle;
  41953. var DecimationVertex = (function () {
  41954. function DecimationVertex(position, id) {
  41955. this.position = position;
  41956. this.id = id;
  41957. this.isBorder = true;
  41958. this.q = new QuadraticMatrix();
  41959. this.triangleCount = 0;
  41960. this.triangleStart = 0;
  41961. this.originalOffsets = [];
  41962. }
  41963. DecimationVertex.prototype.updatePosition = function (newPosition) {
  41964. this.position.copyFrom(newPosition);
  41965. };
  41966. return DecimationVertex;
  41967. }());
  41968. BABYLON.DecimationVertex = DecimationVertex;
  41969. var QuadraticMatrix = (function () {
  41970. function QuadraticMatrix(data) {
  41971. this.data = new Array(10);
  41972. for (var i = 0; i < 10; ++i) {
  41973. if (data && data[i]) {
  41974. this.data[i] = data[i];
  41975. }
  41976. else {
  41977. this.data[i] = 0;
  41978. }
  41979. }
  41980. }
  41981. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  41982. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  41983. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  41984. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  41985. return det;
  41986. };
  41987. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  41988. for (var i = 0; i < 10; ++i) {
  41989. this.data[i] += matrix.data[i];
  41990. }
  41991. };
  41992. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  41993. for (var i = 0; i < 10; ++i) {
  41994. this.data[i] += data[i];
  41995. }
  41996. };
  41997. QuadraticMatrix.prototype.add = function (matrix) {
  41998. var m = new QuadraticMatrix();
  41999. for (var i = 0; i < 10; ++i) {
  42000. m.data[i] = this.data[i] + matrix.data[i];
  42001. }
  42002. return m;
  42003. };
  42004. QuadraticMatrix.FromData = function (a, b, c, d) {
  42005. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  42006. };
  42007. //returning an array to avoid garbage collection
  42008. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  42009. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  42010. };
  42011. return QuadraticMatrix;
  42012. }());
  42013. BABYLON.QuadraticMatrix = QuadraticMatrix;
  42014. var Reference = (function () {
  42015. function Reference(vertexId, triangleId) {
  42016. this.vertexId = vertexId;
  42017. this.triangleId = triangleId;
  42018. }
  42019. return Reference;
  42020. }());
  42021. BABYLON.Reference = Reference;
  42022. /**
  42023. * An implementation of the Quadratic Error simplification algorithm.
  42024. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  42025. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  42026. * @author RaananW
  42027. */
  42028. var QuadraticErrorSimplification = (function () {
  42029. function QuadraticErrorSimplification(_mesh) {
  42030. this._mesh = _mesh;
  42031. this.initialized = false;
  42032. this.syncIterations = 5000;
  42033. this.aggressiveness = 7;
  42034. this.decimationIterations = 100;
  42035. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42036. }
  42037. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42038. var _this = this;
  42039. this.initDecimatedMesh();
  42040. //iterating through the submeshes array, one after the other.
  42041. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42042. _this.initWithMesh(loop.index, function () {
  42043. _this.runDecimation(settings, loop.index, function () {
  42044. loop.executeNext();
  42045. });
  42046. }, settings.optimizeMesh);
  42047. }, function () {
  42048. setTimeout(function () {
  42049. successCallback(_this._reconstructedMesh);
  42050. }, 0);
  42051. });
  42052. };
  42053. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42054. var _this = this;
  42055. var gCount = 0;
  42056. triangle.vertices.forEach(function (vertex) {
  42057. var count = 0;
  42058. var vPos = vertex.position;
  42059. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42060. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42061. ++count;
  42062. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42063. ++count;
  42064. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42065. ++count;
  42066. if (count > 1) {
  42067. ++gCount;
  42068. }
  42069. ;
  42070. });
  42071. if (gCount > 1) {
  42072. console.log(triangle, gCount);
  42073. }
  42074. return gCount > 1;
  42075. };
  42076. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42077. var _this = this;
  42078. var targetCount = ~~(this.triangles.length * settings.quality);
  42079. var deletedTriangles = 0;
  42080. var triangleCount = this.triangles.length;
  42081. var iterationFunction = function (iteration, callback) {
  42082. setTimeout(function () {
  42083. if (iteration % 5 === 0) {
  42084. _this.updateMesh(iteration === 0);
  42085. }
  42086. for (var i = 0; i < _this.triangles.length; ++i) {
  42087. _this.triangles[i].isDirty = false;
  42088. }
  42089. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42090. var trianglesIterator = function (i) {
  42091. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42092. var t = _this.triangles[tIdx];
  42093. if (!t)
  42094. return;
  42095. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42096. return;
  42097. }
  42098. for (var j = 0; j < 3; ++j) {
  42099. if (t.error[j] < threshold) {
  42100. var deleted0 = [];
  42101. var deleted1 = [];
  42102. var v0 = t.vertices[j];
  42103. var v1 = t.vertices[(j + 1) % 3];
  42104. if (v0.isBorder || v1.isBorder)
  42105. continue;
  42106. var p = BABYLON.Vector3.Zero();
  42107. var n = BABYLON.Vector3.Zero();
  42108. var uv = BABYLON.Vector2.Zero();
  42109. var color = new BABYLON.Color4(0, 0, 0, 1);
  42110. _this.calculateError(v0, v1, p, n, uv, color);
  42111. var delTr = [];
  42112. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42113. continue;
  42114. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42115. continue;
  42116. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42117. continue;
  42118. var uniqueArray = [];
  42119. delTr.forEach(function (deletedT) {
  42120. if (uniqueArray.indexOf(deletedT) === -1) {
  42121. deletedT.deletePending = true;
  42122. uniqueArray.push(deletedT);
  42123. }
  42124. });
  42125. if (uniqueArray.length % 2 !== 0) {
  42126. continue;
  42127. }
  42128. v0.q = v1.q.add(v0.q);
  42129. v0.updatePosition(p);
  42130. var tStart = _this.references.length;
  42131. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42132. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42133. var tCount = _this.references.length - tStart;
  42134. if (tCount <= v0.triangleCount) {
  42135. if (tCount) {
  42136. for (var c = 0; c < tCount; c++) {
  42137. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42138. }
  42139. }
  42140. }
  42141. else {
  42142. v0.triangleStart = tStart;
  42143. }
  42144. v0.triangleCount = tCount;
  42145. break;
  42146. }
  42147. }
  42148. };
  42149. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42150. }, 0);
  42151. };
  42152. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42153. if (triangleCount - deletedTriangles <= targetCount)
  42154. loop.breakLoop();
  42155. else {
  42156. iterationFunction(loop.index, function () {
  42157. loop.executeNext();
  42158. });
  42159. }
  42160. }, function () {
  42161. setTimeout(function () {
  42162. //reconstruct this part of the mesh
  42163. _this.reconstructMesh(submeshIndex);
  42164. successCallback();
  42165. }, 0);
  42166. });
  42167. };
  42168. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42169. var _this = this;
  42170. this.vertices = [];
  42171. this.triangles = [];
  42172. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42173. var indices = this._mesh.getIndices();
  42174. var submesh = this._mesh.subMeshes[submeshIndex];
  42175. var findInVertices = function (positionToSearch) {
  42176. if (optimizeMesh) {
  42177. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42178. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42179. return _this.vertices[ii];
  42180. }
  42181. }
  42182. }
  42183. return null;
  42184. };
  42185. var vertexReferences = [];
  42186. var vertexInit = function (i) {
  42187. var offset = i + submesh.verticesStart;
  42188. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42189. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42190. vertex.originalOffsets.push(offset);
  42191. if (vertex.id === _this.vertices.length) {
  42192. _this.vertices.push(vertex);
  42193. }
  42194. vertexReferences.push(vertex.id);
  42195. };
  42196. //var totalVertices = mesh.getTotalVertices();
  42197. var totalVertices = submesh.verticesCount;
  42198. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42199. var indicesInit = function (i) {
  42200. var offset = (submesh.indexStart / 3) + i;
  42201. var pos = (offset * 3);
  42202. var i0 = indices[pos + 0];
  42203. var i1 = indices[pos + 1];
  42204. var i2 = indices[pos + 2];
  42205. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42206. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42207. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42208. var triangle = new DecimationTriangle([v0, v1, v2]);
  42209. triangle.originalOffset = pos;
  42210. _this.triangles.push(triangle);
  42211. };
  42212. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42213. _this.init(callback);
  42214. });
  42215. });
  42216. };
  42217. QuadraticErrorSimplification.prototype.init = function (callback) {
  42218. var _this = this;
  42219. var triangleInit1 = function (i) {
  42220. var t = _this.triangles[i];
  42221. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42222. for (var j = 0; j < 3; j++) {
  42223. 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))));
  42224. }
  42225. };
  42226. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42227. var triangleInit2 = function (i) {
  42228. var t = _this.triangles[i];
  42229. for (var j = 0; j < 3; ++j) {
  42230. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42231. }
  42232. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42233. };
  42234. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42235. _this.initialized = true;
  42236. callback();
  42237. });
  42238. });
  42239. };
  42240. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42241. var newTriangles = [];
  42242. var i;
  42243. for (i = 0; i < this.vertices.length; ++i) {
  42244. this.vertices[i].triangleCount = 0;
  42245. }
  42246. var t;
  42247. var j;
  42248. for (i = 0; i < this.triangles.length; ++i) {
  42249. if (!this.triangles[i].deleted) {
  42250. t = this.triangles[i];
  42251. for (j = 0; j < 3; ++j) {
  42252. t.vertices[j].triangleCount = 1;
  42253. }
  42254. newTriangles.push(t);
  42255. }
  42256. }
  42257. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42258. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42259. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42260. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42261. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42262. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42263. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42264. var vertexCount = 0;
  42265. for (i = 0; i < this.vertices.length; ++i) {
  42266. var vertex = this.vertices[i];
  42267. vertex.id = vertexCount;
  42268. if (vertex.triangleCount) {
  42269. vertex.originalOffsets.forEach(function (originalOffset) {
  42270. newPositionData.push(vertex.position.x);
  42271. newPositionData.push(vertex.position.y);
  42272. newPositionData.push(vertex.position.z);
  42273. newNormalData.push(normalData[originalOffset * 3]);
  42274. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42275. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42276. if (uvs && uvs.length) {
  42277. newUVsData.push(uvs[(originalOffset * 2)]);
  42278. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42279. }
  42280. else if (colorsData && colorsData.length) {
  42281. newColorsData.push(colorsData[(originalOffset * 4)]);
  42282. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42283. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42284. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42285. }
  42286. ++vertexCount;
  42287. });
  42288. }
  42289. }
  42290. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42291. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42292. var submeshesArray = this._reconstructedMesh.subMeshes;
  42293. this._reconstructedMesh.subMeshes = [];
  42294. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42295. var originalIndices = this._mesh.getIndices();
  42296. for (i = 0; i < newTriangles.length; ++i) {
  42297. t = newTriangles[i]; //now get the new referencing point for each vertex
  42298. [0, 1, 2].forEach(function (idx) {
  42299. var id = originalIndices[t.originalOffset + idx];
  42300. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42301. if (offset < 0)
  42302. offset = 0;
  42303. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42304. });
  42305. }
  42306. //overwriting the old vertex buffers and indices.
  42307. this._reconstructedMesh.setIndices(newIndicesArray);
  42308. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42309. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42310. if (newUVsData.length > 0)
  42311. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42312. if (newColorsData.length > 0)
  42313. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42314. //create submesh
  42315. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42316. if (submeshIndex > 0) {
  42317. this._reconstructedMesh.subMeshes = [];
  42318. submeshesArray.forEach(function (submesh) {
  42319. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42320. });
  42321. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42322. }
  42323. };
  42324. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42325. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42326. this._reconstructedMesh.material = this._mesh.material;
  42327. this._reconstructedMesh.parent = this._mesh.parent;
  42328. this._reconstructedMesh.isVisible = false;
  42329. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42330. };
  42331. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42332. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42333. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42334. if (t.deleted)
  42335. continue;
  42336. var s = this.references[vertex1.triangleStart + i].vertexId;
  42337. var v1 = t.vertices[(s + 1) % 3];
  42338. var v2 = t.vertices[(s + 2) % 3];
  42339. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42340. deletedArray[i] = true;
  42341. delTr.push(t);
  42342. continue;
  42343. }
  42344. var d1 = v1.position.subtract(point);
  42345. d1 = d1.normalize();
  42346. var d2 = v2.position.subtract(point);
  42347. d2 = d2.normalize();
  42348. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42349. return true;
  42350. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42351. deletedArray[i] = false;
  42352. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42353. return true;
  42354. }
  42355. return false;
  42356. };
  42357. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42358. var newDeleted = deletedTriangles;
  42359. for (var i = 0; i < vertex.triangleCount; ++i) {
  42360. var ref = this.references[vertex.triangleStart + i];
  42361. var t = this.triangles[ref.triangleId];
  42362. if (t.deleted)
  42363. continue;
  42364. if (deletedArray[i] && t.deletePending) {
  42365. t.deleted = true;
  42366. newDeleted++;
  42367. continue;
  42368. }
  42369. t.vertices[ref.vertexId] = origVertex;
  42370. t.isDirty = true;
  42371. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42372. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42373. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42374. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42375. this.references.push(ref);
  42376. }
  42377. return newDeleted;
  42378. };
  42379. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42380. for (var i = 0; i < this.vertices.length; ++i) {
  42381. var vCount = [];
  42382. var vId = [];
  42383. var v = this.vertices[i];
  42384. var j;
  42385. for (j = 0; j < v.triangleCount; ++j) {
  42386. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42387. for (var ii = 0; ii < 3; ii++) {
  42388. var ofs = 0;
  42389. var vv = triangle.vertices[ii];
  42390. while (ofs < vCount.length) {
  42391. if (vId[ofs] === vv.id)
  42392. break;
  42393. ++ofs;
  42394. }
  42395. if (ofs === vCount.length) {
  42396. vCount.push(1);
  42397. vId.push(vv.id);
  42398. }
  42399. else {
  42400. vCount[ofs]++;
  42401. }
  42402. }
  42403. }
  42404. for (j = 0; j < vCount.length; ++j) {
  42405. if (vCount[j] === 1) {
  42406. this.vertices[vId[j]].isBorder = true;
  42407. }
  42408. else {
  42409. this.vertices[vId[j]].isBorder = false;
  42410. }
  42411. }
  42412. }
  42413. };
  42414. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  42415. if (identifyBorders === void 0) { identifyBorders = false; }
  42416. var i;
  42417. if (!identifyBorders) {
  42418. var newTrianglesVector = [];
  42419. for (i = 0; i < this.triangles.length; ++i) {
  42420. if (!this.triangles[i].deleted) {
  42421. newTrianglesVector.push(this.triangles[i]);
  42422. }
  42423. }
  42424. this.triangles = newTrianglesVector;
  42425. }
  42426. for (i = 0; i < this.vertices.length; ++i) {
  42427. this.vertices[i].triangleCount = 0;
  42428. this.vertices[i].triangleStart = 0;
  42429. }
  42430. var t;
  42431. var j;
  42432. var v;
  42433. for (i = 0; i < this.triangles.length; ++i) {
  42434. t = this.triangles[i];
  42435. for (j = 0; j < 3; ++j) {
  42436. v = t.vertices[j];
  42437. v.triangleCount++;
  42438. }
  42439. }
  42440. var tStart = 0;
  42441. for (i = 0; i < this.vertices.length; ++i) {
  42442. this.vertices[i].triangleStart = tStart;
  42443. tStart += this.vertices[i].triangleCount;
  42444. this.vertices[i].triangleCount = 0;
  42445. }
  42446. var newReferences = new Array(this.triangles.length * 3);
  42447. for (i = 0; i < this.triangles.length; ++i) {
  42448. t = this.triangles[i];
  42449. for (j = 0; j < 3; ++j) {
  42450. v = t.vertices[j];
  42451. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  42452. v.triangleCount++;
  42453. }
  42454. }
  42455. this.references = newReferences;
  42456. if (identifyBorders) {
  42457. this.identifyBorder();
  42458. }
  42459. };
  42460. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  42461. var x = point.x;
  42462. var y = point.y;
  42463. var z = point.z;
  42464. 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
  42465. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  42466. };
  42467. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  42468. var q = vertex1.q.add(vertex2.q);
  42469. var border = vertex1.isBorder && vertex2.isBorder;
  42470. var error = 0;
  42471. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  42472. if (qDet !== 0 && !border) {
  42473. if (!pointResult) {
  42474. pointResult = BABYLON.Vector3.Zero();
  42475. }
  42476. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  42477. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  42478. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  42479. error = this.vertexError(q, pointResult);
  42480. }
  42481. else {
  42482. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  42483. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  42484. var error1 = this.vertexError(q, vertex1.position);
  42485. var error2 = this.vertexError(q, vertex2.position);
  42486. var error3 = this.vertexError(q, p3);
  42487. error = Math.min(error1, error2, error3);
  42488. if (error === error1) {
  42489. if (pointResult) {
  42490. pointResult.copyFrom(vertex1.position);
  42491. }
  42492. }
  42493. else if (error === error2) {
  42494. if (pointResult) {
  42495. pointResult.copyFrom(vertex2.position);
  42496. }
  42497. }
  42498. else {
  42499. if (pointResult) {
  42500. pointResult.copyFrom(p3);
  42501. }
  42502. }
  42503. }
  42504. return error;
  42505. };
  42506. return QuadraticErrorSimplification;
  42507. }());
  42508. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  42509. })(BABYLON || (BABYLON = {}));
  42510. //# sourceMappingURL=babylon.meshSimplification.js.map
  42511. var BABYLON;
  42512. (function (BABYLON) {
  42513. var serializedGeometries = [];
  42514. var serializeGeometry = function (geometry, serializationGeometries) {
  42515. if (serializedGeometries[geometry.id]) {
  42516. return;
  42517. }
  42518. if (geometry.doNotSerialize) {
  42519. return;
  42520. }
  42521. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  42522. serializationGeometries.boxes.push(geometry.serialize());
  42523. }
  42524. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  42525. serializationGeometries.spheres.push(geometry.serialize());
  42526. }
  42527. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  42528. serializationGeometries.cylinders.push(geometry.serialize());
  42529. }
  42530. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  42531. serializationGeometries.toruses.push(geometry.serialize());
  42532. }
  42533. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  42534. serializationGeometries.grounds.push(geometry.serialize());
  42535. }
  42536. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  42537. serializationGeometries.planes.push(geometry.serialize());
  42538. }
  42539. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  42540. serializationGeometries.torusKnots.push(geometry.serialize());
  42541. }
  42542. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  42543. throw new Error("Unknown primitive type");
  42544. }
  42545. else {
  42546. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  42547. }
  42548. serializedGeometries[geometry.id] = true;
  42549. };
  42550. var serializeMesh = function (mesh, serializationScene) {
  42551. var serializationObject = {};
  42552. serializationObject.name = mesh.name;
  42553. serializationObject.id = mesh.id;
  42554. if (BABYLON.Tags.HasTags(mesh)) {
  42555. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  42556. }
  42557. serializationObject.position = mesh.position.asArray();
  42558. if (mesh.rotationQuaternion) {
  42559. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  42560. }
  42561. else if (mesh.rotation) {
  42562. serializationObject.rotation = mesh.rotation.asArray();
  42563. }
  42564. serializationObject.scaling = mesh.scaling.asArray();
  42565. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  42566. serializationObject.isEnabled = mesh.isEnabled();
  42567. serializationObject.isVisible = mesh.isVisible;
  42568. serializationObject.infiniteDistance = mesh.infiniteDistance;
  42569. serializationObject.pickable = mesh.isPickable;
  42570. serializationObject.receiveShadows = mesh.receiveShadows;
  42571. serializationObject.billboardMode = mesh.billboardMode;
  42572. serializationObject.visibility = mesh.visibility;
  42573. serializationObject.checkCollisions = mesh.checkCollisions;
  42574. serializationObject.isBlocker = mesh.isBlocker;
  42575. // Parent
  42576. if (mesh.parent) {
  42577. serializationObject.parentId = mesh.parent.id;
  42578. }
  42579. // Geometry
  42580. var geometry = mesh._geometry;
  42581. if (geometry) {
  42582. var geometryId = geometry.id;
  42583. serializationObject.geometryId = geometryId;
  42584. if (!mesh.getScene().getGeometryByID(geometryId)) {
  42585. // 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
  42586. serializeGeometry(geometry, serializationScene.geometries);
  42587. }
  42588. // SubMeshes
  42589. serializationObject.subMeshes = [];
  42590. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42591. var subMesh = mesh.subMeshes[subIndex];
  42592. serializationObject.subMeshes.push({
  42593. materialIndex: subMesh.materialIndex,
  42594. verticesStart: subMesh.verticesStart,
  42595. verticesCount: subMesh.verticesCount,
  42596. indexStart: subMesh.indexStart,
  42597. indexCount: subMesh.indexCount
  42598. });
  42599. }
  42600. }
  42601. // Material
  42602. if (mesh.material) {
  42603. serializationObject.materialId = mesh.material.id;
  42604. }
  42605. else {
  42606. mesh.material = null;
  42607. }
  42608. // Skeleton
  42609. if (mesh.skeleton) {
  42610. serializationObject.skeletonId = mesh.skeleton.id;
  42611. }
  42612. // Physics
  42613. //TODO implement correct serialization for physics impostors.
  42614. if (mesh.getPhysicsImpostor()) {
  42615. serializationObject.physicsMass = mesh.getPhysicsMass();
  42616. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  42617. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  42618. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  42619. }
  42620. // Metadata
  42621. if (mesh.metadata) {
  42622. serializationObject.metadata = mesh.metadata;
  42623. }
  42624. // Instances
  42625. serializationObject.instances = [];
  42626. for (var index = 0; index < mesh.instances.length; index++) {
  42627. var instance = mesh.instances[index];
  42628. var serializationInstance = {
  42629. name: instance.name,
  42630. position: instance.position.asArray(),
  42631. scaling: instance.scaling.asArray()
  42632. };
  42633. if (instance.rotationQuaternion) {
  42634. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  42635. }
  42636. else if (instance.rotation) {
  42637. serializationInstance.rotation = instance.rotation.asArray();
  42638. }
  42639. serializationObject.instances.push(serializationInstance);
  42640. // Animations
  42641. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  42642. serializationInstance.ranges = instance.serializeAnimationRanges();
  42643. }
  42644. // Animations
  42645. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  42646. serializationObject.ranges = mesh.serializeAnimationRanges();
  42647. // Layer mask
  42648. serializationObject.layerMask = mesh.layerMask;
  42649. // Alpha
  42650. serializationObject.alphaIndex = mesh.alphaIndex;
  42651. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  42652. // Overlay
  42653. serializationObject.overlayAlpha = mesh.overlayAlpha;
  42654. serializationObject.overlayColor = mesh.overlayColor.asArray();
  42655. serializationObject.renderOverlay = mesh.renderOverlay;
  42656. // Fog
  42657. serializationObject.applyFog = mesh.applyFog;
  42658. // Action Manager
  42659. if (mesh.actionManager) {
  42660. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  42661. }
  42662. return serializationObject;
  42663. };
  42664. var finalizeSingleMesh = function (mesh, serializationObject) {
  42665. //only works if the mesh is already loaded
  42666. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42667. //serialize material
  42668. if (mesh.material) {
  42669. if (mesh.material instanceof BABYLON.StandardMaterial) {
  42670. serializationObject.materials = serializationObject.materials || [];
  42671. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42672. serializationObject.materials.push(mesh.material.serialize());
  42673. }
  42674. }
  42675. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  42676. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  42677. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42678. serializationObject.multiMaterials.push(mesh.material.serialize());
  42679. }
  42680. }
  42681. }
  42682. //serialize geometry
  42683. var geometry = mesh._geometry;
  42684. if (geometry) {
  42685. if (!serializationObject.geometries) {
  42686. serializationObject.geometries = {};
  42687. serializationObject.geometries.boxes = [];
  42688. serializationObject.geometries.spheres = [];
  42689. serializationObject.geometries.cylinders = [];
  42690. serializationObject.geometries.toruses = [];
  42691. serializationObject.geometries.grounds = [];
  42692. serializationObject.geometries.planes = [];
  42693. serializationObject.geometries.torusKnots = [];
  42694. serializationObject.geometries.vertexData = [];
  42695. }
  42696. serializeGeometry(geometry, serializationObject.geometries);
  42697. }
  42698. // Skeletons
  42699. if (mesh.skeleton) {
  42700. serializationObject.skeletons = serializationObject.skeletons || [];
  42701. serializationObject.skeletons.push(mesh.skeleton.serialize());
  42702. }
  42703. //serialize the actual mesh
  42704. serializationObject.meshes = serializationObject.meshes || [];
  42705. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42706. }
  42707. };
  42708. var SceneSerializer = (function () {
  42709. function SceneSerializer() {
  42710. }
  42711. SceneSerializer.ClearCache = function () {
  42712. serializedGeometries = [];
  42713. };
  42714. SceneSerializer.Serialize = function (scene) {
  42715. var serializationObject = {};
  42716. // Scene
  42717. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  42718. serializationObject.autoClear = scene.autoClear;
  42719. serializationObject.clearColor = scene.clearColor.asArray();
  42720. serializationObject.ambientColor = scene.ambientColor.asArray();
  42721. serializationObject.gravity = scene.gravity.asArray();
  42722. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  42723. serializationObject.workerCollisions = scene.workerCollisions;
  42724. // Fog
  42725. if (scene.fogMode && scene.fogMode !== 0) {
  42726. serializationObject.fogMode = scene.fogMode;
  42727. serializationObject.fogColor = scene.fogColor.asArray();
  42728. serializationObject.fogStart = scene.fogStart;
  42729. serializationObject.fogEnd = scene.fogEnd;
  42730. serializationObject.fogDensity = scene.fogDensity;
  42731. }
  42732. //Physics
  42733. if (scene.isPhysicsEnabled()) {
  42734. serializationObject.physicsEnabled = true;
  42735. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  42736. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  42737. }
  42738. // Metadata
  42739. if (scene.metadata) {
  42740. serializationObject.metadata = scene.metadata;
  42741. }
  42742. // Lights
  42743. serializationObject.lights = [];
  42744. var index;
  42745. var light;
  42746. for (index = 0; index < scene.lights.length; index++) {
  42747. light = scene.lights[index];
  42748. if (!light.doNotSerialize) {
  42749. serializationObject.lights.push(light.serialize());
  42750. }
  42751. }
  42752. // Cameras
  42753. serializationObject.cameras = [];
  42754. for (index = 0; index < scene.cameras.length; index++) {
  42755. var camera = scene.cameras[index];
  42756. if (!camera.doNotSerialize) {
  42757. serializationObject.cameras.push(camera.serialize());
  42758. }
  42759. }
  42760. if (scene.activeCamera) {
  42761. serializationObject.activeCameraID = scene.activeCamera.id;
  42762. }
  42763. // Animations
  42764. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  42765. // Materials
  42766. serializationObject.materials = [];
  42767. serializationObject.multiMaterials = [];
  42768. var material;
  42769. for (index = 0; index < scene.materials.length; index++) {
  42770. material = scene.materials[index];
  42771. if (!material.doNotSerialize) {
  42772. serializationObject.materials.push(material.serialize());
  42773. }
  42774. }
  42775. // MultiMaterials
  42776. serializationObject.multiMaterials = [];
  42777. for (index = 0; index < scene.multiMaterials.length; index++) {
  42778. var multiMaterial = scene.multiMaterials[index];
  42779. serializationObject.multiMaterials.push(multiMaterial.serialize());
  42780. }
  42781. // Skeletons
  42782. serializationObject.skeletons = [];
  42783. for (index = 0; index < scene.skeletons.length; index++) {
  42784. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  42785. }
  42786. // Geometries
  42787. serializationObject.geometries = {};
  42788. serializationObject.geometries.boxes = [];
  42789. serializationObject.geometries.spheres = [];
  42790. serializationObject.geometries.cylinders = [];
  42791. serializationObject.geometries.toruses = [];
  42792. serializationObject.geometries.grounds = [];
  42793. serializationObject.geometries.planes = [];
  42794. serializationObject.geometries.torusKnots = [];
  42795. serializationObject.geometries.vertexData = [];
  42796. serializedGeometries = [];
  42797. var geometries = scene.getGeometries();
  42798. for (index = 0; index < geometries.length; index++) {
  42799. var geometry = geometries[index];
  42800. if (geometry.isReady()) {
  42801. serializeGeometry(geometry, serializationObject.geometries);
  42802. }
  42803. }
  42804. // Meshes
  42805. serializationObject.meshes = [];
  42806. for (index = 0; index < scene.meshes.length; index++) {
  42807. var abstractMesh = scene.meshes[index];
  42808. if (abstractMesh instanceof BABYLON.Mesh) {
  42809. var mesh = abstractMesh;
  42810. if (!mesh.doNotSerialize) {
  42811. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42812. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42813. }
  42814. }
  42815. }
  42816. }
  42817. // Particles Systems
  42818. serializationObject.particleSystems = [];
  42819. for (index = 0; index < scene.particleSystems.length; index++) {
  42820. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  42821. }
  42822. // Lens flares
  42823. serializationObject.lensFlareSystems = [];
  42824. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  42825. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  42826. }
  42827. // Shadows
  42828. serializationObject.shadowGenerators = [];
  42829. for (index = 0; index < scene.lights.length; index++) {
  42830. light = scene.lights[index];
  42831. var shadowGenerator = light.getShadowGenerator();
  42832. // Only support serialization for official generator so far.
  42833. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  42834. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  42835. }
  42836. }
  42837. // Action Manager
  42838. if (scene.actionManager) {
  42839. serializationObject.actions = scene.actionManager.serialize("scene");
  42840. }
  42841. // Audio
  42842. serializationObject.sounds = [];
  42843. for (index = 0; index < scene.soundTracks.length; index++) {
  42844. var soundtrack = scene.soundTracks[index];
  42845. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  42846. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  42847. }
  42848. }
  42849. return serializationObject;
  42850. };
  42851. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  42852. if (withParents === void 0) { withParents = false; }
  42853. if (withChildren === void 0) { withChildren = false; }
  42854. var serializationObject = {};
  42855. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  42856. if (withParents || withChildren) {
  42857. //deliberate for loop! not for each, appended should be processed as well.
  42858. for (var i = 0; i < toSerialize.length; ++i) {
  42859. if (withChildren) {
  42860. toSerialize[i].getDescendants().forEach(function (node) {
  42861. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  42862. toSerialize.push(node);
  42863. }
  42864. });
  42865. }
  42866. //make sure the array doesn't contain the object already
  42867. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  42868. toSerialize.push(toSerialize[i].parent);
  42869. }
  42870. }
  42871. }
  42872. toSerialize.forEach(function (mesh) {
  42873. finalizeSingleMesh(mesh, serializationObject);
  42874. });
  42875. return serializationObject;
  42876. };
  42877. return SceneSerializer;
  42878. }());
  42879. BABYLON.SceneSerializer = SceneSerializer;
  42880. })(BABYLON || (BABYLON = {}));
  42881. //# sourceMappingURL=babylon.sceneSerializer.js.map
  42882. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  42883. // Huge respect for a such great lib.
  42884. // Earcut license:
  42885. // Copyright (c) 2016, Mapbox
  42886. //
  42887. // Permission to use, copy, modify, and/or distribute this software for any purpose
  42888. // with or without fee is hereby granted, provided that the above copyright notice
  42889. // and this permission notice appear in all copies.
  42890. //
  42891. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  42892. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  42893. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  42894. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  42895. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  42896. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  42897. // THIS SOFTWARE.
  42898. var Earcut;
  42899. (function (Earcut) {
  42900. /**
  42901. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  42902. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  42903. * @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).
  42904. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  42905. */
  42906. function earcut(data, holeIndices, dim) {
  42907. dim = dim || 2;
  42908. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  42909. if (!outerNode)
  42910. return triangles;
  42911. var minX, minY, maxX, maxY, x, y, size;
  42912. if (hasHoles)
  42913. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  42914. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  42915. if (data.length > 80 * dim) {
  42916. minX = maxX = data[0];
  42917. minY = maxY = data[1];
  42918. for (var i = dim; i < outerLen; i += dim) {
  42919. x = data[i];
  42920. y = data[i + 1];
  42921. if (x < minX)
  42922. minX = x;
  42923. if (y < minY)
  42924. minY = y;
  42925. if (x > maxX)
  42926. maxX = x;
  42927. if (y > maxY)
  42928. maxY = y;
  42929. }
  42930. // minX, minY and size are later used to transform coords into integers for z-order calculation
  42931. size = Math.max(maxX - minX, maxY - minY);
  42932. }
  42933. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  42934. return triangles;
  42935. }
  42936. Earcut.earcut = earcut;
  42937. // create a circular doubly linked list from polygon points in the specified winding order
  42938. function linkedList(data, start, end, dim, clockwise) {
  42939. var i, last;
  42940. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  42941. for (i = start; i < end; i += dim)
  42942. last = insertNode(i, data[i], data[i + 1], last);
  42943. }
  42944. else {
  42945. for (i = end - dim; i >= start; i -= dim)
  42946. last = insertNode(i, data[i], data[i + 1], last);
  42947. }
  42948. if (last && equals(last, last.next)) {
  42949. removeNode(last);
  42950. last = last.next;
  42951. }
  42952. return last;
  42953. }
  42954. // eliminate colinear or duplicate points
  42955. function filterPoints(start, end) {
  42956. if (!start)
  42957. return start;
  42958. if (!end)
  42959. end = start;
  42960. var p = start, again;
  42961. do {
  42962. again = false;
  42963. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  42964. removeNode(p);
  42965. p = end = p.prev;
  42966. if (p === p.next)
  42967. return null;
  42968. again = true;
  42969. }
  42970. else {
  42971. p = p.next;
  42972. }
  42973. } while (again || p !== end);
  42974. return end;
  42975. }
  42976. // main ear slicing loop which triangulates a polygon (given as a linked list)
  42977. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  42978. if (!ear)
  42979. return;
  42980. // interlink polygon nodes in z-order
  42981. if (!pass && size)
  42982. indexCurve(ear, minX, minY, size);
  42983. var stop = ear, prev, next;
  42984. // iterate through ears, slicing them one by one
  42985. while (ear.prev !== ear.next) {
  42986. prev = ear.prev;
  42987. next = ear.next;
  42988. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  42989. // cut off the triangle
  42990. triangles.push(prev.i / dim);
  42991. triangles.push(ear.i / dim);
  42992. triangles.push(next.i / dim);
  42993. removeNode(ear);
  42994. // skipping the next vertice leads to less sliver triangles
  42995. ear = next.next;
  42996. stop = next.next;
  42997. continue;
  42998. }
  42999. ear = next;
  43000. // if we looped through the whole remaining polygon and can't find any more ears
  43001. if (ear === stop) {
  43002. // try filtering points and slicing again
  43003. if (!pass) {
  43004. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  43005. }
  43006. else if (pass === 1) {
  43007. ear = cureLocalIntersections(ear, triangles, dim);
  43008. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43009. }
  43010. else if (pass === 2) {
  43011. splitEarcut(ear, triangles, dim, minX, minY, size);
  43012. }
  43013. break;
  43014. }
  43015. }
  43016. }
  43017. // check whether a polygon node forms a valid ear with adjacent nodes
  43018. function isEar(ear) {
  43019. var a = ear.prev, b = ear, c = ear.next;
  43020. if (area(a, b, c) >= 0)
  43021. return false; // reflex, can't be an ear
  43022. // now make sure we don't have other points inside the potential ear
  43023. var p = ear.next.next;
  43024. while (p !== ear.prev) {
  43025. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43026. area(p.prev, p, p.next) >= 0)
  43027. return false;
  43028. p = p.next;
  43029. }
  43030. return true;
  43031. }
  43032. function isEarHashed(ear, minX, minY, size) {
  43033. var a = ear.prev, b = ear, c = ear.next;
  43034. if (area(a, b, c) >= 0)
  43035. return false; // reflex, can't be an ear
  43036. // triangle bbox; min & max are calculated like this for speed
  43037. 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);
  43038. // z-order range for the current triangle bbox;
  43039. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43040. // first look for points inside the triangle in increasing z-order
  43041. var p = ear.nextZ;
  43042. while (p && p.z <= maxZ) {
  43043. if (p !== ear.prev &&
  43044. p !== ear.next &&
  43045. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43046. area(p.prev, p, p.next) >= 0)
  43047. return false;
  43048. p = p.nextZ;
  43049. }
  43050. // then look for points in decreasing z-order
  43051. p = ear.prevZ;
  43052. while (p && p.z >= minZ) {
  43053. if (p !== ear.prev &&
  43054. p !== ear.next &&
  43055. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43056. area(p.prev, p, p.next) >= 0)
  43057. return false;
  43058. p = p.prevZ;
  43059. }
  43060. return true;
  43061. }
  43062. // go through all polygon nodes and cure small local self-intersections
  43063. function cureLocalIntersections(start, triangles, dim) {
  43064. var p = start;
  43065. do {
  43066. var a = p.prev, b = p.next.next;
  43067. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43068. triangles.push(a.i / dim);
  43069. triangles.push(p.i / dim);
  43070. triangles.push(b.i / dim);
  43071. // remove two nodes involved
  43072. removeNode(p);
  43073. removeNode(p.next);
  43074. p = start = b;
  43075. }
  43076. p = p.next;
  43077. } while (p !== start);
  43078. return p;
  43079. }
  43080. // try splitting polygon into two and triangulate them independently
  43081. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43082. // look for a valid diagonal that divides the polygon into two
  43083. var a = start;
  43084. do {
  43085. var b = a.next.next;
  43086. while (b !== a.prev) {
  43087. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43088. // split the polygon in two by the diagonal
  43089. var c = splitPolygon(a, b);
  43090. // filter colinear points around the cuts
  43091. a = filterPoints(a, a.next);
  43092. c = filterPoints(c, c.next);
  43093. // run earcut on each half
  43094. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43095. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43096. return;
  43097. }
  43098. b = b.next;
  43099. }
  43100. a = a.next;
  43101. } while (a !== start);
  43102. }
  43103. // link every hole into the outer loop, producing a single-ring polygon without holes
  43104. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43105. var queue = [], i, len, start, end, list;
  43106. for (i = 0, len = holeIndices.length; i < len; i++) {
  43107. start = holeIndices[i] * dim;
  43108. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43109. list = linkedList(data, start, end, dim, false);
  43110. if (list === list.next)
  43111. list.steiner = true;
  43112. queue.push(getLeftmost(list));
  43113. }
  43114. queue.sort(compareX);
  43115. // process holes from left to right
  43116. for (i = 0; i < queue.length; i++) {
  43117. eliminateHole(queue[i], outerNode);
  43118. outerNode = filterPoints(outerNode, outerNode.next);
  43119. }
  43120. return outerNode;
  43121. }
  43122. function compareX(a, b) {
  43123. return a.x - b.x;
  43124. }
  43125. // find a bridge between vertices that connects hole with an outer ring and and link it
  43126. function eliminateHole(hole, outerNode) {
  43127. outerNode = findHoleBridge(hole, outerNode);
  43128. if (outerNode) {
  43129. var b = splitPolygon(outerNode, hole);
  43130. filterPoints(b, b.next);
  43131. }
  43132. }
  43133. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43134. function findHoleBridge(hole, outerNode) {
  43135. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43136. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43137. // segment's endpoint with lesser x will be potential connection point
  43138. do {
  43139. if (hy <= p.y && hy >= p.next.y) {
  43140. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43141. if (x <= hx && x > qx) {
  43142. qx = x;
  43143. if (x === hx) {
  43144. if (hy === p.y)
  43145. return p;
  43146. if (hy === p.next.y)
  43147. return p.next;
  43148. }
  43149. m = p.x < p.next.x ? p : p.next;
  43150. }
  43151. }
  43152. p = p.next;
  43153. } while (p !== outerNode);
  43154. if (!m)
  43155. return null;
  43156. if (hx === qx)
  43157. return m.prev; // hole touches outer segment; pick lower endpoint
  43158. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43159. // if there are no points found, we have a valid connection;
  43160. // otherwise choose the point of the minimum angle with the ray as connection point
  43161. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43162. p = m.next;
  43163. while (p !== stop) {
  43164. if (hx >= p.x &&
  43165. p.x >= mx &&
  43166. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43167. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43168. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43169. m = p;
  43170. tanMin = tan;
  43171. }
  43172. }
  43173. p = p.next;
  43174. }
  43175. return m;
  43176. }
  43177. // interlink polygon nodes in z-order
  43178. function indexCurve(start, minX, minY, size) {
  43179. var p = start;
  43180. do {
  43181. if (p.z === null)
  43182. p.z = zOrder(p.x, p.y, minX, minY, size);
  43183. p.prevZ = p.prev;
  43184. p.nextZ = p.next;
  43185. p = p.next;
  43186. } while (p !== start);
  43187. p.prevZ.nextZ = null;
  43188. p.prevZ = null;
  43189. sortLinked(p);
  43190. }
  43191. // Simon Tatham's linked list merge sort algorithm
  43192. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43193. function sortLinked(list) {
  43194. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43195. do {
  43196. p = list;
  43197. list = null;
  43198. tail = null;
  43199. numMerges = 0;
  43200. while (p) {
  43201. numMerges++;
  43202. q = p;
  43203. pSize = 0;
  43204. for (i = 0; i < inSize; i++) {
  43205. pSize++;
  43206. q = q.nextZ;
  43207. if (!q)
  43208. break;
  43209. }
  43210. qSize = inSize;
  43211. while (pSize > 0 || (qSize > 0 && q)) {
  43212. if (pSize === 0) {
  43213. e = q;
  43214. q = q.nextZ;
  43215. qSize--;
  43216. }
  43217. else if (qSize === 0 || !q) {
  43218. e = p;
  43219. p = p.nextZ;
  43220. pSize--;
  43221. }
  43222. else if (p.z <= q.z) {
  43223. e = p;
  43224. p = p.nextZ;
  43225. pSize--;
  43226. }
  43227. else {
  43228. e = q;
  43229. q = q.nextZ;
  43230. qSize--;
  43231. }
  43232. if (tail)
  43233. tail.nextZ = e;
  43234. else
  43235. list = e;
  43236. e.prevZ = tail;
  43237. tail = e;
  43238. }
  43239. p = q;
  43240. }
  43241. tail.nextZ = null;
  43242. inSize *= 2;
  43243. } while (numMerges > 1);
  43244. return list;
  43245. }
  43246. // z-order of a point given coords and size of the data bounding box
  43247. function zOrder(x, y, minX, minY, size) {
  43248. // coords are transformed into non-negative 15-bit integer range
  43249. x = 32767 * (x - minX) / size;
  43250. y = 32767 * (y - minY) / size;
  43251. x = (x | (x << 8)) & 0x00FF00FF;
  43252. x = (x | (x << 4)) & 0x0F0F0F0F;
  43253. x = (x | (x << 2)) & 0x33333333;
  43254. x = (x | (x << 1)) & 0x55555555;
  43255. y = (y | (y << 8)) & 0x00FF00FF;
  43256. y = (y | (y << 4)) & 0x0F0F0F0F;
  43257. y = (y | (y << 2)) & 0x33333333;
  43258. y = (y | (y << 1)) & 0x55555555;
  43259. return x | (y << 1);
  43260. }
  43261. // find the leftmost node of a polygon ring
  43262. function getLeftmost(start) {
  43263. var p = start, leftmost = start;
  43264. do {
  43265. if (p.x < leftmost.x)
  43266. leftmost = p;
  43267. p = p.next;
  43268. } while (p !== start);
  43269. return leftmost;
  43270. }
  43271. // check if a point lies within a convex triangle
  43272. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43273. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43274. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43275. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43276. }
  43277. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43278. function isValidDiagonal(a, b) {
  43279. return a.next.i !== b.i &&
  43280. a.prev.i !== b.i &&
  43281. !intersectsPolygon(a, b) &&
  43282. locallyInside(a, b) &&
  43283. locallyInside(b, a) &&
  43284. middleInside(a, b);
  43285. }
  43286. // signed area of a triangle
  43287. function area(p, q, r) {
  43288. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43289. }
  43290. // check if two points are equal
  43291. function equals(p1, p2) {
  43292. return p1.x === p2.x && p1.y === p2.y;
  43293. }
  43294. // check if two segments intersect
  43295. function intersects(p1, q1, p2, q2) {
  43296. if ((equals(p1, q1) && equals(p2, q2)) ||
  43297. (equals(p1, q2) && equals(p2, q1)))
  43298. return true;
  43299. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43300. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43301. }
  43302. // check if a polygon diagonal intersects any polygon segments
  43303. function intersectsPolygon(a, b) {
  43304. var p = a;
  43305. do {
  43306. if (p.i !== a.i &&
  43307. p.next.i !== a.i &&
  43308. p.i !== b.i &&
  43309. p.next.i !== b.i &&
  43310. intersects(p, p.next, a, b))
  43311. return true;
  43312. p = p.next;
  43313. } while (p !== a);
  43314. return false;
  43315. }
  43316. // check if a polygon diagonal is locally inside the polygon
  43317. function locallyInside(a, b) {
  43318. return area(a.prev, a, a.next) < 0
  43319. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43320. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43321. }
  43322. // check if the middle point of a polygon diagonal is inside the polygon
  43323. function middleInside(a, b) {
  43324. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43325. do {
  43326. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43327. inside = !inside;
  43328. p = p.next;
  43329. } while (p !== a);
  43330. return inside;
  43331. }
  43332. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43333. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43334. function splitPolygon(a, b) {
  43335. 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;
  43336. a.next = b;
  43337. b.prev = a;
  43338. a2.next = an;
  43339. an.prev = a2;
  43340. b2.next = a2;
  43341. a2.prev = b2;
  43342. bp.next = b2;
  43343. b2.prev = bp;
  43344. return b2;
  43345. }
  43346. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43347. function insertNode(i, x, y, last) {
  43348. var p = new Node(i, x, y);
  43349. if (!last) {
  43350. p.prev = p;
  43351. p.next = p;
  43352. }
  43353. else {
  43354. p.next = last.next;
  43355. p.prev = last;
  43356. last.next.prev = p;
  43357. last.next = p;
  43358. }
  43359. return p;
  43360. }
  43361. function removeNode(p) {
  43362. p.next.prev = p.prev;
  43363. p.prev.next = p.next;
  43364. if (p.prevZ)
  43365. p.prevZ.nextZ = p.nextZ;
  43366. if (p.nextZ)
  43367. p.nextZ.prevZ = p.prevZ;
  43368. }
  43369. function Node(i, x, y) {
  43370. // vertice index in coordinates array
  43371. this.i = i;
  43372. // vertex coordinates
  43373. this.x = x;
  43374. this.y = y;
  43375. // previous and next vertice nodes in a polygon ring
  43376. this.prev = null;
  43377. this.next = null;
  43378. // z-order curve value
  43379. this.z = null;
  43380. // previous and next nodes in z-order
  43381. this.prevZ = null;
  43382. this.nextZ = null;
  43383. // indicates whether this is a steiner point
  43384. this.steiner = false;
  43385. }
  43386. /**
  43387. * return a percentage difference between the polygon area and its triangulation area;
  43388. * used to verify correctness of triangulation
  43389. */
  43390. function deviation(data, holeIndices, dim, triangles) {
  43391. var hasHoles = holeIndices && holeIndices.length;
  43392. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  43393. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  43394. if (hasHoles) {
  43395. for (var i = 0, len = holeIndices.length; i < len; i++) {
  43396. var start = holeIndices[i] * dim;
  43397. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43398. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  43399. }
  43400. }
  43401. var trianglesArea = 0;
  43402. for (i = 0; i < triangles.length; i += 3) {
  43403. var a = triangles[i] * dim;
  43404. var b = triangles[i + 1] * dim;
  43405. var c = triangles[i + 2] * dim;
  43406. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  43407. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  43408. }
  43409. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  43410. }
  43411. Earcut.deviation = deviation;
  43412. ;
  43413. function signedArea(data, start, end, dim) {
  43414. var sum = 0;
  43415. for (var i = start, j = end - dim; i < end; i += dim) {
  43416. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  43417. j = i;
  43418. }
  43419. return sum;
  43420. }
  43421. /**
  43422. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  43423. */
  43424. function flatten(data) {
  43425. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  43426. for (var i = 0; i < data.length; i++) {
  43427. for (var j = 0; j < data[i].length; j++) {
  43428. for (var d = 0; d < dim; d++)
  43429. result.vertices.push(data[i][j][d]);
  43430. }
  43431. if (i > 0) {
  43432. holeIndex += data[i - 1].length;
  43433. result.holes.push(holeIndex);
  43434. }
  43435. }
  43436. return result;
  43437. }
  43438. Earcut.flatten = flatten;
  43439. ;
  43440. })(Earcut || (Earcut = {}));
  43441. //# sourceMappingURL=babylon.earcut.js.map
  43442. var BABYLON;
  43443. (function (BABYLON) {
  43444. // Unique ID when we import meshes from Babylon to CSG
  43445. var currentCSGMeshId = 0;
  43446. // # class Vertex
  43447. // Represents a vertex of a polygon. Use your own vertex class instead of this
  43448. // one to provide additional features like texture coordinates and vertex
  43449. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  43450. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  43451. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  43452. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  43453. // is not used anywhere else.
  43454. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  43455. var Vertex = (function () {
  43456. function Vertex(pos, normal, uv) {
  43457. this.pos = pos;
  43458. this.normal = normal;
  43459. this.uv = uv;
  43460. }
  43461. Vertex.prototype.clone = function () {
  43462. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43463. };
  43464. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  43465. // orientation of a polygon is flipped.
  43466. Vertex.prototype.flip = function () {
  43467. this.normal = this.normal.scale(-1);
  43468. };
  43469. // Create a new vertex between this vertex and `other` by linearly
  43470. // interpolating all properties using a parameter of `t`. Subclasses should
  43471. // override this to interpolate additional properties.
  43472. Vertex.prototype.interpolate = function (other, t) {
  43473. 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));
  43474. };
  43475. return Vertex;
  43476. }());
  43477. // # class Plane
  43478. // Represents a plane in 3D space.
  43479. var Plane = (function () {
  43480. function Plane(normal, w) {
  43481. this.normal = normal;
  43482. this.w = w;
  43483. }
  43484. Plane.FromPoints = function (a, b, c) {
  43485. var v0 = c.subtract(a);
  43486. var v1 = b.subtract(a);
  43487. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  43488. return null;
  43489. }
  43490. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  43491. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  43492. };
  43493. Plane.prototype.clone = function () {
  43494. return new Plane(this.normal.clone(), this.w);
  43495. };
  43496. Plane.prototype.flip = function () {
  43497. this.normal.scaleInPlace(-1);
  43498. this.w = -this.w;
  43499. };
  43500. // Split `polygon` by this plane if needed, then put the polygon or polygon
  43501. // fragments in the appropriate lists. Coplanar polygons go into either
  43502. // `coplanarFront` or `coplanarBack` depending on their orientation with
  43503. // respect to this plane. Polygons in front or in back of this plane go into
  43504. // either `front` or `back`.
  43505. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  43506. var COPLANAR = 0;
  43507. var FRONT = 1;
  43508. var BACK = 2;
  43509. var SPANNING = 3;
  43510. // Classify each point as well as the entire polygon into one of the above
  43511. // four classes.
  43512. var polygonType = 0;
  43513. var types = [];
  43514. var i;
  43515. var t;
  43516. for (i = 0; i < polygon.vertices.length; i++) {
  43517. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  43518. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  43519. polygonType |= type;
  43520. types.push(type);
  43521. }
  43522. // Put the polygon in the correct list, splitting it when necessary.
  43523. switch (polygonType) {
  43524. case COPLANAR:
  43525. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  43526. break;
  43527. case FRONT:
  43528. front.push(polygon);
  43529. break;
  43530. case BACK:
  43531. back.push(polygon);
  43532. break;
  43533. case SPANNING:
  43534. var f = [], b = [];
  43535. for (i = 0; i < polygon.vertices.length; i++) {
  43536. var j = (i + 1) % polygon.vertices.length;
  43537. var ti = types[i], tj = types[j];
  43538. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  43539. if (ti !== BACK)
  43540. f.push(vi);
  43541. if (ti !== FRONT)
  43542. b.push(ti !== BACK ? vi.clone() : vi);
  43543. if ((ti | tj) === SPANNING) {
  43544. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  43545. var v = vi.interpolate(vj, t);
  43546. f.push(v);
  43547. b.push(v.clone());
  43548. }
  43549. }
  43550. var poly;
  43551. if (f.length >= 3) {
  43552. poly = new Polygon(f, polygon.shared);
  43553. if (poly.plane)
  43554. front.push(poly);
  43555. }
  43556. if (b.length >= 3) {
  43557. poly = new Polygon(b, polygon.shared);
  43558. if (poly.plane)
  43559. back.push(poly);
  43560. }
  43561. break;
  43562. }
  43563. };
  43564. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  43565. // point is on the plane.
  43566. Plane.EPSILON = 1e-5;
  43567. return Plane;
  43568. }());
  43569. // # class Polygon
  43570. // Represents a convex polygon. The vertices used to initialize a polygon must
  43571. // be coplanar and form a convex loop.
  43572. //
  43573. // Each convex polygon has a `shared` property, which is shared between all
  43574. // polygons that are clones of each other or were split from the same polygon.
  43575. // This can be used to define per-polygon properties (such as surface color).
  43576. var Polygon = (function () {
  43577. function Polygon(vertices, shared) {
  43578. this.vertices = vertices;
  43579. this.shared = shared;
  43580. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  43581. }
  43582. Polygon.prototype.clone = function () {
  43583. var vertices = this.vertices.map(function (v) { return v.clone(); });
  43584. return new Polygon(vertices, this.shared);
  43585. };
  43586. Polygon.prototype.flip = function () {
  43587. this.vertices.reverse().map(function (v) { v.flip(); });
  43588. this.plane.flip();
  43589. };
  43590. return Polygon;
  43591. }());
  43592. // # class Node
  43593. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  43594. // by picking a polygon to split along. That polygon (and all other coplanar
  43595. // polygons) are added directly to that node and the other polygons are added to
  43596. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  43597. // no distinction between internal and leaf nodes.
  43598. var Node = (function () {
  43599. function Node(polygons) {
  43600. this.plane = null;
  43601. this.front = null;
  43602. this.back = null;
  43603. this.polygons = [];
  43604. if (polygons) {
  43605. this.build(polygons);
  43606. }
  43607. }
  43608. Node.prototype.clone = function () {
  43609. var node = new Node();
  43610. node.plane = this.plane && this.plane.clone();
  43611. node.front = this.front && this.front.clone();
  43612. node.back = this.back && this.back.clone();
  43613. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  43614. return node;
  43615. };
  43616. // Convert solid space to empty space and empty space to solid space.
  43617. Node.prototype.invert = function () {
  43618. for (var i = 0; i < this.polygons.length; i++) {
  43619. this.polygons[i].flip();
  43620. }
  43621. if (this.plane) {
  43622. this.plane.flip();
  43623. }
  43624. if (this.front) {
  43625. this.front.invert();
  43626. }
  43627. if (this.back) {
  43628. this.back.invert();
  43629. }
  43630. var temp = this.front;
  43631. this.front = this.back;
  43632. this.back = temp;
  43633. };
  43634. // Recursively remove all polygons in `polygons` that are inside this BSP
  43635. // tree.
  43636. Node.prototype.clipPolygons = function (polygons) {
  43637. if (!this.plane)
  43638. return polygons.slice();
  43639. var front = [], back = [];
  43640. for (var i = 0; i < polygons.length; i++) {
  43641. this.plane.splitPolygon(polygons[i], front, back, front, back);
  43642. }
  43643. if (this.front) {
  43644. front = this.front.clipPolygons(front);
  43645. }
  43646. if (this.back) {
  43647. back = this.back.clipPolygons(back);
  43648. }
  43649. else {
  43650. back = [];
  43651. }
  43652. return front.concat(back);
  43653. };
  43654. // Remove all polygons in this BSP tree that are inside the other BSP tree
  43655. // `bsp`.
  43656. Node.prototype.clipTo = function (bsp) {
  43657. this.polygons = bsp.clipPolygons(this.polygons);
  43658. if (this.front)
  43659. this.front.clipTo(bsp);
  43660. if (this.back)
  43661. this.back.clipTo(bsp);
  43662. };
  43663. // Return a list of all polygons in this BSP tree.
  43664. Node.prototype.allPolygons = function () {
  43665. var polygons = this.polygons.slice();
  43666. if (this.front)
  43667. polygons = polygons.concat(this.front.allPolygons());
  43668. if (this.back)
  43669. polygons = polygons.concat(this.back.allPolygons());
  43670. return polygons;
  43671. };
  43672. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  43673. // new polygons are filtered down to the bottom of the tree and become new
  43674. // nodes there. Each set of polygons is partitioned using the first polygon
  43675. // (no heuristic is used to pick a good split).
  43676. Node.prototype.build = function (polygons) {
  43677. if (!polygons.length)
  43678. return;
  43679. if (!this.plane)
  43680. this.plane = polygons[0].plane.clone();
  43681. var front = [], back = [];
  43682. for (var i = 0; i < polygons.length; i++) {
  43683. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  43684. }
  43685. if (front.length) {
  43686. if (!this.front)
  43687. this.front = new Node();
  43688. this.front.build(front);
  43689. }
  43690. if (back.length) {
  43691. if (!this.back)
  43692. this.back = new Node();
  43693. this.back.build(back);
  43694. }
  43695. };
  43696. return Node;
  43697. }());
  43698. var CSG = (function () {
  43699. function CSG() {
  43700. this.polygons = new Array();
  43701. }
  43702. // Convert BABYLON.Mesh to BABYLON.CSG
  43703. CSG.FromMesh = function (mesh) {
  43704. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  43705. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  43706. if (mesh instanceof BABYLON.Mesh) {
  43707. mesh.computeWorldMatrix(true);
  43708. matrix = mesh.getWorldMatrix();
  43709. meshPosition = mesh.position.clone();
  43710. meshRotation = mesh.rotation.clone();
  43711. if (mesh.rotationQuaternion) {
  43712. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  43713. }
  43714. meshScaling = mesh.scaling.clone();
  43715. }
  43716. else {
  43717. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  43718. }
  43719. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43720. var subMeshes = mesh.subMeshes;
  43721. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  43722. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  43723. vertices = [];
  43724. for (var j = 0; j < 3; j++) {
  43725. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  43726. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  43727. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  43728. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  43729. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  43730. vertex = new Vertex(position, normal, uv);
  43731. vertices.push(vertex);
  43732. }
  43733. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  43734. // To handle the case of degenerated triangle
  43735. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  43736. if (polygon.plane)
  43737. polygons.push(polygon);
  43738. }
  43739. }
  43740. var csg = CSG.FromPolygons(polygons);
  43741. csg.matrix = matrix;
  43742. csg.position = meshPosition;
  43743. csg.rotation = meshRotation;
  43744. csg.scaling = meshScaling;
  43745. csg.rotationQuaternion = meshRotationQuaternion;
  43746. currentCSGMeshId++;
  43747. return csg;
  43748. };
  43749. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  43750. CSG.FromPolygons = function (polygons) {
  43751. var csg = new CSG();
  43752. csg.polygons = polygons;
  43753. return csg;
  43754. };
  43755. CSG.prototype.clone = function () {
  43756. var csg = new CSG();
  43757. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  43758. csg.copyTransformAttributes(this);
  43759. return csg;
  43760. };
  43761. CSG.prototype.toPolygons = function () {
  43762. return this.polygons;
  43763. };
  43764. CSG.prototype.union = function (csg) {
  43765. var a = new Node(this.clone().polygons);
  43766. var b = new Node(csg.clone().polygons);
  43767. a.clipTo(b);
  43768. b.clipTo(a);
  43769. b.invert();
  43770. b.clipTo(a);
  43771. b.invert();
  43772. a.build(b.allPolygons());
  43773. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43774. };
  43775. CSG.prototype.unionInPlace = function (csg) {
  43776. var a = new Node(this.polygons);
  43777. var b = new Node(csg.polygons);
  43778. a.clipTo(b);
  43779. b.clipTo(a);
  43780. b.invert();
  43781. b.clipTo(a);
  43782. b.invert();
  43783. a.build(b.allPolygons());
  43784. this.polygons = a.allPolygons();
  43785. };
  43786. CSG.prototype.subtract = function (csg) {
  43787. var a = new Node(this.clone().polygons);
  43788. var b = new Node(csg.clone().polygons);
  43789. a.invert();
  43790. a.clipTo(b);
  43791. b.clipTo(a);
  43792. b.invert();
  43793. b.clipTo(a);
  43794. b.invert();
  43795. a.build(b.allPolygons());
  43796. a.invert();
  43797. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43798. };
  43799. CSG.prototype.subtractInPlace = function (csg) {
  43800. var a = new Node(this.polygons);
  43801. var b = new Node(csg.polygons);
  43802. a.invert();
  43803. a.clipTo(b);
  43804. b.clipTo(a);
  43805. b.invert();
  43806. b.clipTo(a);
  43807. b.invert();
  43808. a.build(b.allPolygons());
  43809. a.invert();
  43810. this.polygons = a.allPolygons();
  43811. };
  43812. CSG.prototype.intersect = function (csg) {
  43813. var a = new Node(this.clone().polygons);
  43814. var b = new Node(csg.clone().polygons);
  43815. a.invert();
  43816. b.clipTo(a);
  43817. b.invert();
  43818. a.clipTo(b);
  43819. b.clipTo(a);
  43820. a.build(b.allPolygons());
  43821. a.invert();
  43822. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43823. };
  43824. CSG.prototype.intersectInPlace = function (csg) {
  43825. var a = new Node(this.polygons);
  43826. var b = new Node(csg.polygons);
  43827. a.invert();
  43828. b.clipTo(a);
  43829. b.invert();
  43830. a.clipTo(b);
  43831. b.clipTo(a);
  43832. a.build(b.allPolygons());
  43833. a.invert();
  43834. this.polygons = a.allPolygons();
  43835. };
  43836. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  43837. // not modified.
  43838. CSG.prototype.inverse = function () {
  43839. var csg = this.clone();
  43840. csg.inverseInPlace();
  43841. return csg;
  43842. };
  43843. CSG.prototype.inverseInPlace = function () {
  43844. this.polygons.map(function (p) { p.flip(); });
  43845. };
  43846. // This is used to keep meshes transformations so they can be restored
  43847. // when we build back a Babylon Mesh
  43848. // NB : All CSG operations are performed in world coordinates
  43849. CSG.prototype.copyTransformAttributes = function (csg) {
  43850. this.matrix = csg.matrix;
  43851. this.position = csg.position;
  43852. this.rotation = csg.rotation;
  43853. this.scaling = csg.scaling;
  43854. this.rotationQuaternion = csg.rotationQuaternion;
  43855. return this;
  43856. };
  43857. // Build Raw mesh from CSG
  43858. // Coordinates here are in world space
  43859. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  43860. var matrix = this.matrix.clone();
  43861. matrix.invert();
  43862. 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;
  43863. if (keepSubMeshes) {
  43864. // Sort Polygons, since subMeshes are indices range
  43865. polygons.sort(function (a, b) {
  43866. if (a.shared.meshId === b.shared.meshId) {
  43867. return a.shared.subMeshId - b.shared.subMeshId;
  43868. }
  43869. else {
  43870. return a.shared.meshId - b.shared.meshId;
  43871. }
  43872. });
  43873. }
  43874. for (var i = 0, il = polygons.length; i < il; i++) {
  43875. polygon = polygons[i];
  43876. // Building SubMeshes
  43877. if (!subMesh_dict[polygon.shared.meshId]) {
  43878. subMesh_dict[polygon.shared.meshId] = {};
  43879. }
  43880. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  43881. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  43882. indexStart: +Infinity,
  43883. indexEnd: -Infinity,
  43884. materialIndex: polygon.shared.materialIndex
  43885. };
  43886. }
  43887. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  43888. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  43889. polygonIndices[0] = 0;
  43890. polygonIndices[1] = j - 1;
  43891. polygonIndices[2] = j;
  43892. for (var k = 0; k < 3; k++) {
  43893. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  43894. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  43895. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  43896. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  43897. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  43898. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  43899. // Check if 2 points can be merged
  43900. if (!(typeof vertex_idx !== 'undefined' &&
  43901. normals[vertex_idx * 3] === localNormal.x &&
  43902. normals[vertex_idx * 3 + 1] === localNormal.y &&
  43903. normals[vertex_idx * 3 + 2] === localNormal.z &&
  43904. uvs[vertex_idx * 2] === uv.x &&
  43905. uvs[vertex_idx * 2 + 1] === uv.y)) {
  43906. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  43907. uvs.push(uv.x, uv.y);
  43908. normals.push(normal.x, normal.y, normal.z);
  43909. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  43910. }
  43911. indices.push(vertex_idx);
  43912. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  43913. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  43914. currentIndex++;
  43915. }
  43916. }
  43917. }
  43918. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  43919. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  43920. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  43921. mesh.setIndices(indices);
  43922. if (keepSubMeshes) {
  43923. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  43924. var materialIndexOffset = 0, materialMaxIndex;
  43925. mesh.subMeshes = new Array();
  43926. for (var m in subMesh_dict) {
  43927. materialMaxIndex = -1;
  43928. for (var sm in subMesh_dict[m]) {
  43929. subMesh_obj = subMesh_dict[m][sm];
  43930. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  43931. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  43932. }
  43933. materialIndexOffset += ++materialMaxIndex;
  43934. }
  43935. }
  43936. return mesh;
  43937. };
  43938. // Build Mesh from CSG taking material and transforms into account
  43939. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  43940. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  43941. mesh.material = material;
  43942. mesh.position.copyFrom(this.position);
  43943. mesh.rotation.copyFrom(this.rotation);
  43944. if (this.rotationQuaternion) {
  43945. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  43946. }
  43947. mesh.scaling.copyFrom(this.scaling);
  43948. mesh.computeWorldMatrix(true);
  43949. return mesh;
  43950. };
  43951. return CSG;
  43952. }());
  43953. BABYLON.CSG = CSG;
  43954. })(BABYLON || (BABYLON = {}));
  43955. //# sourceMappingURL=babylon.csg.js.map
  43956. var BABYLON;
  43957. (function (BABYLON) {
  43958. var VRDistortionCorrectionPostProcess = (function (_super) {
  43959. __extends(VRDistortionCorrectionPostProcess, _super);
  43960. //ANY
  43961. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  43962. var _this = this;
  43963. _super.call(this, name, "vrDistortionCorrection", [
  43964. 'LensCenter',
  43965. 'Scale',
  43966. 'ScaleIn',
  43967. 'HmdWarpParam'
  43968. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  43969. this._isRightEye = isRightEye;
  43970. this._distortionFactors = vrMetrics.distortionK;
  43971. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  43972. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  43973. this.onSizeChangedObservable.add(function () {
  43974. _this.aspectRatio = _this.width * .5 / _this.height;
  43975. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  43976. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  43977. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  43978. });
  43979. this.onApplyObservable.add(function (effect) {
  43980. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  43981. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  43982. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  43983. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  43984. });
  43985. }
  43986. return VRDistortionCorrectionPostProcess;
  43987. }(BABYLON.PostProcess));
  43988. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  43989. })(BABYLON || (BABYLON = {}));
  43990. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  43991. // Mainly based on these 2 articles :
  43992. // 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
  43993. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  43994. var BABYLON;
  43995. (function (BABYLON) {
  43996. (function (JoystickAxis) {
  43997. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  43998. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  43999. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44000. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44001. var JoystickAxis = BABYLON.JoystickAxis;
  44002. var VirtualJoystick = (function () {
  44003. function VirtualJoystick(leftJoystick) {
  44004. var _this = this;
  44005. if (leftJoystick) {
  44006. this._leftJoystick = true;
  44007. }
  44008. else {
  44009. this._leftJoystick = false;
  44010. }
  44011. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44012. VirtualJoystick._globalJoystickIndex++;
  44013. // By default left & right arrow keys are moving the X
  44014. // and up & down keys are moving the Y
  44015. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44016. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44017. this.reverseLeftRight = false;
  44018. this.reverseUpDown = false;
  44019. // collections of pointers
  44020. this._touches = new BABYLON.StringDictionary();
  44021. this.deltaPosition = BABYLON.Vector3.Zero();
  44022. this._joystickSensibility = 25;
  44023. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44024. this._rotationSpeed = 25;
  44025. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44026. this._rotateOnAxisRelativeToMesh = false;
  44027. this._onResize = function (evt) {
  44028. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44029. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44030. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44031. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44032. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44033. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44034. };
  44035. // injecting a canvas element on top of the canvas 3D game
  44036. if (!VirtualJoystick.vjCanvas) {
  44037. window.addEventListener("resize", this._onResize, false);
  44038. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44039. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44040. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44041. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44042. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44043. VirtualJoystick.vjCanvas.style.width = "100%";
  44044. VirtualJoystick.vjCanvas.style.height = "100%";
  44045. VirtualJoystick.vjCanvas.style.position = "absolute";
  44046. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44047. VirtualJoystick.vjCanvas.style.top = "0px";
  44048. VirtualJoystick.vjCanvas.style.left = "0px";
  44049. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44050. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44051. // Support for jQuery PEP polyfill
  44052. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44053. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44054. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44055. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44056. document.body.appendChild(VirtualJoystick.vjCanvas);
  44057. }
  44058. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44059. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44060. this.pressed = false;
  44061. // default joystick color
  44062. this._joystickColor = "cyan";
  44063. this._joystickPointerID = -1;
  44064. // current joystick position
  44065. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44066. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44067. // origin joystick position
  44068. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44069. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44070. this._onPointerDownHandlerRef = function (evt) {
  44071. _this._onPointerDown(evt);
  44072. };
  44073. this._onPointerMoveHandlerRef = function (evt) {
  44074. _this._onPointerMove(evt);
  44075. };
  44076. this._onPointerOutHandlerRef = function (evt) {
  44077. _this._onPointerUp(evt);
  44078. };
  44079. this._onPointerUpHandlerRef = function (evt) {
  44080. _this._onPointerUp(evt);
  44081. };
  44082. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44083. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44084. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44085. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44086. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44087. evt.preventDefault(); // Disables system menu
  44088. }, false);
  44089. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44090. }
  44091. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44092. this._joystickSensibility = newJoystickSensibility;
  44093. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44094. };
  44095. VirtualJoystick.prototype._onPointerDown = function (e) {
  44096. var positionOnScreenCondition;
  44097. e.preventDefault();
  44098. if (this._leftJoystick === true) {
  44099. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44100. }
  44101. else {
  44102. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44103. }
  44104. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44105. // First contact will be dedicated to the virtual joystick
  44106. this._joystickPointerID = e.pointerId;
  44107. this._joystickPointerStartPos.x = e.clientX;
  44108. this._joystickPointerStartPos.y = e.clientY;
  44109. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44110. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44111. this._deltaJoystickVector.x = 0;
  44112. this._deltaJoystickVector.y = 0;
  44113. this.pressed = true;
  44114. this._touches.add(e.pointerId.toString(), e);
  44115. }
  44116. else {
  44117. // You can only trigger the action buttons with a joystick declared
  44118. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44119. this._action();
  44120. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44121. }
  44122. }
  44123. };
  44124. VirtualJoystick.prototype._onPointerMove = function (e) {
  44125. // If the current pointer is the one associated to the joystick (first touch contact)
  44126. if (this._joystickPointerID == e.pointerId) {
  44127. this._joystickPointerPos.x = e.clientX;
  44128. this._joystickPointerPos.y = e.clientY;
  44129. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44130. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44131. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44132. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44133. switch (this._axisTargetedByLeftAndRight) {
  44134. case JoystickAxis.X:
  44135. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44136. break;
  44137. case JoystickAxis.Y:
  44138. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44139. break;
  44140. case JoystickAxis.Z:
  44141. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44142. break;
  44143. }
  44144. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44145. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44146. switch (this._axisTargetedByUpAndDown) {
  44147. case JoystickAxis.X:
  44148. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44149. break;
  44150. case JoystickAxis.Y:
  44151. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44152. break;
  44153. case JoystickAxis.Z:
  44154. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44155. break;
  44156. }
  44157. }
  44158. else {
  44159. var data = this._touches.get(e.pointerId.toString());
  44160. if (data) {
  44161. data.x = e.clientX;
  44162. data.y = e.clientY;
  44163. }
  44164. }
  44165. };
  44166. VirtualJoystick.prototype._onPointerUp = function (e) {
  44167. if (this._joystickPointerID == e.pointerId) {
  44168. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  44169. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  44170. this._joystickPointerID = -1;
  44171. this.pressed = false;
  44172. }
  44173. else {
  44174. var touch = this._touches.get(e.pointerId.toString());
  44175. if (touch) {
  44176. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44177. }
  44178. }
  44179. this._deltaJoystickVector.x = 0;
  44180. this._deltaJoystickVector.y = 0;
  44181. this._touches.remove(e.pointerId.toString());
  44182. };
  44183. /**
  44184. * Change the color of the virtual joystick
  44185. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44186. */
  44187. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44188. this._joystickColor = newColor;
  44189. };
  44190. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44191. this._action = action;
  44192. };
  44193. // Define which axis you'd like to control for left & right
  44194. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44195. switch (axis) {
  44196. case JoystickAxis.X:
  44197. case JoystickAxis.Y:
  44198. case JoystickAxis.Z:
  44199. this._axisTargetedByLeftAndRight = axis;
  44200. break;
  44201. default:
  44202. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44203. break;
  44204. }
  44205. };
  44206. // Define which axis you'd like to control for up & down
  44207. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44208. switch (axis) {
  44209. case JoystickAxis.X:
  44210. case JoystickAxis.Y:
  44211. case JoystickAxis.Z:
  44212. this._axisTargetedByUpAndDown = axis;
  44213. break;
  44214. default:
  44215. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44216. break;
  44217. }
  44218. };
  44219. VirtualJoystick.prototype._clearCanvas = function () {
  44220. if (this._leftJoystick) {
  44221. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44222. }
  44223. else {
  44224. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44225. }
  44226. };
  44227. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44228. var _this = this;
  44229. if (this.pressed) {
  44230. this._touches.forEach(function (touch) {
  44231. if (touch.pointerId === _this._joystickPointerID) {
  44232. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44233. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44234. VirtualJoystick.vjCanvasContext.beginPath();
  44235. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44236. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44237. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44238. VirtualJoystick.vjCanvasContext.stroke();
  44239. VirtualJoystick.vjCanvasContext.closePath();
  44240. VirtualJoystick.vjCanvasContext.beginPath();
  44241. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44242. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44243. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44244. VirtualJoystick.vjCanvasContext.stroke();
  44245. VirtualJoystick.vjCanvasContext.closePath();
  44246. VirtualJoystick.vjCanvasContext.beginPath();
  44247. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44248. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44249. VirtualJoystick.vjCanvasContext.stroke();
  44250. VirtualJoystick.vjCanvasContext.closePath();
  44251. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44252. }
  44253. else {
  44254. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44255. VirtualJoystick.vjCanvasContext.beginPath();
  44256. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44257. VirtualJoystick.vjCanvasContext.beginPath();
  44258. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44259. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44260. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44261. VirtualJoystick.vjCanvasContext.stroke();
  44262. VirtualJoystick.vjCanvasContext.closePath();
  44263. touch.prevX = touch.x;
  44264. touch.prevY = touch.y;
  44265. }
  44266. ;
  44267. });
  44268. }
  44269. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44270. };
  44271. VirtualJoystick.prototype.releaseCanvas = function () {
  44272. if (VirtualJoystick.vjCanvas) {
  44273. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44274. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44275. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44276. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44277. window.removeEventListener("resize", this._onResize);
  44278. document.body.removeChild(VirtualJoystick.vjCanvas);
  44279. VirtualJoystick.vjCanvas = null;
  44280. }
  44281. };
  44282. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44283. VirtualJoystick._globalJoystickIndex = 0;
  44284. return VirtualJoystick;
  44285. }());
  44286. BABYLON.VirtualJoystick = VirtualJoystick;
  44287. })(BABYLON || (BABYLON = {}));
  44288. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44289. var BABYLON;
  44290. (function (BABYLON) {
  44291. // We're mainly based on the logic defined into the FreeCamera code
  44292. var VirtualJoysticksCamera = (function (_super) {
  44293. __extends(VirtualJoysticksCamera, _super);
  44294. function VirtualJoysticksCamera(name, position, scene) {
  44295. _super.call(this, name, position, scene);
  44296. this.inputs.addVirtualJoystick();
  44297. }
  44298. VirtualJoysticksCamera.prototype.getClassName = function () {
  44299. return "VirtualJoysticksCamera";
  44300. };
  44301. return VirtualJoysticksCamera;
  44302. }(BABYLON.FreeCamera));
  44303. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44304. })(BABYLON || (BABYLON = {}));
  44305. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44306. var BABYLON;
  44307. (function (BABYLON) {
  44308. var FreeCameraVirtualJoystickInput = (function () {
  44309. function FreeCameraVirtualJoystickInput() {
  44310. }
  44311. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44312. return this._leftjoystick;
  44313. };
  44314. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44315. return this._rightjoystick;
  44316. };
  44317. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44318. if (this._leftjoystick) {
  44319. var camera = this.camera;
  44320. var speed = camera._computeLocalCameraSpeed() * 50;
  44321. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44322. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44323. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44324. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44325. if (!this._leftjoystick.pressed) {
  44326. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44327. }
  44328. if (!this._rightjoystick.pressed) {
  44329. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44330. }
  44331. }
  44332. };
  44333. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44334. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44335. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44336. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44337. this._leftjoystick.setJoystickSensibility(0.15);
  44338. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44339. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44340. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44341. this._rightjoystick.reverseUpDown = true;
  44342. this._rightjoystick.setJoystickSensibility(0.05);
  44343. this._rightjoystick.setJoystickColor("yellow");
  44344. };
  44345. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44346. this._leftjoystick.releaseCanvas();
  44347. this._rightjoystick.releaseCanvas();
  44348. };
  44349. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44350. return "FreeCameraVirtualJoystickInput";
  44351. };
  44352. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44353. return "virtualJoystick";
  44354. };
  44355. return FreeCameraVirtualJoystickInput;
  44356. }());
  44357. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44358. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44359. })(BABYLON || (BABYLON = {}));
  44360. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44361. var BABYLON;
  44362. (function (BABYLON) {
  44363. var AnaglyphPostProcess = (function (_super) {
  44364. __extends(AnaglyphPostProcess, _super);
  44365. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44366. var _this = this;
  44367. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  44368. this._passedProcess = rigCameras[0]._rigPostProcess;
  44369. this.onApplyObservable.add(function (effect) {
  44370. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44371. });
  44372. }
  44373. return AnaglyphPostProcess;
  44374. }(BABYLON.PostProcess));
  44375. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44376. })(BABYLON || (BABYLON = {}));
  44377. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44378. var BABYLON;
  44379. (function (BABYLON) {
  44380. var OutlineRenderer = (function () {
  44381. function OutlineRenderer(scene) {
  44382. this._scene = scene;
  44383. }
  44384. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44385. var _this = this;
  44386. if (useOverlay === void 0) { useOverlay = false; }
  44387. var scene = this._scene;
  44388. var engine = this._scene.getEngine();
  44389. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44390. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  44391. return;
  44392. }
  44393. var mesh = subMesh.getRenderingMesh();
  44394. var material = subMesh.getMaterial();
  44395. engine.enableEffect(this._effect);
  44396. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  44397. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  44398. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44399. // Bones
  44400. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44401. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44402. }
  44403. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44404. // Alpha test
  44405. if (material && material.needAlphaTesting()) {
  44406. var alphaTexture = material.getAlphaTestTexture();
  44407. this._effect.setTexture("diffuseSampler", alphaTexture);
  44408. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44409. }
  44410. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  44411. };
  44412. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  44413. var defines = [];
  44414. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  44415. var mesh = subMesh.getMesh();
  44416. var material = subMesh.getMaterial();
  44417. // Alpha test
  44418. if (material && material.needAlphaTesting()) {
  44419. defines.push("#define ALPHATEST");
  44420. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44421. attribs.push(BABYLON.VertexBuffer.UVKind);
  44422. defines.push("#define UV1");
  44423. }
  44424. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44425. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44426. defines.push("#define UV2");
  44427. }
  44428. }
  44429. // Bones
  44430. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44431. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44432. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44433. if (mesh.numBoneInfluencers > 4) {
  44434. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44435. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44436. }
  44437. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44438. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44439. }
  44440. else {
  44441. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44442. }
  44443. // Instances
  44444. if (useInstances) {
  44445. defines.push("#define INSTANCES");
  44446. attribs.push("world0");
  44447. attribs.push("world1");
  44448. attribs.push("world2");
  44449. attribs.push("world3");
  44450. }
  44451. // Get correct effect
  44452. var join = defines.join("\n");
  44453. if (this._cachedDefines !== join) {
  44454. this._cachedDefines = join;
  44455. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  44456. }
  44457. return this._effect.isReady();
  44458. };
  44459. return OutlineRenderer;
  44460. }());
  44461. BABYLON.OutlineRenderer = OutlineRenderer;
  44462. })(BABYLON || (BABYLON = {}));
  44463. //# sourceMappingURL=babylon.outlineRenderer.js.map
  44464. var BABYLON;
  44465. (function (BABYLON) {
  44466. var MeshAssetTask = (function () {
  44467. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  44468. this.name = name;
  44469. this.meshesNames = meshesNames;
  44470. this.rootUrl = rootUrl;
  44471. this.sceneFilename = sceneFilename;
  44472. this.isCompleted = false;
  44473. }
  44474. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44475. var _this = this;
  44476. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  44477. _this.loadedMeshes = meshes;
  44478. _this.loadedParticleSystems = particleSystems;
  44479. _this.loadedSkeletons = skeletons;
  44480. _this.isCompleted = true;
  44481. if (_this.onSuccess) {
  44482. _this.onSuccess(_this);
  44483. }
  44484. onSuccess();
  44485. }, null, function () {
  44486. if (_this.onError) {
  44487. _this.onError(_this);
  44488. }
  44489. onError();
  44490. });
  44491. };
  44492. return MeshAssetTask;
  44493. }());
  44494. BABYLON.MeshAssetTask = MeshAssetTask;
  44495. var TextFileAssetTask = (function () {
  44496. function TextFileAssetTask(name, url) {
  44497. this.name = name;
  44498. this.url = url;
  44499. this.isCompleted = false;
  44500. }
  44501. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44502. var _this = this;
  44503. BABYLON.Tools.LoadFile(this.url, function (data) {
  44504. _this.text = data;
  44505. _this.isCompleted = true;
  44506. if (_this.onSuccess) {
  44507. _this.onSuccess(_this);
  44508. }
  44509. onSuccess();
  44510. }, null, scene.database, false, function () {
  44511. if (_this.onError) {
  44512. _this.onError(_this);
  44513. }
  44514. onError();
  44515. });
  44516. };
  44517. return TextFileAssetTask;
  44518. }());
  44519. BABYLON.TextFileAssetTask = TextFileAssetTask;
  44520. var BinaryFileAssetTask = (function () {
  44521. function BinaryFileAssetTask(name, url) {
  44522. this.name = name;
  44523. this.url = url;
  44524. this.isCompleted = false;
  44525. }
  44526. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44527. var _this = this;
  44528. BABYLON.Tools.LoadFile(this.url, function (data) {
  44529. _this.data = data;
  44530. _this.isCompleted = true;
  44531. if (_this.onSuccess) {
  44532. _this.onSuccess(_this);
  44533. }
  44534. onSuccess();
  44535. }, null, scene.database, true, function () {
  44536. if (_this.onError) {
  44537. _this.onError(_this);
  44538. }
  44539. onError();
  44540. });
  44541. };
  44542. return BinaryFileAssetTask;
  44543. }());
  44544. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  44545. var ImageAssetTask = (function () {
  44546. function ImageAssetTask(name, url) {
  44547. this.name = name;
  44548. this.url = url;
  44549. this.isCompleted = false;
  44550. }
  44551. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44552. var _this = this;
  44553. var img = new Image();
  44554. BABYLON.Tools.SetCorsBehavior(this.url, img);
  44555. img.onload = function () {
  44556. _this.image = img;
  44557. _this.isCompleted = true;
  44558. if (_this.onSuccess) {
  44559. _this.onSuccess(_this);
  44560. }
  44561. onSuccess();
  44562. };
  44563. img.onerror = function () {
  44564. if (_this.onError) {
  44565. _this.onError(_this);
  44566. }
  44567. onError();
  44568. };
  44569. img.src = this.url;
  44570. };
  44571. return ImageAssetTask;
  44572. }());
  44573. BABYLON.ImageAssetTask = ImageAssetTask;
  44574. var TextureAssetTask = (function () {
  44575. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  44576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44577. this.name = name;
  44578. this.url = url;
  44579. this.noMipmap = noMipmap;
  44580. this.invertY = invertY;
  44581. this.samplingMode = samplingMode;
  44582. this.isCompleted = false;
  44583. }
  44584. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44585. var _this = this;
  44586. var onload = function () {
  44587. _this.isCompleted = true;
  44588. if (_this.onSuccess) {
  44589. _this.onSuccess(_this);
  44590. }
  44591. onSuccess();
  44592. };
  44593. var onerror = function () {
  44594. if (_this.onError) {
  44595. _this.onError(_this);
  44596. }
  44597. onError();
  44598. };
  44599. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  44600. };
  44601. return TextureAssetTask;
  44602. }());
  44603. BABYLON.TextureAssetTask = TextureAssetTask;
  44604. var CubeTextureAssetTask = (function () {
  44605. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  44606. this.name = name;
  44607. this.url = url;
  44608. this.extensions = extensions;
  44609. this.noMipmap = noMipmap;
  44610. this.files = files;
  44611. this.isCompleted = false;
  44612. }
  44613. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44614. var _this = this;
  44615. var onload = function () {
  44616. _this.isCompleted = true;
  44617. if (_this.onSuccess) {
  44618. _this.onSuccess(_this);
  44619. }
  44620. onSuccess();
  44621. };
  44622. var onerror = function () {
  44623. if (_this.onError) {
  44624. _this.onError(_this);
  44625. }
  44626. onError();
  44627. };
  44628. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  44629. };
  44630. return CubeTextureAssetTask;
  44631. }());
  44632. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  44633. var AssetsManager = (function () {
  44634. function AssetsManager(scene) {
  44635. this.tasks = new Array();
  44636. this.waitingTasksCount = 0;
  44637. this.useDefaultLoadingScreen = true;
  44638. this._scene = scene;
  44639. }
  44640. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  44641. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  44642. this.tasks.push(task);
  44643. return task;
  44644. };
  44645. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  44646. var task = new TextFileAssetTask(taskName, url);
  44647. this.tasks.push(task);
  44648. return task;
  44649. };
  44650. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  44651. var task = new BinaryFileAssetTask(taskName, url);
  44652. this.tasks.push(task);
  44653. return task;
  44654. };
  44655. AssetsManager.prototype.addImageTask = function (taskName, url) {
  44656. var task = new ImageAssetTask(taskName, url);
  44657. this.tasks.push(task);
  44658. return task;
  44659. };
  44660. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  44661. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44662. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  44663. this.tasks.push(task);
  44664. return task;
  44665. };
  44666. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  44667. this.waitingTasksCount--;
  44668. if (this.waitingTasksCount === 0) {
  44669. if (this.onFinish) {
  44670. this.onFinish(this.tasks);
  44671. }
  44672. this._scene.getEngine().hideLoadingUI();
  44673. }
  44674. };
  44675. AssetsManager.prototype._runTask = function (task) {
  44676. var _this = this;
  44677. task.run(this._scene, function () {
  44678. if (_this.onTaskSuccess) {
  44679. _this.onTaskSuccess(task);
  44680. }
  44681. _this._decreaseWaitingTasksCount();
  44682. }, function () {
  44683. if (_this.onTaskError) {
  44684. _this.onTaskError(task);
  44685. }
  44686. _this._decreaseWaitingTasksCount();
  44687. });
  44688. };
  44689. AssetsManager.prototype.reset = function () {
  44690. this.tasks = new Array();
  44691. return this;
  44692. };
  44693. AssetsManager.prototype.load = function () {
  44694. this.waitingTasksCount = this.tasks.length;
  44695. if (this.waitingTasksCount === 0) {
  44696. if (this.onFinish) {
  44697. this.onFinish(this.tasks);
  44698. }
  44699. return this;
  44700. }
  44701. if (this.useDefaultLoadingScreen) {
  44702. this._scene.getEngine().displayLoadingUI();
  44703. }
  44704. for (var index = 0; index < this.tasks.length; index++) {
  44705. var task = this.tasks[index];
  44706. this._runTask(task);
  44707. }
  44708. return this;
  44709. };
  44710. return AssetsManager;
  44711. }());
  44712. BABYLON.AssetsManager = AssetsManager;
  44713. })(BABYLON || (BABYLON = {}));
  44714. //# sourceMappingURL=babylon.assetsManager.js.map
  44715. var BABYLON;
  44716. (function (BABYLON) {
  44717. var VRCameraMetrics = (function () {
  44718. function VRCameraMetrics() {
  44719. this.compensateDistortion = true;
  44720. }
  44721. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  44722. get: function () {
  44723. return this.hResolution / (2 * this.vResolution);
  44724. },
  44725. enumerable: true,
  44726. configurable: true
  44727. });
  44728. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  44729. get: function () {
  44730. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  44731. },
  44732. enumerable: true,
  44733. configurable: true
  44734. });
  44735. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  44736. get: function () {
  44737. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44738. var h = (4 * meters) / this.hScreenSize;
  44739. return BABYLON.Matrix.Translation(h, 0, 0);
  44740. },
  44741. enumerable: true,
  44742. configurable: true
  44743. });
  44744. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  44745. get: function () {
  44746. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44747. var h = (4 * meters) / this.hScreenSize;
  44748. return BABYLON.Matrix.Translation(-h, 0, 0);
  44749. },
  44750. enumerable: true,
  44751. configurable: true
  44752. });
  44753. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  44754. get: function () {
  44755. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  44756. },
  44757. enumerable: true,
  44758. configurable: true
  44759. });
  44760. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  44761. get: function () {
  44762. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  44763. },
  44764. enumerable: true,
  44765. configurable: true
  44766. });
  44767. VRCameraMetrics.GetDefault = function () {
  44768. var result = new VRCameraMetrics();
  44769. result.hResolution = 1280;
  44770. result.vResolution = 800;
  44771. result.hScreenSize = 0.149759993;
  44772. result.vScreenSize = 0.0935999975;
  44773. result.vScreenCenter = 0.0467999987,
  44774. result.eyeToScreenDistance = 0.0410000011;
  44775. result.lensSeparationDistance = 0.0635000020;
  44776. result.interpupillaryDistance = 0.0640000030;
  44777. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  44778. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  44779. result.postProcessScaleFactor = 1.714605507808412;
  44780. result.lensCenterOffset = 0.151976421;
  44781. return result;
  44782. };
  44783. return VRCameraMetrics;
  44784. }());
  44785. BABYLON.VRCameraMetrics = VRCameraMetrics;
  44786. })(BABYLON || (BABYLON = {}));
  44787. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  44788. var BABYLON;
  44789. (function (BABYLON) {
  44790. var WebVRFreeCamera = (function (_super) {
  44791. __extends(WebVRFreeCamera, _super);
  44792. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  44793. var _this = this;
  44794. if (compensateDistortion === void 0) { compensateDistortion = false; }
  44795. if (webVROptions === void 0) { webVROptions = {}; }
  44796. _super.call(this, name, position, scene);
  44797. this.webVROptions = webVROptions;
  44798. this._vrDevice = null;
  44799. this._cacheState = null;
  44800. this._vrEnabled = false;
  44801. this._attached = false;
  44802. //using the position provided as the current position offset
  44803. this._positionOffset = position;
  44804. //enable VR
  44805. this.getEngine().initWebVR();
  44806. if (!this.getEngine().vrDisplaysPromise) {
  44807. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  44808. }
  44809. else {
  44810. //TODO get the metrics updated using the device's eye parameters!
  44811. //TODO also check that the device has the right capabilities!
  44812. this._frameData = new VRFrameData();
  44813. this.getEngine().vrDisplaysPromise.then(function (devices) {
  44814. if (devices.length > 0) {
  44815. _this._vrEnabled = true;
  44816. if (_this.webVROptions.displayName) {
  44817. var found = devices.some(function (device) {
  44818. if (device.displayName === _this.webVROptions.displayName) {
  44819. _this._vrDevice = device;
  44820. return true;
  44821. }
  44822. else {
  44823. return false;
  44824. }
  44825. });
  44826. if (!found) {
  44827. _this._vrDevice = devices[0];
  44828. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  44829. }
  44830. }
  44831. else {
  44832. //choose the first one
  44833. _this._vrDevice = devices[0];
  44834. }
  44835. //reset the rig parameters.
  44836. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  44837. if (_this._attached) {
  44838. _this.getEngine().enableVR(_this._vrDevice);
  44839. }
  44840. }
  44841. else {
  44842. BABYLON.Tools.Error("No WebVR devices found!");
  44843. }
  44844. });
  44845. }
  44846. this.rotationQuaternion = new BABYLON.Quaternion();
  44847. this._quaternionCache = new BABYLON.Quaternion();
  44848. }
  44849. WebVRFreeCamera.prototype._checkInputs = function () {
  44850. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  44851. var currentPost = this._frameData.pose;
  44852. //make sure we have data
  44853. if (currentPost && currentPost.orientation) {
  44854. this._cacheState = currentPost;
  44855. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  44856. if (this.webVROptions.trackPosition && this._cacheState.position) {
  44857. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  44858. //scale the position accordingly
  44859. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  44860. //add the position offset
  44861. this.position.addInPlace(this._positionOffset);
  44862. }
  44863. }
  44864. }
  44865. _super.prototype._checkInputs.call(this);
  44866. };
  44867. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44868. _super.prototype.attachControl.call(this, element, noPreventDefault);
  44869. this._attached = true;
  44870. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  44871. if (this._vrEnabled) {
  44872. this.getEngine().enableVR(this._vrDevice);
  44873. }
  44874. };
  44875. WebVRFreeCamera.prototype.detachControl = function (element) {
  44876. _super.prototype.detachControl.call(this, element);
  44877. this._vrEnabled = false;
  44878. this._attached = false;
  44879. this.getEngine().disableVR();
  44880. };
  44881. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  44882. //Backwards comp.
  44883. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  44884. //this.getEngine().switchFullscreen(requestPointerlock);
  44885. };
  44886. WebVRFreeCamera.prototype.getClassName = function () {
  44887. return "WebVRFreeCamera";
  44888. };
  44889. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  44890. //uses the vrDisplay's "resetPose()".
  44891. //pitch and roll won't be affected.
  44892. this._vrDevice.resetPose();
  44893. };
  44894. /**
  44895. *
  44896. * Set the position offset of the VR camera
  44897. * The offset will be added to the WebVR pose, after scaling it (if set).
  44898. *
  44899. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  44900. *
  44901. * @memberOf WebVRFreeCamera
  44902. */
  44903. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  44904. if (newPosition) {
  44905. this._positionOffset = newPosition;
  44906. }
  44907. else {
  44908. this._positionOffset.copyFrom(this.position);
  44909. }
  44910. };
  44911. return WebVRFreeCamera;
  44912. }(BABYLON.FreeCamera));
  44913. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  44914. })(BABYLON || (BABYLON = {}));
  44915. //# sourceMappingURL=babylon.webVRCamera.js.map
  44916. var BABYLON;
  44917. (function (BABYLON) {
  44918. // Standard optimizations
  44919. var SceneOptimization = (function () {
  44920. function SceneOptimization(priority) {
  44921. if (priority === void 0) { priority = 0; }
  44922. this.priority = priority;
  44923. this.apply = function (scene) {
  44924. return true; // Return true if everything that can be done was applied
  44925. };
  44926. }
  44927. return SceneOptimization;
  44928. }());
  44929. BABYLON.SceneOptimization = SceneOptimization;
  44930. var TextureOptimization = (function (_super) {
  44931. __extends(TextureOptimization, _super);
  44932. function TextureOptimization(priority, maximumSize) {
  44933. var _this = this;
  44934. if (priority === void 0) { priority = 0; }
  44935. if (maximumSize === void 0) { maximumSize = 1024; }
  44936. _super.call(this, priority);
  44937. this.priority = priority;
  44938. this.maximumSize = maximumSize;
  44939. this.apply = function (scene) {
  44940. var allDone = true;
  44941. for (var index = 0; index < scene.textures.length; index++) {
  44942. var texture = scene.textures[index];
  44943. if (!texture.canRescale) {
  44944. continue;
  44945. }
  44946. var currentSize = texture.getSize();
  44947. var maxDimension = Math.max(currentSize.width, currentSize.height);
  44948. if (maxDimension > _this.maximumSize) {
  44949. texture.scale(0.5);
  44950. allDone = false;
  44951. }
  44952. }
  44953. return allDone;
  44954. };
  44955. }
  44956. return TextureOptimization;
  44957. }(SceneOptimization));
  44958. BABYLON.TextureOptimization = TextureOptimization;
  44959. var HardwareScalingOptimization = (function (_super) {
  44960. __extends(HardwareScalingOptimization, _super);
  44961. function HardwareScalingOptimization(priority, maximumScale) {
  44962. var _this = this;
  44963. if (priority === void 0) { priority = 0; }
  44964. if (maximumScale === void 0) { maximumScale = 2; }
  44965. _super.call(this, priority);
  44966. this.priority = priority;
  44967. this.maximumScale = maximumScale;
  44968. this._currentScale = 1;
  44969. this.apply = function (scene) {
  44970. _this._currentScale++;
  44971. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  44972. return _this._currentScale >= _this.maximumScale;
  44973. };
  44974. }
  44975. return HardwareScalingOptimization;
  44976. }(SceneOptimization));
  44977. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  44978. var ShadowsOptimization = (function (_super) {
  44979. __extends(ShadowsOptimization, _super);
  44980. function ShadowsOptimization() {
  44981. _super.apply(this, arguments);
  44982. this.apply = function (scene) {
  44983. scene.shadowsEnabled = false;
  44984. return true;
  44985. };
  44986. }
  44987. return ShadowsOptimization;
  44988. }(SceneOptimization));
  44989. BABYLON.ShadowsOptimization = ShadowsOptimization;
  44990. var PostProcessesOptimization = (function (_super) {
  44991. __extends(PostProcessesOptimization, _super);
  44992. function PostProcessesOptimization() {
  44993. _super.apply(this, arguments);
  44994. this.apply = function (scene) {
  44995. scene.postProcessesEnabled = false;
  44996. return true;
  44997. };
  44998. }
  44999. return PostProcessesOptimization;
  45000. }(SceneOptimization));
  45001. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45002. var LensFlaresOptimization = (function (_super) {
  45003. __extends(LensFlaresOptimization, _super);
  45004. function LensFlaresOptimization() {
  45005. _super.apply(this, arguments);
  45006. this.apply = function (scene) {
  45007. scene.lensFlaresEnabled = false;
  45008. return true;
  45009. };
  45010. }
  45011. return LensFlaresOptimization;
  45012. }(SceneOptimization));
  45013. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45014. var ParticlesOptimization = (function (_super) {
  45015. __extends(ParticlesOptimization, _super);
  45016. function ParticlesOptimization() {
  45017. _super.apply(this, arguments);
  45018. this.apply = function (scene) {
  45019. scene.particlesEnabled = false;
  45020. return true;
  45021. };
  45022. }
  45023. return ParticlesOptimization;
  45024. }(SceneOptimization));
  45025. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45026. var RenderTargetsOptimization = (function (_super) {
  45027. __extends(RenderTargetsOptimization, _super);
  45028. function RenderTargetsOptimization() {
  45029. _super.apply(this, arguments);
  45030. this.apply = function (scene) {
  45031. scene.renderTargetsEnabled = false;
  45032. return true;
  45033. };
  45034. }
  45035. return RenderTargetsOptimization;
  45036. }(SceneOptimization));
  45037. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45038. var MergeMeshesOptimization = (function (_super) {
  45039. __extends(MergeMeshesOptimization, _super);
  45040. function MergeMeshesOptimization() {
  45041. var _this = this;
  45042. _super.apply(this, arguments);
  45043. this._canBeMerged = function (abstractMesh) {
  45044. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45045. return false;
  45046. }
  45047. var mesh = abstractMesh;
  45048. if (!mesh.isVisible || !mesh.isEnabled()) {
  45049. return false;
  45050. }
  45051. if (mesh.instances.length > 0) {
  45052. return false;
  45053. }
  45054. if (mesh.skeleton || mesh.hasLODLevels) {
  45055. return false;
  45056. }
  45057. if (mesh.parent) {
  45058. return false;
  45059. }
  45060. return true;
  45061. };
  45062. this.apply = function (scene, updateSelectionTree) {
  45063. var globalPool = scene.meshes.slice(0);
  45064. var globalLength = globalPool.length;
  45065. for (var index = 0; index < globalLength; index++) {
  45066. var currentPool = new Array();
  45067. var current = globalPool[index];
  45068. // Checks
  45069. if (!_this._canBeMerged(current)) {
  45070. continue;
  45071. }
  45072. currentPool.push(current);
  45073. // Find compatible meshes
  45074. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45075. var otherMesh = globalPool[subIndex];
  45076. if (!_this._canBeMerged(otherMesh)) {
  45077. continue;
  45078. }
  45079. if (otherMesh.material !== current.material) {
  45080. continue;
  45081. }
  45082. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45083. continue;
  45084. }
  45085. currentPool.push(otherMesh);
  45086. globalLength--;
  45087. globalPool.splice(subIndex, 1);
  45088. subIndex--;
  45089. }
  45090. if (currentPool.length < 2) {
  45091. continue;
  45092. }
  45093. // Merge meshes
  45094. BABYLON.Mesh.MergeMeshes(currentPool);
  45095. }
  45096. if (updateSelectionTree != undefined) {
  45097. if (updateSelectionTree) {
  45098. scene.createOrUpdateSelectionOctree();
  45099. }
  45100. }
  45101. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45102. scene.createOrUpdateSelectionOctree();
  45103. }
  45104. return true;
  45105. };
  45106. }
  45107. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45108. get: function () {
  45109. return MergeMeshesOptimization._UpdateSelectionTree;
  45110. },
  45111. set: function (value) {
  45112. MergeMeshesOptimization._UpdateSelectionTree = value;
  45113. },
  45114. enumerable: true,
  45115. configurable: true
  45116. });
  45117. MergeMeshesOptimization._UpdateSelectionTree = false;
  45118. return MergeMeshesOptimization;
  45119. }(SceneOptimization));
  45120. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45121. // Options
  45122. var SceneOptimizerOptions = (function () {
  45123. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45124. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45125. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45126. this.targetFrameRate = targetFrameRate;
  45127. this.trackerDuration = trackerDuration;
  45128. this.optimizations = new Array();
  45129. }
  45130. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45131. var result = new SceneOptimizerOptions(targetFrameRate);
  45132. var priority = 0;
  45133. result.optimizations.push(new MergeMeshesOptimization(priority));
  45134. result.optimizations.push(new ShadowsOptimization(priority));
  45135. result.optimizations.push(new LensFlaresOptimization(priority));
  45136. // Next priority
  45137. priority++;
  45138. result.optimizations.push(new PostProcessesOptimization(priority));
  45139. result.optimizations.push(new ParticlesOptimization(priority));
  45140. // Next priority
  45141. priority++;
  45142. result.optimizations.push(new TextureOptimization(priority, 1024));
  45143. return result;
  45144. };
  45145. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45146. var result = new SceneOptimizerOptions(targetFrameRate);
  45147. var priority = 0;
  45148. result.optimizations.push(new MergeMeshesOptimization(priority));
  45149. result.optimizations.push(new ShadowsOptimization(priority));
  45150. result.optimizations.push(new LensFlaresOptimization(priority));
  45151. // Next priority
  45152. priority++;
  45153. result.optimizations.push(new PostProcessesOptimization(priority));
  45154. result.optimizations.push(new ParticlesOptimization(priority));
  45155. // Next priority
  45156. priority++;
  45157. result.optimizations.push(new TextureOptimization(priority, 512));
  45158. // Next priority
  45159. priority++;
  45160. result.optimizations.push(new RenderTargetsOptimization(priority));
  45161. // Next priority
  45162. priority++;
  45163. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45164. return result;
  45165. };
  45166. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45167. var result = new SceneOptimizerOptions(targetFrameRate);
  45168. var priority = 0;
  45169. result.optimizations.push(new MergeMeshesOptimization(priority));
  45170. result.optimizations.push(new ShadowsOptimization(priority));
  45171. result.optimizations.push(new LensFlaresOptimization(priority));
  45172. // Next priority
  45173. priority++;
  45174. result.optimizations.push(new PostProcessesOptimization(priority));
  45175. result.optimizations.push(new ParticlesOptimization(priority));
  45176. // Next priority
  45177. priority++;
  45178. result.optimizations.push(new TextureOptimization(priority, 256));
  45179. // Next priority
  45180. priority++;
  45181. result.optimizations.push(new RenderTargetsOptimization(priority));
  45182. // Next priority
  45183. priority++;
  45184. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45185. return result;
  45186. };
  45187. return SceneOptimizerOptions;
  45188. }());
  45189. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45190. // Scene optimizer tool
  45191. var SceneOptimizer = (function () {
  45192. function SceneOptimizer() {
  45193. }
  45194. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45195. // TODO: add an epsilon
  45196. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45197. if (onSuccess) {
  45198. onSuccess();
  45199. }
  45200. return;
  45201. }
  45202. // Apply current level of optimizations
  45203. var allDone = true;
  45204. var noOptimizationApplied = true;
  45205. for (var index = 0; index < options.optimizations.length; index++) {
  45206. var optimization = options.optimizations[index];
  45207. if (optimization.priority === currentPriorityLevel) {
  45208. noOptimizationApplied = false;
  45209. allDone = allDone && optimization.apply(scene);
  45210. }
  45211. }
  45212. // If no optimization was applied, this is a failure :(
  45213. if (noOptimizationApplied) {
  45214. if (onFailure) {
  45215. onFailure();
  45216. }
  45217. return;
  45218. }
  45219. // If all optimizations were done, move to next level
  45220. if (allDone) {
  45221. currentPriorityLevel++;
  45222. }
  45223. // Let's the system running for a specific amount of time before checking FPS
  45224. scene.executeWhenReady(function () {
  45225. setTimeout(function () {
  45226. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45227. }, options.trackerDuration);
  45228. });
  45229. };
  45230. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45231. if (!options) {
  45232. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45233. }
  45234. // Let's the system running for a specific amount of time before checking FPS
  45235. scene.executeWhenReady(function () {
  45236. setTimeout(function () {
  45237. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45238. }, options.trackerDuration);
  45239. });
  45240. };
  45241. return SceneOptimizer;
  45242. }());
  45243. BABYLON.SceneOptimizer = SceneOptimizer;
  45244. })(BABYLON || (BABYLON = {}));
  45245. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45246. var BABYLON;
  45247. (function (BABYLON) {
  45248. var Internals;
  45249. (function (Internals) {
  45250. var MeshLODLevel = (function () {
  45251. function MeshLODLevel(distance, mesh) {
  45252. this.distance = distance;
  45253. this.mesh = mesh;
  45254. }
  45255. return MeshLODLevel;
  45256. }());
  45257. Internals.MeshLODLevel = MeshLODLevel;
  45258. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45259. })(BABYLON || (BABYLON = {}));
  45260. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45261. var BABYLON;
  45262. (function (BABYLON) {
  45263. var RawTexture = (function (_super) {
  45264. __extends(RawTexture, _super);
  45265. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45266. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45267. if (invertY === void 0) { invertY = false; }
  45268. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45269. _super.call(this, null, scene, !generateMipMaps, invertY);
  45270. this.format = format;
  45271. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45272. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45273. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45274. }
  45275. RawTexture.prototype.update = function (data) {
  45276. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45277. };
  45278. // Statics
  45279. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45280. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45281. if (invertY === void 0) { invertY = false; }
  45282. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45283. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45284. };
  45285. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45286. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45287. if (invertY === void 0) { invertY = false; }
  45288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45289. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45290. };
  45291. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45292. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45293. if (invertY === void 0) { invertY = false; }
  45294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45295. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45296. };
  45297. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45298. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45299. if (invertY === void 0) { invertY = false; }
  45300. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45301. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45302. };
  45303. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45304. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45305. if (invertY === void 0) { invertY = false; }
  45306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45307. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45308. };
  45309. return RawTexture;
  45310. }(BABYLON.Texture));
  45311. BABYLON.RawTexture = RawTexture;
  45312. })(BABYLON || (BABYLON = {}));
  45313. //# sourceMappingURL=babylon.rawTexture.js.map
  45314. var BABYLON;
  45315. (function (BABYLON) {
  45316. var IndexedVector2 = (function (_super) {
  45317. __extends(IndexedVector2, _super);
  45318. function IndexedVector2(original, index) {
  45319. _super.call(this, original.x, original.y);
  45320. this.index = index;
  45321. }
  45322. return IndexedVector2;
  45323. }(BABYLON.Vector2));
  45324. var PolygonPoints = (function () {
  45325. function PolygonPoints() {
  45326. this.elements = new Array();
  45327. }
  45328. PolygonPoints.prototype.add = function (originalPoints) {
  45329. var _this = this;
  45330. var result = new Array();
  45331. originalPoints.forEach(function (point) {
  45332. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45333. var newPoint = new IndexedVector2(point, _this.elements.length);
  45334. result.push(newPoint);
  45335. _this.elements.push(newPoint);
  45336. }
  45337. });
  45338. return result;
  45339. };
  45340. PolygonPoints.prototype.computeBounds = function () {
  45341. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45342. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45343. this.elements.forEach(function (point) {
  45344. // x
  45345. if (point.x < lmin.x) {
  45346. lmin.x = point.x;
  45347. }
  45348. else if (point.x > lmax.x) {
  45349. lmax.x = point.x;
  45350. }
  45351. // y
  45352. if (point.y < lmin.y) {
  45353. lmin.y = point.y;
  45354. }
  45355. else if (point.y > lmax.y) {
  45356. lmax.y = point.y;
  45357. }
  45358. });
  45359. return {
  45360. min: lmin,
  45361. max: lmax,
  45362. width: lmax.x - lmin.x,
  45363. height: lmax.y - lmin.y
  45364. };
  45365. };
  45366. return PolygonPoints;
  45367. }());
  45368. var Polygon = (function () {
  45369. function Polygon() {
  45370. }
  45371. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45372. return [
  45373. new BABYLON.Vector2(xmin, ymin),
  45374. new BABYLON.Vector2(xmax, ymin),
  45375. new BABYLON.Vector2(xmax, ymax),
  45376. new BABYLON.Vector2(xmin, ymax)
  45377. ];
  45378. };
  45379. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45380. if (cx === void 0) { cx = 0; }
  45381. if (cy === void 0) { cy = 0; }
  45382. if (numberOfSides === void 0) { numberOfSides = 32; }
  45383. var result = new Array();
  45384. var angle = 0;
  45385. var increment = (Math.PI * 2) / numberOfSides;
  45386. for (var i = 0; i < numberOfSides; i++) {
  45387. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  45388. angle -= increment;
  45389. }
  45390. return result;
  45391. };
  45392. Polygon.Parse = function (input) {
  45393. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  45394. var i, result = [];
  45395. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  45396. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  45397. }
  45398. return result;
  45399. };
  45400. Polygon.StartingAt = function (x, y) {
  45401. return BABYLON.Path2.StartingAt(x, y);
  45402. };
  45403. return Polygon;
  45404. }());
  45405. BABYLON.Polygon = Polygon;
  45406. var PolygonMeshBuilder = (function () {
  45407. function PolygonMeshBuilder(name, contours, scene) {
  45408. this._points = new PolygonPoints();
  45409. this._outlinepoints = new PolygonPoints();
  45410. this._holes = [];
  45411. this._epoints = new Array();
  45412. this._eholes = new Array();
  45413. this._name = name;
  45414. this._scene = scene;
  45415. var points;
  45416. if (contours instanceof BABYLON.Path2) {
  45417. points = contours.getPoints();
  45418. }
  45419. else {
  45420. points = contours;
  45421. }
  45422. this._addToepoint(points);
  45423. this._points.add(points);
  45424. this._outlinepoints.add(points);
  45425. }
  45426. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  45427. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  45428. var p = points_1[_i];
  45429. this._epoints.push(p.x, p.y);
  45430. }
  45431. };
  45432. PolygonMeshBuilder.prototype.addHole = function (hole) {
  45433. this._points.add(hole);
  45434. var holepoints = new PolygonPoints();
  45435. holepoints.add(hole);
  45436. this._holes.push(holepoints);
  45437. this._eholes.push(this._epoints.length / 2);
  45438. this._addToepoint(hole);
  45439. return this;
  45440. };
  45441. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  45442. var _this = this;
  45443. if (updatable === void 0) { updatable = false; }
  45444. var result = new BABYLON.Mesh(this._name, this._scene);
  45445. var normals = [];
  45446. var positions = [];
  45447. var uvs = [];
  45448. var bounds = this._points.computeBounds();
  45449. this._points.elements.forEach(function (p) {
  45450. normals.push(0, 1.0, 0);
  45451. positions.push(p.x, 0, p.y);
  45452. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  45453. });
  45454. var indices = [];
  45455. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  45456. for (var i = 0; i < res.length; i++) {
  45457. indices.push(res[i]);
  45458. }
  45459. if (depth > 0) {
  45460. var positionscount = (positions.length / 3); //get the current pointcount
  45461. this._points.elements.forEach(function (p) {
  45462. normals.push(0, -1.0, 0);
  45463. positions.push(p.x, -depth, p.y);
  45464. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  45465. });
  45466. var totalCount = indices.length;
  45467. for (var i = 0; i < totalCount; i += 3) {
  45468. var i0 = indices[i + 0];
  45469. var i1 = indices[i + 1];
  45470. var i2 = indices[i + 2];
  45471. indices.push(i2 + positionscount);
  45472. indices.push(i1 + positionscount);
  45473. indices.push(i0 + positionscount);
  45474. }
  45475. //Add the sides
  45476. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  45477. this._holes.forEach(function (hole) {
  45478. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  45479. });
  45480. }
  45481. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  45482. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  45483. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  45484. result.setIndices(indices);
  45485. return result;
  45486. };
  45487. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  45488. var StartIndex = positions.length / 3;
  45489. var ulength = 0;
  45490. for (var i = 0; i < points.elements.length; i++) {
  45491. var p = points.elements[i];
  45492. var p1;
  45493. if ((i + 1) > points.elements.length - 1) {
  45494. p1 = points.elements[0];
  45495. }
  45496. else {
  45497. p1 = points.elements[i + 1];
  45498. }
  45499. positions.push(p.x, 0, p.y);
  45500. positions.push(p.x, -depth, p.y);
  45501. positions.push(p1.x, 0, p1.y);
  45502. positions.push(p1.x, -depth, p1.y);
  45503. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  45504. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  45505. var v3 = v2.subtract(v1);
  45506. var v4 = new BABYLON.Vector3(0, 1, 0);
  45507. var vn = BABYLON.Vector3.Cross(v3, v4);
  45508. vn = vn.normalize();
  45509. uvs.push(ulength / bounds.width, 0);
  45510. uvs.push(ulength / bounds.width, 1);
  45511. ulength += v3.length();
  45512. uvs.push((ulength / bounds.width), 0);
  45513. uvs.push((ulength / bounds.width), 1);
  45514. if (!flip) {
  45515. normals.push(-vn.x, -vn.y, -vn.z);
  45516. normals.push(-vn.x, -vn.y, -vn.z);
  45517. normals.push(-vn.x, -vn.y, -vn.z);
  45518. normals.push(-vn.x, -vn.y, -vn.z);
  45519. indices.push(StartIndex);
  45520. indices.push(StartIndex + 1);
  45521. indices.push(StartIndex + 2);
  45522. indices.push(StartIndex + 1);
  45523. indices.push(StartIndex + 3);
  45524. indices.push(StartIndex + 2);
  45525. }
  45526. else {
  45527. normals.push(vn.x, vn.y, vn.z);
  45528. normals.push(vn.x, vn.y, vn.z);
  45529. normals.push(vn.x, vn.y, vn.z);
  45530. normals.push(vn.x, vn.y, vn.z);
  45531. indices.push(StartIndex);
  45532. indices.push(StartIndex + 2);
  45533. indices.push(StartIndex + 1);
  45534. indices.push(StartIndex + 1);
  45535. indices.push(StartIndex + 2);
  45536. indices.push(StartIndex + 3);
  45537. }
  45538. StartIndex += 4;
  45539. }
  45540. ;
  45541. };
  45542. return PolygonMeshBuilder;
  45543. }());
  45544. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  45545. })(BABYLON || (BABYLON = {}));
  45546. //# sourceMappingURL=babylon.polygonMesh.js.map
  45547. var BABYLON;
  45548. (function (BABYLON) {
  45549. var Octree = (function () {
  45550. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  45551. if (maxDepth === void 0) { maxDepth = 2; }
  45552. this.maxDepth = maxDepth;
  45553. this.dynamicContent = new Array();
  45554. this._maxBlockCapacity = maxBlockCapacity || 64;
  45555. this._selectionContent = new BABYLON.SmartArray(1024);
  45556. this._creationFunc = creationFunc;
  45557. }
  45558. // Methods
  45559. Octree.prototype.update = function (worldMin, worldMax, entries) {
  45560. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  45561. };
  45562. Octree.prototype.addMesh = function (entry) {
  45563. for (var index = 0; index < this.blocks.length; index++) {
  45564. var block = this.blocks[index];
  45565. block.addEntry(entry);
  45566. }
  45567. };
  45568. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  45569. this._selectionContent.reset();
  45570. for (var index = 0; index < this.blocks.length; index++) {
  45571. var block = this.blocks[index];
  45572. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  45573. }
  45574. if (allowDuplicate) {
  45575. this._selectionContent.concat(this.dynamicContent);
  45576. }
  45577. else {
  45578. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45579. }
  45580. return this._selectionContent;
  45581. };
  45582. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  45583. this._selectionContent.reset();
  45584. for (var index = 0; index < this.blocks.length; index++) {
  45585. var block = this.blocks[index];
  45586. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  45587. }
  45588. if (allowDuplicate) {
  45589. this._selectionContent.concat(this.dynamicContent);
  45590. }
  45591. else {
  45592. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45593. }
  45594. return this._selectionContent;
  45595. };
  45596. Octree.prototype.intersectsRay = function (ray) {
  45597. this._selectionContent.reset();
  45598. for (var index = 0; index < this.blocks.length; index++) {
  45599. var block = this.blocks[index];
  45600. block.intersectsRay(ray, this._selectionContent);
  45601. }
  45602. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45603. return this._selectionContent;
  45604. };
  45605. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  45606. target.blocks = new Array();
  45607. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  45608. // Segmenting space
  45609. for (var x = 0; x < 2; x++) {
  45610. for (var y = 0; y < 2; y++) {
  45611. for (var z = 0; z < 2; z++) {
  45612. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  45613. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  45614. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  45615. block.addEntries(entries);
  45616. target.blocks.push(block);
  45617. }
  45618. }
  45619. }
  45620. };
  45621. Octree.CreationFuncForMeshes = function (entry, block) {
  45622. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45623. block.entries.push(entry);
  45624. }
  45625. };
  45626. Octree.CreationFuncForSubMeshes = function (entry, block) {
  45627. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45628. block.entries.push(entry);
  45629. }
  45630. };
  45631. return Octree;
  45632. }());
  45633. BABYLON.Octree = Octree;
  45634. })(BABYLON || (BABYLON = {}));
  45635. //# sourceMappingURL=babylon.octree.js.map
  45636. var BABYLON;
  45637. (function (BABYLON) {
  45638. var OctreeBlock = (function () {
  45639. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  45640. this.entries = new Array();
  45641. this._boundingVectors = new Array();
  45642. this._capacity = capacity;
  45643. this._depth = depth;
  45644. this._maxDepth = maxDepth;
  45645. this._creationFunc = creationFunc;
  45646. this._minPoint = minPoint;
  45647. this._maxPoint = maxPoint;
  45648. this._boundingVectors.push(minPoint.clone());
  45649. this._boundingVectors.push(maxPoint.clone());
  45650. this._boundingVectors.push(minPoint.clone());
  45651. this._boundingVectors[2].x = maxPoint.x;
  45652. this._boundingVectors.push(minPoint.clone());
  45653. this._boundingVectors[3].y = maxPoint.y;
  45654. this._boundingVectors.push(minPoint.clone());
  45655. this._boundingVectors[4].z = maxPoint.z;
  45656. this._boundingVectors.push(maxPoint.clone());
  45657. this._boundingVectors[5].z = minPoint.z;
  45658. this._boundingVectors.push(maxPoint.clone());
  45659. this._boundingVectors[6].x = minPoint.x;
  45660. this._boundingVectors.push(maxPoint.clone());
  45661. this._boundingVectors[7].y = minPoint.y;
  45662. }
  45663. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  45664. // Property
  45665. get: function () {
  45666. return this._capacity;
  45667. },
  45668. enumerable: true,
  45669. configurable: true
  45670. });
  45671. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  45672. get: function () {
  45673. return this._minPoint;
  45674. },
  45675. enumerable: true,
  45676. configurable: true
  45677. });
  45678. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  45679. get: function () {
  45680. return this._maxPoint;
  45681. },
  45682. enumerable: true,
  45683. configurable: true
  45684. });
  45685. // Methods
  45686. OctreeBlock.prototype.addEntry = function (entry) {
  45687. if (this.blocks) {
  45688. for (var index = 0; index < this.blocks.length; index++) {
  45689. var block = this.blocks[index];
  45690. block.addEntry(entry);
  45691. }
  45692. return;
  45693. }
  45694. this._creationFunc(entry, this);
  45695. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  45696. this.createInnerBlocks();
  45697. }
  45698. };
  45699. OctreeBlock.prototype.addEntries = function (entries) {
  45700. for (var index = 0; index < entries.length; index++) {
  45701. var mesh = entries[index];
  45702. this.addEntry(mesh);
  45703. }
  45704. };
  45705. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  45706. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  45707. if (this.blocks) {
  45708. for (var index = 0; index < this.blocks.length; index++) {
  45709. var block = this.blocks[index];
  45710. block.select(frustumPlanes, selection, allowDuplicate);
  45711. }
  45712. return;
  45713. }
  45714. if (allowDuplicate) {
  45715. selection.concat(this.entries);
  45716. }
  45717. else {
  45718. selection.concatWithNoDuplicate(this.entries);
  45719. }
  45720. }
  45721. };
  45722. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  45723. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  45724. if (this.blocks) {
  45725. for (var index = 0; index < this.blocks.length; index++) {
  45726. var block = this.blocks[index];
  45727. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  45728. }
  45729. return;
  45730. }
  45731. if (allowDuplicate) {
  45732. selection.concat(this.entries);
  45733. }
  45734. else {
  45735. selection.concatWithNoDuplicate(this.entries);
  45736. }
  45737. }
  45738. };
  45739. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  45740. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  45741. if (this.blocks) {
  45742. for (var index = 0; index < this.blocks.length; index++) {
  45743. var block = this.blocks[index];
  45744. block.intersectsRay(ray, selection);
  45745. }
  45746. return;
  45747. }
  45748. selection.concatWithNoDuplicate(this.entries);
  45749. }
  45750. };
  45751. OctreeBlock.prototype.createInnerBlocks = function () {
  45752. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  45753. };
  45754. return OctreeBlock;
  45755. }());
  45756. BABYLON.OctreeBlock = OctreeBlock;
  45757. })(BABYLON || (BABYLON = {}));
  45758. //# sourceMappingURL=babylon.octreeBlock.js.map
  45759. var BABYLON;
  45760. (function (BABYLON) {
  45761. var BlurPostProcess = (function (_super) {
  45762. __extends(BlurPostProcess, _super);
  45763. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  45764. var _this = this;
  45765. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45766. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  45767. this.direction = direction;
  45768. this.blurWidth = blurWidth;
  45769. this.onApplyObservable.add(function (effect) {
  45770. effect.setFloat2("screenSize", _this.width, _this.height);
  45771. effect.setVector2("direction", _this.direction);
  45772. effect.setFloat("blurWidth", _this.blurWidth);
  45773. });
  45774. }
  45775. return BlurPostProcess;
  45776. }(BABYLON.PostProcess));
  45777. BABYLON.BlurPostProcess = BlurPostProcess;
  45778. })(BABYLON || (BABYLON = {}));
  45779. //# sourceMappingURL=babylon.blurPostProcess.js.map
  45780. var BABYLON;
  45781. (function (BABYLON) {
  45782. var RefractionPostProcess = (function (_super) {
  45783. __extends(RefractionPostProcess, _super);
  45784. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  45785. var _this = this;
  45786. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  45787. this.color = color;
  45788. this.depth = depth;
  45789. this.colorLevel = colorLevel;
  45790. this.onActivateObservable.add(function (cam) {
  45791. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  45792. });
  45793. this.onApplyObservable.add(function (effect) {
  45794. effect.setColor3("baseColor", _this.color);
  45795. effect.setFloat("depth", _this.depth);
  45796. effect.setFloat("colorLevel", _this.colorLevel);
  45797. effect.setTexture("refractionSampler", _this._refRexture);
  45798. });
  45799. }
  45800. // Methods
  45801. RefractionPostProcess.prototype.dispose = function (camera) {
  45802. if (this._refRexture) {
  45803. this._refRexture.dispose();
  45804. }
  45805. _super.prototype.dispose.call(this, camera);
  45806. };
  45807. return RefractionPostProcess;
  45808. }(BABYLON.PostProcess));
  45809. BABYLON.RefractionPostProcess = RefractionPostProcess;
  45810. })(BABYLON || (BABYLON = {}));
  45811. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  45812. var BABYLON;
  45813. (function (BABYLON) {
  45814. var BlackAndWhitePostProcess = (function (_super) {
  45815. __extends(BlackAndWhitePostProcess, _super);
  45816. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  45817. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  45818. }
  45819. return BlackAndWhitePostProcess;
  45820. }(BABYLON.PostProcess));
  45821. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  45822. })(BABYLON || (BABYLON = {}));
  45823. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  45824. var BABYLON;
  45825. (function (BABYLON) {
  45826. var ConvolutionPostProcess = (function (_super) {
  45827. __extends(ConvolutionPostProcess, _super);
  45828. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  45829. var _this = this;
  45830. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  45831. this.kernel = kernel;
  45832. this.onApply = function (effect) {
  45833. effect.setFloat2("screenSize", _this.width, _this.height);
  45834. effect.setArray("kernel", _this.kernel);
  45835. };
  45836. }
  45837. // Statics
  45838. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  45839. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  45840. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  45841. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  45842. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  45843. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  45844. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  45845. return ConvolutionPostProcess;
  45846. }(BABYLON.PostProcess));
  45847. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  45848. })(BABYLON || (BABYLON = {}));
  45849. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  45850. var BABYLON;
  45851. (function (BABYLON) {
  45852. var FilterPostProcess = (function (_super) {
  45853. __extends(FilterPostProcess, _super);
  45854. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  45855. var _this = this;
  45856. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  45857. this.kernelMatrix = kernelMatrix;
  45858. this.onApply = function (effect) {
  45859. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  45860. };
  45861. }
  45862. return FilterPostProcess;
  45863. }(BABYLON.PostProcess));
  45864. BABYLON.FilterPostProcess = FilterPostProcess;
  45865. })(BABYLON || (BABYLON = {}));
  45866. //# sourceMappingURL=babylon.filterPostProcess.js.map
  45867. var BABYLON;
  45868. (function (BABYLON) {
  45869. var FxaaPostProcess = (function (_super) {
  45870. __extends(FxaaPostProcess, _super);
  45871. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  45872. var _this = this;
  45873. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  45874. this.onSizeChangedObservable.add(function () {
  45875. _this.texelWidth = 1.0 / _this.width;
  45876. _this.texelHeight = 1.0 / _this.height;
  45877. });
  45878. this.onApplyObservable.add(function (effect) {
  45879. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  45880. });
  45881. }
  45882. return FxaaPostProcess;
  45883. }(BABYLON.PostProcess));
  45884. BABYLON.FxaaPostProcess = FxaaPostProcess;
  45885. })(BABYLON || (BABYLON = {}));
  45886. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  45887. var BABYLON;
  45888. (function (BABYLON) {
  45889. var StereoscopicInterlacePostProcess = (function (_super) {
  45890. __extends(StereoscopicInterlacePostProcess, _super);
  45891. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  45892. var _this = this;
  45893. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  45894. this._passedProcess = rigCameras[0]._rigPostProcess;
  45895. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  45896. this.onSizeChangedObservable.add(function () {
  45897. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45898. });
  45899. this.onApplyObservable.add(function (effect) {
  45900. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  45901. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  45902. });
  45903. }
  45904. return StereoscopicInterlacePostProcess;
  45905. }(BABYLON.PostProcess));
  45906. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  45907. })(BABYLON || (BABYLON = {}));
  45908. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  45909. var BABYLON;
  45910. (function (BABYLON) {
  45911. var LensFlare = (function () {
  45912. function LensFlare(size, position, color, imgUrl, system) {
  45913. this.size = size;
  45914. this.position = position;
  45915. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  45916. this.dispose = function () {
  45917. if (this.texture) {
  45918. this.texture.dispose();
  45919. }
  45920. // Remove from scene
  45921. var index = this._system.lensFlares.indexOf(this);
  45922. this._system.lensFlares.splice(index, 1);
  45923. };
  45924. this.color = color || new BABYLON.Color3(1, 1, 1);
  45925. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  45926. this._system = system;
  45927. system.lensFlares.push(this);
  45928. }
  45929. return LensFlare;
  45930. }());
  45931. BABYLON.LensFlare = LensFlare;
  45932. })(BABYLON || (BABYLON = {}));
  45933. //# sourceMappingURL=babylon.lensFlare.js.map
  45934. var BABYLON;
  45935. (function (BABYLON) {
  45936. var LensFlareSystem = (function () {
  45937. function LensFlareSystem(name, emitter, scene) {
  45938. this.name = name;
  45939. this.lensFlares = new Array();
  45940. this.borderLimit = 300;
  45941. this.viewportBorder = 0;
  45942. this.layerMask = 0x0FFFFFFF;
  45943. this._vertexBuffers = {};
  45944. this._isEnabled = true;
  45945. this._scene = scene;
  45946. this._emitter = emitter;
  45947. this.id = name;
  45948. scene.lensFlareSystems.push(this);
  45949. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  45950. var engine = scene.getEngine();
  45951. // VBO
  45952. var vertices = [];
  45953. vertices.push(1, 1);
  45954. vertices.push(-1, 1);
  45955. vertices.push(-1, -1);
  45956. vertices.push(1, -1);
  45957. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  45958. // Indices
  45959. var indices = [];
  45960. indices.push(0);
  45961. indices.push(1);
  45962. indices.push(2);
  45963. indices.push(0);
  45964. indices.push(2);
  45965. indices.push(3);
  45966. this._indexBuffer = engine.createIndexBuffer(indices);
  45967. // Effects
  45968. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  45969. }
  45970. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  45971. get: function () {
  45972. return this._isEnabled;
  45973. },
  45974. set: function (value) {
  45975. this._isEnabled = value;
  45976. },
  45977. enumerable: true,
  45978. configurable: true
  45979. });
  45980. LensFlareSystem.prototype.getScene = function () {
  45981. return this._scene;
  45982. };
  45983. LensFlareSystem.prototype.getEmitter = function () {
  45984. return this._emitter;
  45985. };
  45986. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  45987. this._emitter = newEmitter;
  45988. };
  45989. LensFlareSystem.prototype.getEmitterPosition = function () {
  45990. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  45991. };
  45992. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  45993. var position = this.getEmitterPosition();
  45994. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  45995. this._positionX = position.x;
  45996. this._positionY = position.y;
  45997. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  45998. if (this.viewportBorder > 0) {
  45999. globalViewport.x -= this.viewportBorder;
  46000. globalViewport.y -= this.viewportBorder;
  46001. globalViewport.width += this.viewportBorder * 2;
  46002. globalViewport.height += this.viewportBorder * 2;
  46003. position.x += this.viewportBorder;
  46004. position.y += this.viewportBorder;
  46005. this._positionX += this.viewportBorder;
  46006. this._positionY += this.viewportBorder;
  46007. }
  46008. if (position.z > 0) {
  46009. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46010. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46011. return true;
  46012. }
  46013. return true;
  46014. }
  46015. return false;
  46016. };
  46017. LensFlareSystem.prototype._isVisible = function () {
  46018. if (!this._isEnabled) {
  46019. return false;
  46020. }
  46021. var emitterPosition = this.getEmitterPosition();
  46022. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  46023. var distance = direction.length();
  46024. direction.normalize();
  46025. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  46026. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46027. return !pickInfo.hit || pickInfo.distance > distance;
  46028. };
  46029. LensFlareSystem.prototype.render = function () {
  46030. if (!this._effect.isReady())
  46031. return false;
  46032. var engine = this._scene.getEngine();
  46033. var viewport = this._scene.activeCamera.viewport;
  46034. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46035. // Position
  46036. if (!this.computeEffectivePosition(globalViewport)) {
  46037. return false;
  46038. }
  46039. // Visibility
  46040. if (!this._isVisible()) {
  46041. return false;
  46042. }
  46043. // Intensity
  46044. var awayX;
  46045. var awayY;
  46046. if (this._positionX < this.borderLimit + globalViewport.x) {
  46047. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46048. }
  46049. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46050. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46051. }
  46052. else {
  46053. awayX = 0;
  46054. }
  46055. if (this._positionY < this.borderLimit + globalViewport.y) {
  46056. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46057. }
  46058. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46059. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46060. }
  46061. else {
  46062. awayY = 0;
  46063. }
  46064. var away = (awayX > awayY) ? awayX : awayY;
  46065. away -= this.viewportBorder;
  46066. if (away > this.borderLimit) {
  46067. away = this.borderLimit;
  46068. }
  46069. var intensity = 1.0 - (away / this.borderLimit);
  46070. if (intensity < 0) {
  46071. return false;
  46072. }
  46073. if (intensity > 1.0) {
  46074. intensity = 1.0;
  46075. }
  46076. if (this.viewportBorder > 0) {
  46077. globalViewport.x += this.viewportBorder;
  46078. globalViewport.y += this.viewportBorder;
  46079. globalViewport.width -= this.viewportBorder * 2;
  46080. globalViewport.height -= this.viewportBorder * 2;
  46081. this._positionX -= this.viewportBorder;
  46082. this._positionY -= this.viewportBorder;
  46083. }
  46084. // Position
  46085. var centerX = globalViewport.x + globalViewport.width / 2;
  46086. var centerY = globalViewport.y + globalViewport.height / 2;
  46087. var distX = centerX - this._positionX;
  46088. var distY = centerY - this._positionY;
  46089. // Effects
  46090. engine.enableEffect(this._effect);
  46091. engine.setState(false);
  46092. engine.setDepthBuffer(false);
  46093. // VBOs
  46094. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46095. // Flares
  46096. for (var index = 0; index < this.lensFlares.length; index++) {
  46097. var flare = this.lensFlares[index];
  46098. engine.setAlphaMode(flare.alphaMode);
  46099. var x = centerX - (distX * flare.position);
  46100. var y = centerY - (distY * flare.position);
  46101. var cw = flare.size;
  46102. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46103. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46104. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46105. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46106. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46107. // Texture
  46108. this._effect.setTexture("textureSampler", flare.texture);
  46109. // Color
  46110. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46111. // Draw order
  46112. engine.draw(true, 0, 6);
  46113. }
  46114. engine.setDepthBuffer(true);
  46115. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46116. return true;
  46117. };
  46118. LensFlareSystem.prototype.dispose = function () {
  46119. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46120. if (vertexBuffer) {
  46121. vertexBuffer.dispose();
  46122. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46123. }
  46124. if (this._indexBuffer) {
  46125. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46126. this._indexBuffer = null;
  46127. }
  46128. while (this.lensFlares.length) {
  46129. this.lensFlares[0].dispose();
  46130. }
  46131. // Remove from scene
  46132. var index = this._scene.lensFlareSystems.indexOf(this);
  46133. this._scene.lensFlareSystems.splice(index, 1);
  46134. };
  46135. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46136. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46137. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46138. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46139. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46140. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46141. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46142. var parsedFlare = parsedLensFlareSystem.flares[index];
  46143. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46144. }
  46145. return lensFlareSystem;
  46146. };
  46147. LensFlareSystem.prototype.serialize = function () {
  46148. var serializationObject = {};
  46149. serializationObject.id = this.id;
  46150. serializationObject.name = this.name;
  46151. serializationObject.emitterId = this.getEmitter().id;
  46152. serializationObject.borderLimit = this.borderLimit;
  46153. serializationObject.flares = [];
  46154. for (var index = 0; index < this.lensFlares.length; index++) {
  46155. var flare = this.lensFlares[index];
  46156. serializationObject.flares.push({
  46157. size: flare.size,
  46158. position: flare.position,
  46159. color: flare.color.asArray(),
  46160. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46161. });
  46162. }
  46163. return serializationObject;
  46164. };
  46165. return LensFlareSystem;
  46166. }());
  46167. BABYLON.LensFlareSystem = LensFlareSystem;
  46168. })(BABYLON || (BABYLON = {}));
  46169. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46170. var BABYLON;
  46171. (function (BABYLON) {
  46172. // We're mainly based on the logic defined into the FreeCamera code
  46173. var DeviceOrientationCamera = (function (_super) {
  46174. __extends(DeviceOrientationCamera, _super);
  46175. function DeviceOrientationCamera(name, position, scene) {
  46176. _super.call(this, name, position, scene);
  46177. this._quaternionCache = new BABYLON.Quaternion();
  46178. this.inputs.addDeviceOrientation();
  46179. }
  46180. DeviceOrientationCamera.prototype.getClassName = function () {
  46181. return "DeviceOrientationCamera";
  46182. };
  46183. DeviceOrientationCamera.prototype._checkInputs = function () {
  46184. _super.prototype._checkInputs.call(this);
  46185. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46186. if (this._initialQuaternion) {
  46187. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46188. }
  46189. };
  46190. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46191. var _this = this;
  46192. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46193. //can only work if this camera has a rotation quaternion already.
  46194. if (!this.rotationQuaternion)
  46195. return;
  46196. if (!this._initialQuaternion) {
  46197. this._initialQuaternion = new BABYLON.Quaternion();
  46198. }
  46199. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46200. ['x', 'y', 'z'].forEach(function (axisName) {
  46201. if (!axis[axisName]) {
  46202. _this._initialQuaternion[axisName] = 0;
  46203. }
  46204. else {
  46205. _this._initialQuaternion[axisName] *= -1;
  46206. }
  46207. });
  46208. this._initialQuaternion.normalize();
  46209. //force rotation update
  46210. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46211. };
  46212. return DeviceOrientationCamera;
  46213. }(BABYLON.FreeCamera));
  46214. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46215. })(BABYLON || (BABYLON = {}));
  46216. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46217. var BABYLON;
  46218. (function (BABYLON) {
  46219. var VRDeviceOrientationFreeCamera = (function (_super) {
  46220. __extends(VRDeviceOrientationFreeCamera, _super);
  46221. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46222. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46223. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46224. _super.call(this, name, position, scene);
  46225. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46226. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46227. }
  46228. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46229. return "VRDeviceOrientationFreeCamera";
  46230. };
  46231. return VRDeviceOrientationFreeCamera;
  46232. }(BABYLON.DeviceOrientationCamera));
  46233. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46234. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46235. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46236. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46237. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46238. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46239. _super.call(this, name, alpha, beta, radius, target, scene);
  46240. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46241. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46242. this.inputs.addVRDeviceOrientation();
  46243. }
  46244. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  46245. return "VRDeviceOrientationArcRotateCamera";
  46246. };
  46247. return VRDeviceOrientationArcRotateCamera;
  46248. }(BABYLON.ArcRotateCamera));
  46249. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46250. })(BABYLON || (BABYLON = {}));
  46251. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46252. var BABYLON;
  46253. (function (BABYLON) {
  46254. // We're mainly based on the logic defined into the FreeCamera code
  46255. var UniversalCamera = (function (_super) {
  46256. __extends(UniversalCamera, _super);
  46257. //-- end properties for backward compatibility for inputs
  46258. function UniversalCamera(name, position, scene) {
  46259. _super.call(this, name, position, scene);
  46260. this.inputs.addGamepad();
  46261. }
  46262. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46263. //-- Begin properties for backward compatibility for inputs
  46264. get: function () {
  46265. var gamepad = this.inputs.attached["gamepad"];
  46266. if (gamepad)
  46267. return gamepad.gamepadAngularSensibility;
  46268. },
  46269. set: function (value) {
  46270. var gamepad = this.inputs.attached["gamepad"];
  46271. if (gamepad)
  46272. gamepad.gamepadAngularSensibility = value;
  46273. },
  46274. enumerable: true,
  46275. configurable: true
  46276. });
  46277. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46278. get: function () {
  46279. var gamepad = this.inputs.attached["gamepad"];
  46280. if (gamepad)
  46281. return gamepad.gamepadMoveSensibility;
  46282. },
  46283. set: function (value) {
  46284. var gamepad = this.inputs.attached["gamepad"];
  46285. if (gamepad)
  46286. gamepad.gamepadMoveSensibility = value;
  46287. },
  46288. enumerable: true,
  46289. configurable: true
  46290. });
  46291. UniversalCamera.prototype.getClassName = function () {
  46292. return "UniversalCamera";
  46293. };
  46294. return UniversalCamera;
  46295. }(BABYLON.TouchCamera));
  46296. BABYLON.UniversalCamera = UniversalCamera;
  46297. })(BABYLON || (BABYLON = {}));
  46298. //# sourceMappingURL=babylon.universalCamera.js.map
  46299. var BABYLON;
  46300. (function (BABYLON) {
  46301. var Gamepads = (function () {
  46302. function Gamepads(ongamedpadconnected) {
  46303. var _this = this;
  46304. this.babylonGamepads = [];
  46305. this.oneGamepadConnected = false;
  46306. this.isMonitoring = false;
  46307. this.gamepadEventSupported = 'GamepadEvent' in window;
  46308. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46309. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46310. this._callbackGamepadConnected = ongamedpadconnected;
  46311. if (this.gamepadSupportAvailable) {
  46312. // Checking if the gamepad connected event is supported (like in Firefox)
  46313. if (this.gamepadEventSupported) {
  46314. this._onGamepadConnectedEvent = function (evt) {
  46315. _this._onGamepadConnected(evt);
  46316. };
  46317. this._onGamepadDisonnectedEvent = function (evt) {
  46318. _this._onGamepadDisconnected(evt);
  46319. };
  46320. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46321. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46322. }
  46323. else {
  46324. this._startMonitoringGamepads();
  46325. }
  46326. }
  46327. }
  46328. Gamepads.prototype.dispose = function () {
  46329. if (Gamepads.gamepadDOMInfo) {
  46330. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46331. }
  46332. if (this._onGamepadConnectedEvent) {
  46333. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46334. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46335. this._onGamepadConnectedEvent = null;
  46336. this._onGamepadDisonnectedEvent = null;
  46337. }
  46338. };
  46339. Gamepads.prototype._onGamepadConnected = function (evt) {
  46340. var newGamepad = this._addNewGamepad(evt.gamepad);
  46341. if (this._callbackGamepadConnected)
  46342. this._callbackGamepadConnected(newGamepad);
  46343. this._startMonitoringGamepads();
  46344. };
  46345. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46346. if (!this.oneGamepadConnected) {
  46347. this.oneGamepadConnected = true;
  46348. if (Gamepads.gamepadDOMInfo) {
  46349. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46350. Gamepads.gamepadDOMInfo = null;
  46351. }
  46352. }
  46353. var newGamepad;
  46354. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46355. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46356. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46357. }
  46358. else {
  46359. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46360. }
  46361. this.babylonGamepads.push(newGamepad);
  46362. return newGamepad;
  46363. };
  46364. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  46365. // Remove the gamepad from the list of gamepads to monitor.
  46366. for (var i in this.babylonGamepads) {
  46367. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  46368. this.babylonGamepads.splice(+i, 1);
  46369. break;
  46370. }
  46371. }
  46372. // If no gamepads are left, stop the polling loop.
  46373. if (this.babylonGamepads.length == 0) {
  46374. this._stopMonitoringGamepads();
  46375. }
  46376. };
  46377. Gamepads.prototype._startMonitoringGamepads = function () {
  46378. if (!this.isMonitoring) {
  46379. this.isMonitoring = true;
  46380. this._checkGamepadsStatus();
  46381. }
  46382. };
  46383. Gamepads.prototype._stopMonitoringGamepads = function () {
  46384. this.isMonitoring = false;
  46385. };
  46386. Gamepads.prototype._checkGamepadsStatus = function () {
  46387. var _this = this;
  46388. // updating gamepad objects
  46389. this._updateGamepadObjects();
  46390. for (var i in this.babylonGamepads) {
  46391. this.babylonGamepads[i].update();
  46392. }
  46393. if (this.isMonitoring) {
  46394. if (window.requestAnimationFrame) {
  46395. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46396. }
  46397. else if (window.mozRequestAnimationFrame) {
  46398. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46399. }
  46400. else if (window.webkitRequestAnimationFrame) {
  46401. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46402. }
  46403. }
  46404. };
  46405. // This function is called only on Chrome, which does not yet support
  46406. // connection/disconnection events, but requires you to monitor
  46407. // an array for changes.
  46408. Gamepads.prototype._updateGamepadObjects = function () {
  46409. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  46410. for (var i = 0; i < gamepads.length; i++) {
  46411. if (gamepads[i]) {
  46412. if (!(gamepads[i].index in this.babylonGamepads)) {
  46413. var newGamepad = this._addNewGamepad(gamepads[i]);
  46414. if (this._callbackGamepadConnected) {
  46415. this._callbackGamepadConnected(newGamepad);
  46416. }
  46417. }
  46418. else {
  46419. this.babylonGamepads[i].browserGamepad = gamepads[i];
  46420. }
  46421. }
  46422. }
  46423. };
  46424. return Gamepads;
  46425. }());
  46426. BABYLON.Gamepads = Gamepads;
  46427. var StickValues = (function () {
  46428. function StickValues(x, y) {
  46429. this.x = x;
  46430. this.y = y;
  46431. }
  46432. return StickValues;
  46433. }());
  46434. BABYLON.StickValues = StickValues;
  46435. var Gamepad = (function () {
  46436. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  46437. if (leftStickX === void 0) { leftStickX = 0; }
  46438. if (leftStickY === void 0) { leftStickY = 1; }
  46439. if (rightStickX === void 0) { rightStickX = 2; }
  46440. if (rightStickY === void 0) { rightStickY = 3; }
  46441. this.id = id;
  46442. this.index = index;
  46443. this.browserGamepad = browserGamepad;
  46444. this._leftStickAxisX = leftStickX;
  46445. this._leftStickAxisY = leftStickY;
  46446. this._rightStickAxisX = rightStickX;
  46447. this._rightStickAxisY = rightStickY;
  46448. if (this.browserGamepad.axes.length >= 2) {
  46449. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46450. }
  46451. if (this.browserGamepad.axes.length >= 4) {
  46452. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46453. }
  46454. }
  46455. Gamepad.prototype.onleftstickchanged = function (callback) {
  46456. this._onleftstickchanged = callback;
  46457. };
  46458. Gamepad.prototype.onrightstickchanged = function (callback) {
  46459. this._onrightstickchanged = callback;
  46460. };
  46461. Object.defineProperty(Gamepad.prototype, "leftStick", {
  46462. get: function () {
  46463. return this._leftStick;
  46464. },
  46465. set: function (newValues) {
  46466. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  46467. this._onleftstickchanged(newValues);
  46468. }
  46469. this._leftStick = newValues;
  46470. },
  46471. enumerable: true,
  46472. configurable: true
  46473. });
  46474. Object.defineProperty(Gamepad.prototype, "rightStick", {
  46475. get: function () {
  46476. return this._rightStick;
  46477. },
  46478. set: function (newValues) {
  46479. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  46480. this._onrightstickchanged(newValues);
  46481. }
  46482. this._rightStick = newValues;
  46483. },
  46484. enumerable: true,
  46485. configurable: true
  46486. });
  46487. Gamepad.prototype.update = function () {
  46488. if (this._leftStick) {
  46489. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46490. }
  46491. if (this._rightStick) {
  46492. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46493. }
  46494. };
  46495. return Gamepad;
  46496. }());
  46497. BABYLON.Gamepad = Gamepad;
  46498. var GenericPad = (function (_super) {
  46499. __extends(GenericPad, _super);
  46500. function GenericPad(id, index, gamepad) {
  46501. _super.call(this, id, index, gamepad);
  46502. this.id = id;
  46503. this.index = index;
  46504. this.gamepad = gamepad;
  46505. this._buttons = new Array(gamepad.buttons.length);
  46506. }
  46507. GenericPad.prototype.onbuttondown = function (callback) {
  46508. this._onbuttondown = callback;
  46509. };
  46510. GenericPad.prototype.onbuttonup = function (callback) {
  46511. this._onbuttonup = callback;
  46512. };
  46513. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  46514. if (newValue !== currentValue) {
  46515. if (this._onbuttondown && newValue === 1) {
  46516. this._onbuttondown(buttonIndex);
  46517. }
  46518. if (this._onbuttonup && newValue === 0) {
  46519. this._onbuttonup(buttonIndex);
  46520. }
  46521. }
  46522. return newValue;
  46523. };
  46524. GenericPad.prototype.update = function () {
  46525. _super.prototype.update.call(this);
  46526. for (var index = 0; index < this._buttons.length; index++) {
  46527. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  46528. }
  46529. };
  46530. return GenericPad;
  46531. }(Gamepad));
  46532. BABYLON.GenericPad = GenericPad;
  46533. (function (Xbox360Button) {
  46534. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  46535. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  46536. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  46537. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  46538. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  46539. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  46540. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  46541. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  46542. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  46543. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  46544. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  46545. var Xbox360Button = BABYLON.Xbox360Button;
  46546. (function (Xbox360Dpad) {
  46547. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  46548. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  46549. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  46550. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  46551. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  46552. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  46553. var Xbox360Pad = (function (_super) {
  46554. __extends(Xbox360Pad, _super);
  46555. function Xbox360Pad(id, index, gamepad, xboxOne) {
  46556. if (xboxOne === void 0) { xboxOne = false; }
  46557. _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3));
  46558. this._leftTrigger = 0;
  46559. this._rightTrigger = 0;
  46560. this._buttonA = 0;
  46561. this._buttonB = 0;
  46562. this._buttonX = 0;
  46563. this._buttonY = 0;
  46564. this._buttonBack = 0;
  46565. this._buttonStart = 0;
  46566. this._buttonLB = 0;
  46567. this._buttonRB = 0;
  46568. this._buttonLeftStick = 0;
  46569. this._buttonRightStick = 0;
  46570. this._dPadUp = 0;
  46571. this._dPadDown = 0;
  46572. this._dPadLeft = 0;
  46573. this._dPadRight = 0;
  46574. this._isXboxOnePad = false;
  46575. this._isXboxOnePad = xboxOne;
  46576. }
  46577. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  46578. this._onlefttriggerchanged = callback;
  46579. };
  46580. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  46581. this._onrighttriggerchanged = callback;
  46582. };
  46583. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  46584. get: function () {
  46585. return this._leftTrigger;
  46586. },
  46587. set: function (newValue) {
  46588. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  46589. this._onlefttriggerchanged(newValue);
  46590. }
  46591. this._leftTrigger = newValue;
  46592. },
  46593. enumerable: true,
  46594. configurable: true
  46595. });
  46596. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  46597. get: function () {
  46598. return this._rightTrigger;
  46599. },
  46600. set: function (newValue) {
  46601. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  46602. this._onrighttriggerchanged(newValue);
  46603. }
  46604. this._rightTrigger = newValue;
  46605. },
  46606. enumerable: true,
  46607. configurable: true
  46608. });
  46609. Xbox360Pad.prototype.onbuttondown = function (callback) {
  46610. this._onbuttondown = callback;
  46611. };
  46612. Xbox360Pad.prototype.onbuttonup = function (callback) {
  46613. this._onbuttonup = callback;
  46614. };
  46615. Xbox360Pad.prototype.ondpaddown = function (callback) {
  46616. this._ondpaddown = callback;
  46617. };
  46618. Xbox360Pad.prototype.ondpadup = function (callback) {
  46619. this._ondpadup = callback;
  46620. };
  46621. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  46622. if (newValue !== currentValue) {
  46623. if (this._onbuttondown && newValue === 1) {
  46624. this._onbuttondown(buttonType);
  46625. }
  46626. if (this._onbuttonup && newValue === 0) {
  46627. this._onbuttonup(buttonType);
  46628. }
  46629. }
  46630. return newValue;
  46631. };
  46632. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  46633. if (newValue !== currentValue) {
  46634. if (this._ondpaddown && newValue === 1) {
  46635. this._ondpaddown(buttonType);
  46636. }
  46637. if (this._ondpadup && newValue === 0) {
  46638. this._ondpadup(buttonType);
  46639. }
  46640. }
  46641. return newValue;
  46642. };
  46643. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  46644. get: function () {
  46645. return this._buttonA;
  46646. },
  46647. set: function (value) {
  46648. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  46649. },
  46650. enumerable: true,
  46651. configurable: true
  46652. });
  46653. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  46654. get: function () {
  46655. return this._buttonB;
  46656. },
  46657. set: function (value) {
  46658. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  46659. },
  46660. enumerable: true,
  46661. configurable: true
  46662. });
  46663. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  46664. get: function () {
  46665. return this._buttonX;
  46666. },
  46667. set: function (value) {
  46668. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  46669. },
  46670. enumerable: true,
  46671. configurable: true
  46672. });
  46673. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  46674. get: function () {
  46675. return this._buttonY;
  46676. },
  46677. set: function (value) {
  46678. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  46679. },
  46680. enumerable: true,
  46681. configurable: true
  46682. });
  46683. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  46684. get: function () {
  46685. return this._buttonStart;
  46686. },
  46687. set: function (value) {
  46688. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  46689. },
  46690. enumerable: true,
  46691. configurable: true
  46692. });
  46693. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  46694. get: function () {
  46695. return this._buttonBack;
  46696. },
  46697. set: function (value) {
  46698. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  46699. },
  46700. enumerable: true,
  46701. configurable: true
  46702. });
  46703. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  46704. get: function () {
  46705. return this._buttonLB;
  46706. },
  46707. set: function (value) {
  46708. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  46709. },
  46710. enumerable: true,
  46711. configurable: true
  46712. });
  46713. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  46714. get: function () {
  46715. return this._buttonRB;
  46716. },
  46717. set: function (value) {
  46718. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  46719. },
  46720. enumerable: true,
  46721. configurable: true
  46722. });
  46723. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  46724. get: function () {
  46725. return this._buttonLeftStick;
  46726. },
  46727. set: function (value) {
  46728. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  46729. },
  46730. enumerable: true,
  46731. configurable: true
  46732. });
  46733. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  46734. get: function () {
  46735. return this._buttonRightStick;
  46736. },
  46737. set: function (value) {
  46738. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  46739. },
  46740. enumerable: true,
  46741. configurable: true
  46742. });
  46743. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  46744. get: function () {
  46745. return this._dPadUp;
  46746. },
  46747. set: function (value) {
  46748. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  46749. },
  46750. enumerable: true,
  46751. configurable: true
  46752. });
  46753. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  46754. get: function () {
  46755. return this._dPadDown;
  46756. },
  46757. set: function (value) {
  46758. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  46759. },
  46760. enumerable: true,
  46761. configurable: true
  46762. });
  46763. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  46764. get: function () {
  46765. return this._dPadLeft;
  46766. },
  46767. set: function (value) {
  46768. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  46769. },
  46770. enumerable: true,
  46771. configurable: true
  46772. });
  46773. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  46774. get: function () {
  46775. return this._dPadRight;
  46776. },
  46777. set: function (value) {
  46778. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  46779. },
  46780. enumerable: true,
  46781. configurable: true
  46782. });
  46783. Xbox360Pad.prototype.update = function () {
  46784. _super.prototype.update.call(this);
  46785. if (this._isXboxOnePad) {
  46786. this.buttonA = this.browserGamepad.buttons[0].value;
  46787. this.buttonB = this.browserGamepad.buttons[1].value;
  46788. this.buttonX = this.browserGamepad.buttons[2].value;
  46789. this.buttonY = this.browserGamepad.buttons[3].value;
  46790. this.buttonLB = this.browserGamepad.buttons[4].value;
  46791. this.buttonRB = this.browserGamepad.buttons[5].value;
  46792. this.leftTrigger = this.browserGamepad.axes[2];
  46793. this.rightTrigger = this.browserGamepad.axes[5];
  46794. this.buttonBack = this.browserGamepad.buttons[9].value;
  46795. this.buttonStart = this.browserGamepad.buttons[8].value;
  46796. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  46797. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  46798. this.dPadUp = this.browserGamepad.buttons[11].value;
  46799. this.dPadDown = this.browserGamepad.buttons[12].value;
  46800. this.dPadLeft = this.browserGamepad.buttons[13].value;
  46801. this.dPadRight = this.browserGamepad.buttons[14].value;
  46802. }
  46803. else {
  46804. this.buttonA = this.browserGamepad.buttons[0].value;
  46805. this.buttonB = this.browserGamepad.buttons[1].value;
  46806. this.buttonX = this.browserGamepad.buttons[2].value;
  46807. this.buttonY = this.browserGamepad.buttons[3].value;
  46808. this.buttonLB = this.browserGamepad.buttons[4].value;
  46809. this.buttonRB = this.browserGamepad.buttons[5].value;
  46810. this.leftTrigger = this.browserGamepad.buttons[6].value;
  46811. this.rightTrigger = this.browserGamepad.buttons[7].value;
  46812. this.buttonBack = this.browserGamepad.buttons[8].value;
  46813. this.buttonStart = this.browserGamepad.buttons[9].value;
  46814. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  46815. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  46816. this.dPadUp = this.browserGamepad.buttons[12].value;
  46817. this.dPadDown = this.browserGamepad.buttons[13].value;
  46818. this.dPadLeft = this.browserGamepad.buttons[14].value;
  46819. this.dPadRight = this.browserGamepad.buttons[15].value;
  46820. }
  46821. };
  46822. return Xbox360Pad;
  46823. }(Gamepad));
  46824. BABYLON.Xbox360Pad = Xbox360Pad;
  46825. })(BABYLON || (BABYLON = {}));
  46826. //# sourceMappingURL=babylon.gamepads.js.map
  46827. var BABYLON;
  46828. (function (BABYLON) {
  46829. // We're mainly based on the logic defined into the FreeCamera code
  46830. var GamepadCamera = (function (_super) {
  46831. __extends(GamepadCamera, _super);
  46832. //-- end properties for backward compatibility for inputs
  46833. function GamepadCamera(name, position, scene) {
  46834. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  46835. _super.call(this, name, position, scene);
  46836. }
  46837. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46838. //-- Begin properties for backward compatibility for inputs
  46839. get: function () {
  46840. var gamepad = this.inputs.attached["gamepad"];
  46841. if (gamepad)
  46842. return gamepad.gamepadAngularSensibility;
  46843. },
  46844. set: function (value) {
  46845. var gamepad = this.inputs.attached["gamepad"];
  46846. if (gamepad)
  46847. gamepad.gamepadAngularSensibility = value;
  46848. },
  46849. enumerable: true,
  46850. configurable: true
  46851. });
  46852. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46853. get: function () {
  46854. var gamepad = this.inputs.attached["gamepad"];
  46855. if (gamepad)
  46856. return gamepad.gamepadMoveSensibility;
  46857. },
  46858. set: function (value) {
  46859. var gamepad = this.inputs.attached["gamepad"];
  46860. if (gamepad)
  46861. gamepad.gamepadMoveSensibility = value;
  46862. },
  46863. enumerable: true,
  46864. configurable: true
  46865. });
  46866. GamepadCamera.prototype.getClassName = function () {
  46867. return "GamepadCamera";
  46868. };
  46869. return GamepadCamera;
  46870. }(BABYLON.UniversalCamera));
  46871. BABYLON.GamepadCamera = GamepadCamera;
  46872. })(BABYLON || (BABYLON = {}));
  46873. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46874. var BABYLON;
  46875. (function (BABYLON) {
  46876. var Analyser = (function () {
  46877. function Analyser(scene) {
  46878. this.SMOOTHING = 0.75;
  46879. this.FFT_SIZE = 512;
  46880. this.BARGRAPHAMPLITUDE = 256;
  46881. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  46882. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  46883. this._scene = scene;
  46884. this._audioEngine = BABYLON.Engine.audioEngine;
  46885. if (this._audioEngine.canUseWebAudio) {
  46886. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  46887. this._webAudioAnalyser.minDecibels = -140;
  46888. this._webAudioAnalyser.maxDecibels = 0;
  46889. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46890. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46891. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  46892. }
  46893. }
  46894. Analyser.prototype.getFrequencyBinCount = function () {
  46895. if (this._audioEngine.canUseWebAudio) {
  46896. return this._webAudioAnalyser.frequencyBinCount;
  46897. }
  46898. else {
  46899. return 0;
  46900. }
  46901. };
  46902. Analyser.prototype.getByteFrequencyData = function () {
  46903. if (this._audioEngine.canUseWebAudio) {
  46904. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46905. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46906. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  46907. }
  46908. return this._byteFreqs;
  46909. };
  46910. Analyser.prototype.getByteTimeDomainData = function () {
  46911. if (this._audioEngine.canUseWebAudio) {
  46912. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46913. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46914. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  46915. }
  46916. return this._byteTime;
  46917. };
  46918. Analyser.prototype.getFloatFrequencyData = function () {
  46919. if (this._audioEngine.canUseWebAudio) {
  46920. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46921. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46922. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  46923. }
  46924. return this._floatFreqs;
  46925. };
  46926. Analyser.prototype.drawDebugCanvas = function () {
  46927. var _this = this;
  46928. if (this._audioEngine.canUseWebAudio) {
  46929. if (!this._debugCanvas) {
  46930. this._debugCanvas = document.createElement("canvas");
  46931. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  46932. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  46933. this._debugCanvas.style.position = "absolute";
  46934. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  46935. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  46936. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  46937. document.body.appendChild(this._debugCanvas);
  46938. this._registerFunc = function () {
  46939. _this.drawDebugCanvas();
  46940. };
  46941. this._scene.registerBeforeRender(this._registerFunc);
  46942. }
  46943. if (this._registerFunc) {
  46944. var workingArray = this.getByteFrequencyData();
  46945. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  46946. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  46947. // Draw the frequency domain chart.
  46948. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  46949. var value = workingArray[i];
  46950. var percent = value / this.BARGRAPHAMPLITUDE;
  46951. var height = this.DEBUGCANVASSIZE.height * percent;
  46952. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  46953. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  46954. var hue = i / this.getFrequencyBinCount() * 360;
  46955. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  46956. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  46957. }
  46958. }
  46959. }
  46960. };
  46961. Analyser.prototype.stopDebugCanvas = function () {
  46962. if (this._debugCanvas) {
  46963. this._scene.unregisterBeforeRender(this._registerFunc);
  46964. this._registerFunc = null;
  46965. document.body.removeChild(this._debugCanvas);
  46966. this._debugCanvas = null;
  46967. this._debugCanvasContext = null;
  46968. }
  46969. };
  46970. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  46971. if (this._audioEngine.canUseWebAudio) {
  46972. inputAudioNode.connect(this._webAudioAnalyser);
  46973. this._webAudioAnalyser.connect(outputAudioNode);
  46974. }
  46975. };
  46976. Analyser.prototype.dispose = function () {
  46977. if (this._audioEngine.canUseWebAudio) {
  46978. this._webAudioAnalyser.disconnect();
  46979. }
  46980. };
  46981. return Analyser;
  46982. }());
  46983. BABYLON.Analyser = Analyser;
  46984. })(BABYLON || (BABYLON = {}));
  46985. //# sourceMappingURL=babylon.analyser.js.map
  46986. var BABYLON;
  46987. (function (BABYLON) {
  46988. var DepthRenderer = (function () {
  46989. function DepthRenderer(scene, type) {
  46990. var _this = this;
  46991. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  46992. this._viewMatrix = BABYLON.Matrix.Zero();
  46993. this._projectionMatrix = BABYLON.Matrix.Zero();
  46994. this._transformMatrix = BABYLON.Matrix.Zero();
  46995. this._worldViewProjection = BABYLON.Matrix.Zero();
  46996. this._scene = scene;
  46997. var engine = scene.getEngine();
  46998. // Render target
  46999. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47000. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47001. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47002. this._depthMap.refreshRate = 1;
  47003. this._depthMap.renderParticles = false;
  47004. this._depthMap.renderList = null;
  47005. // set default depth value to 1.0 (far away)
  47006. this._depthMap.onClearObservable.add(function (engine) {
  47007. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47008. });
  47009. // Custom render function
  47010. var renderSubMesh = function (subMesh) {
  47011. var mesh = subMesh.getRenderingMesh();
  47012. var scene = _this._scene;
  47013. var engine = scene.getEngine();
  47014. // Culling
  47015. engine.setState(subMesh.getMaterial().backFaceCulling);
  47016. // Managing instances
  47017. var batch = mesh._getInstancesRenderList(subMesh._id);
  47018. if (batch.mustReturn) {
  47019. return;
  47020. }
  47021. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47022. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47023. engine.enableEffect(_this._effect);
  47024. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47025. var material = subMesh.getMaterial();
  47026. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47027. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47028. // Alpha test
  47029. if (material && material.needAlphaTesting()) {
  47030. var alphaTexture = material.getAlphaTestTexture();
  47031. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47032. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47033. }
  47034. // Bones
  47035. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47036. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47037. }
  47038. // Draw
  47039. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47040. }
  47041. };
  47042. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47043. var index;
  47044. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47045. renderSubMesh(opaqueSubMeshes.data[index]);
  47046. }
  47047. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47048. renderSubMesh(alphaTestSubMeshes.data[index]);
  47049. }
  47050. };
  47051. }
  47052. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47053. var material = subMesh.getMaterial();
  47054. if (material.disableDepthWrite) {
  47055. return false;
  47056. }
  47057. var defines = [];
  47058. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47059. var mesh = subMesh.getMesh();
  47060. var scene = mesh.getScene();
  47061. // Alpha test
  47062. if (material && material.needAlphaTesting()) {
  47063. defines.push("#define ALPHATEST");
  47064. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47065. attribs.push(BABYLON.VertexBuffer.UVKind);
  47066. defines.push("#define UV1");
  47067. }
  47068. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47069. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47070. defines.push("#define UV2");
  47071. }
  47072. }
  47073. // Bones
  47074. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47075. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47076. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47077. if (mesh.numBoneInfluencers > 4) {
  47078. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47079. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47080. }
  47081. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47082. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47083. }
  47084. else {
  47085. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47086. }
  47087. // Instances
  47088. if (useInstances) {
  47089. defines.push("#define INSTANCES");
  47090. attribs.push("world0");
  47091. attribs.push("world1");
  47092. attribs.push("world2");
  47093. attribs.push("world3");
  47094. }
  47095. // Get correct effect
  47096. var join = defines.join("\n");
  47097. if (this._cachedDefines !== join) {
  47098. this._cachedDefines = join;
  47099. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47100. }
  47101. return this._effect.isReady();
  47102. };
  47103. DepthRenderer.prototype.getDepthMap = function () {
  47104. return this._depthMap;
  47105. };
  47106. // Methods
  47107. DepthRenderer.prototype.dispose = function () {
  47108. this._depthMap.dispose();
  47109. };
  47110. return DepthRenderer;
  47111. }());
  47112. BABYLON.DepthRenderer = DepthRenderer;
  47113. })(BABYLON || (BABYLON = {}));
  47114. //# sourceMappingURL=babylon.depthRenderer.js.map
  47115. var BABYLON;
  47116. (function (BABYLON) {
  47117. var SSAORenderingPipeline = (function (_super) {
  47118. __extends(SSAORenderingPipeline, _super);
  47119. /**
  47120. * @constructor
  47121. * @param {string} name - The rendering pipeline name
  47122. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47123. * @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 }
  47124. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47125. */
  47126. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47127. var _this = this;
  47128. _super.call(this, scene.getEngine(), name);
  47129. // Members
  47130. /**
  47131. * The PassPostProcess id in the pipeline that contains the original scene color
  47132. * @type {string}
  47133. */
  47134. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47135. /**
  47136. * The SSAO PostProcess id in the pipeline
  47137. * @type {string}
  47138. */
  47139. this.SSAORenderEffect = "SSAORenderEffect";
  47140. /**
  47141. * The horizontal blur PostProcess id in the pipeline
  47142. * @type {string}
  47143. */
  47144. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47145. /**
  47146. * The vertical blur PostProcess id in the pipeline
  47147. * @type {string}
  47148. */
  47149. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47150. /**
  47151. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47152. * @type {string}
  47153. */
  47154. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47155. /**
  47156. * The output strength of the SSAO post-process. Default value is 1.0.
  47157. * @type {number}
  47158. */
  47159. this.totalStrength = 1.0;
  47160. /**
  47161. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47162. * @type {number}
  47163. */
  47164. this.radius = 0.0001;
  47165. /**
  47166. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47167. * Must not be equal to fallOff and superior to fallOff.
  47168. * Default value is 0.975
  47169. * @type {number}
  47170. */
  47171. this.area = 0.0075;
  47172. /**
  47173. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47174. * Must not be equal to area and inferior to area.
  47175. * Default value is 0.0
  47176. * @type {number}
  47177. */
  47178. this.fallOff = 0.000001;
  47179. /**
  47180. * The base color of the SSAO post-process
  47181. * The final result is "base + ssao" between [0, 1]
  47182. * @type {number}
  47183. */
  47184. this.base = 0.5;
  47185. this._firstUpdate = true;
  47186. this._scene = scene;
  47187. // Set up assets
  47188. this._createRandomTexture();
  47189. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47190. var ssaoRatio = ratio.ssaoRatio || ratio;
  47191. var combineRatio = ratio.combineRatio || ratio;
  47192. this._ratio = {
  47193. ssaoRatio: ssaoRatio,
  47194. combineRatio: combineRatio
  47195. };
  47196. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47197. this._createSSAOPostProcess(ssaoRatio);
  47198. this._createBlurPostProcess(ssaoRatio);
  47199. this._createSSAOCombinePostProcess(combineRatio);
  47200. // Set up pipeline
  47201. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47202. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47203. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47204. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47205. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47206. // Finish
  47207. scene.postProcessRenderPipelineManager.addPipeline(this);
  47208. if (cameras)
  47209. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47210. }
  47211. // Public Methods
  47212. /**
  47213. * Returns the horizontal blur PostProcess
  47214. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47215. */
  47216. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47217. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47218. return null;
  47219. };
  47220. /**
  47221. * Returns the vertical blur PostProcess
  47222. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47223. */
  47224. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47225. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47226. return null;
  47227. };
  47228. /**
  47229. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47230. */
  47231. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47232. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47233. for (var i = 0; i < this._scene.cameras.length; i++) {
  47234. var camera = this._scene.cameras[i];
  47235. this._originalColorPostProcess.dispose(camera);
  47236. this._ssaoPostProcess.dispose(camera);
  47237. this._blurHPostProcess.dispose(camera);
  47238. this._blurVPostProcess.dispose(camera);
  47239. this._ssaoCombinePostProcess.dispose(camera);
  47240. }
  47241. this._randomTexture.dispose();
  47242. if (disableDepthRender)
  47243. this._scene.disableDepthRenderer();
  47244. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47245. };
  47246. // Private Methods
  47247. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47248. var _this = this;
  47249. /*
  47250. var samplerOffsets = [
  47251. -8.0, -6.0, -4.0, -2.0,
  47252. 0.0,
  47253. 2.0, 4.0, 6.0, 8.0
  47254. ];
  47255. */
  47256. var samples = 16;
  47257. var samplerOffsets = [];
  47258. for (var i = -8; i < 8; i++) {
  47259. samplerOffsets.push(i * 2);
  47260. }
  47261. 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");
  47262. this._blurHPostProcess.onApply = function (effect) {
  47263. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47264. effect.setTexture("depthSampler", _this._depthTexture);
  47265. if (_this._firstUpdate) {
  47266. effect.setArray("samplerOffsets", samplerOffsets);
  47267. }
  47268. };
  47269. 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");
  47270. this._blurVPostProcess.onApply = function (effect) {
  47271. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47272. effect.setTexture("depthSampler", _this._depthTexture);
  47273. if (_this._firstUpdate) {
  47274. effect.setArray("samplerOffsets", samplerOffsets);
  47275. _this._firstUpdate = false;
  47276. }
  47277. };
  47278. };
  47279. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47280. var _this = this;
  47281. var numSamples = 16;
  47282. var sampleSphere = [
  47283. 0.5381, 0.1856, -0.4319,
  47284. 0.1379, 0.2486, 0.4430,
  47285. 0.3371, 0.5679, -0.0057,
  47286. -0.6999, -0.0451, -0.0019,
  47287. 0.0689, -0.1598, -0.8547,
  47288. 0.0560, 0.0069, -0.1843,
  47289. -0.0146, 0.1402, 0.0762,
  47290. 0.0100, -0.1924, -0.0344,
  47291. -0.3577, -0.5301, -0.4358,
  47292. -0.3169, 0.1063, 0.0158,
  47293. 0.0103, -0.5869, 0.0046,
  47294. -0.0897, -0.4940, 0.3287,
  47295. 0.7119, -0.0154, -0.0918,
  47296. -0.0533, 0.0596, -0.5411,
  47297. 0.0352, -0.0631, 0.5460,
  47298. -0.4776, 0.2847, -0.0271
  47299. ];
  47300. var samplesFactor = 1.0 / numSamples;
  47301. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47302. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47303. "area", "fallOff", "base", "range", "viewport"
  47304. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47305. var viewport = new BABYLON.Vector2(0, 0);
  47306. this._ssaoPostProcess.onApply = function (effect) {
  47307. if (_this._firstUpdate) {
  47308. effect.setArray3("sampleSphere", sampleSphere);
  47309. effect.setFloat("samplesFactor", samplesFactor);
  47310. effect.setFloat("randTextureTiles", 4.0);
  47311. }
  47312. effect.setFloat("totalStrength", _this.totalStrength);
  47313. effect.setFloat("radius", _this.radius);
  47314. effect.setFloat("area", _this.area);
  47315. effect.setFloat("fallOff", _this.fallOff);
  47316. effect.setFloat("base", _this.base);
  47317. effect.setTexture("textureSampler", _this._depthTexture);
  47318. effect.setTexture("randomSampler", _this._randomTexture);
  47319. };
  47320. };
  47321. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47322. var _this = this;
  47323. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47324. this._ssaoCombinePostProcess.onApply = function (effect) {
  47325. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47326. };
  47327. };
  47328. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47329. var size = 512;
  47330. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47331. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47332. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47333. var context = this._randomTexture.getContext();
  47334. var rand = function (min, max) {
  47335. return Math.random() * (max - min) + min;
  47336. };
  47337. var randVector = BABYLON.Vector3.Zero();
  47338. for (var x = 0; x < size; x++) {
  47339. for (var y = 0; y < size; y++) {
  47340. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47341. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47342. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47343. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47344. context.fillRect(x, y, 1, 1);
  47345. }
  47346. }
  47347. this._randomTexture.update(false);
  47348. };
  47349. __decorate([
  47350. BABYLON.serialize()
  47351. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47352. __decorate([
  47353. BABYLON.serialize()
  47354. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47355. __decorate([
  47356. BABYLON.serialize()
  47357. ], SSAORenderingPipeline.prototype, "area", void 0);
  47358. __decorate([
  47359. BABYLON.serialize()
  47360. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47361. __decorate([
  47362. BABYLON.serialize()
  47363. ], SSAORenderingPipeline.prototype, "base", void 0);
  47364. __decorate([
  47365. BABYLON.serialize()
  47366. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47367. return SSAORenderingPipeline;
  47368. }(BABYLON.PostProcessRenderPipeline));
  47369. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47370. })(BABYLON || (BABYLON = {}));
  47371. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47372. var BABYLON;
  47373. (function (BABYLON) {
  47374. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47375. var VolumetricLightScatteringPostProcess = (function (_super) {
  47376. __extends(VolumetricLightScatteringPostProcess, _super);
  47377. /**
  47378. * @constructor
  47379. * @param {string} name - The post-process name
  47380. * @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)
  47381. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47382. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47383. * @param {number} samples - The post-process quality, default 100
  47384. * @param {number} samplingMode - The post-process filtering mode
  47385. * @param {BABYLON.Engine} engine - The babylon engine
  47386. * @param {boolean} reusable - If the post-process is reusable
  47387. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47388. */
  47389. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47390. var _this = this;
  47391. if (samples === void 0) { samples = 100; }
  47392. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47393. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  47394. this._screenCoordinates = BABYLON.Vector2.Zero();
  47395. /**
  47396. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47397. * @type {Vector3}
  47398. */
  47399. this.customMeshPosition = BABYLON.Vector3.Zero();
  47400. /**
  47401. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47402. * @type {boolean}
  47403. */
  47404. this.useCustomMeshPosition = false;
  47405. /**
  47406. * If the post-process should inverse the light scattering direction
  47407. * @type {boolean}
  47408. */
  47409. this.invert = true;
  47410. /**
  47411. * Array containing the excluded meshes not rendered in the internal pass
  47412. */
  47413. this.excludedMeshes = new Array();
  47414. /**
  47415. * Controls the overall intensity of the post-process
  47416. * @type {number}
  47417. */
  47418. this.exposure = 0.3;
  47419. /**
  47420. * Dissipates each sample's contribution in range [0, 1]
  47421. * @type {number}
  47422. */
  47423. this.decay = 0.96815;
  47424. /**
  47425. * Controls the overall intensity of each sample
  47426. * @type {number}
  47427. */
  47428. this.weight = 0.58767;
  47429. /**
  47430. * Controls the density of each sample
  47431. * @type {number}
  47432. */
  47433. this.density = 0.926;
  47434. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47435. var engine = scene.getEngine();
  47436. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47437. // Configure mesh
  47438. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47439. // Configure
  47440. this._createPass(scene, ratio.passRatio || ratio);
  47441. this.onActivate = function (camera) {
  47442. if (!_this.isSupported) {
  47443. _this.dispose(camera);
  47444. }
  47445. _this.onActivate = null;
  47446. };
  47447. this.onApplyObservable.add(function (effect) {
  47448. _this._updateMeshScreenCoordinates(scene);
  47449. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47450. effect.setFloat("exposure", _this.exposure);
  47451. effect.setFloat("decay", _this.decay);
  47452. effect.setFloat("weight", _this.weight);
  47453. effect.setFloat("density", _this.density);
  47454. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47455. });
  47456. }
  47457. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47458. get: function () {
  47459. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47460. return false;
  47461. },
  47462. set: function (useDiffuseColor) {
  47463. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47464. },
  47465. enumerable: true,
  47466. configurable: true
  47467. });
  47468. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47469. var mesh = subMesh.getMesh();
  47470. // Render this.mesh as default
  47471. if (mesh === this.mesh) {
  47472. return mesh.material.isReady(mesh);
  47473. }
  47474. var defines = [];
  47475. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47476. var material = subMesh.getMaterial();
  47477. var needUV = false;
  47478. // Alpha test
  47479. if (material) {
  47480. if (material.needAlphaTesting()) {
  47481. defines.push("#define ALPHATEST");
  47482. }
  47483. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47484. attribs.push(BABYLON.VertexBuffer.UVKind);
  47485. defines.push("#define UV1");
  47486. }
  47487. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47488. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47489. defines.push("#define UV2");
  47490. }
  47491. }
  47492. // Bones
  47493. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47494. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47495. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47496. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47497. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47498. }
  47499. else {
  47500. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47501. }
  47502. // Instances
  47503. if (useInstances) {
  47504. defines.push("#define INSTANCES");
  47505. attribs.push("world0");
  47506. attribs.push("world1");
  47507. attribs.push("world2");
  47508. attribs.push("world3");
  47509. }
  47510. // Get correct effect
  47511. var join = defines.join("\n");
  47512. if (this._cachedDefines !== join) {
  47513. this._cachedDefines = join;
  47514. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47515. }
  47516. return this._volumetricLightScatteringPass.isReady();
  47517. };
  47518. /**
  47519. * Sets the new light position for light scattering effect
  47520. * @param {BABYLON.Vector3} The new custom light position
  47521. */
  47522. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47523. this.customMeshPosition = position;
  47524. };
  47525. /**
  47526. * Returns the light position for light scattering effect
  47527. * @return {BABYLON.Vector3} The custom light position
  47528. */
  47529. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47530. return this.customMeshPosition;
  47531. };
  47532. /**
  47533. * Disposes the internal assets and detaches the post-process from the camera
  47534. */
  47535. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47536. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47537. if (rttIndex !== -1) {
  47538. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47539. }
  47540. this._volumetricLightScatteringRTT.dispose();
  47541. _super.prototype.dispose.call(this, camera);
  47542. };
  47543. /**
  47544. * Returns the render target texture used by the post-process
  47545. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47546. */
  47547. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47548. return this._volumetricLightScatteringRTT;
  47549. };
  47550. // Private methods
  47551. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47552. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47553. return true;
  47554. }
  47555. return false;
  47556. };
  47557. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47558. var _this = this;
  47559. var engine = scene.getEngine();
  47560. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47561. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47562. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47563. this._volumetricLightScatteringRTT.renderList = null;
  47564. this._volumetricLightScatteringRTT.renderParticles = false;
  47565. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47566. // Custom render function for submeshes
  47567. var renderSubMesh = function (subMesh) {
  47568. var mesh = subMesh.getRenderingMesh();
  47569. if (_this._meshExcluded(mesh)) {
  47570. return;
  47571. }
  47572. var scene = mesh.getScene();
  47573. var engine = scene.getEngine();
  47574. // Culling
  47575. engine.setState(subMesh.getMaterial().backFaceCulling);
  47576. // Managing instances
  47577. var batch = mesh._getInstancesRenderList(subMesh._id);
  47578. if (batch.mustReturn) {
  47579. return;
  47580. }
  47581. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47582. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47583. var effect = _this._volumetricLightScatteringPass;
  47584. if (mesh === _this.mesh) {
  47585. effect = subMesh.getMaterial().getEffect();
  47586. }
  47587. engine.enableEffect(effect);
  47588. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47589. if (mesh === _this.mesh) {
  47590. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47591. }
  47592. else {
  47593. var material = subMesh.getMaterial();
  47594. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47595. // Alpha test
  47596. if (material && material.needAlphaTesting()) {
  47597. var alphaTexture = material.getAlphaTestTexture();
  47598. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47599. if (alphaTexture) {
  47600. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47601. }
  47602. }
  47603. // Bones
  47604. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47605. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47606. }
  47607. }
  47608. // Draw
  47609. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47610. }
  47611. };
  47612. // Render target texture callbacks
  47613. var savedSceneClearColor;
  47614. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47615. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47616. savedSceneClearColor = scene.clearColor;
  47617. scene.clearColor = sceneClearColor;
  47618. });
  47619. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47620. scene.clearColor = savedSceneClearColor;
  47621. });
  47622. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47623. var engine = scene.getEngine();
  47624. var index;
  47625. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47626. renderSubMesh(opaqueSubMeshes.data[index]);
  47627. }
  47628. engine.setAlphaTesting(true);
  47629. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47630. renderSubMesh(alphaTestSubMeshes.data[index]);
  47631. }
  47632. engine.setAlphaTesting(false);
  47633. if (transparentSubMeshes.length) {
  47634. // Sort sub meshes
  47635. for (index = 0; index < transparentSubMeshes.length; index++) {
  47636. var submesh = transparentSubMeshes.data[index];
  47637. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47638. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47639. }
  47640. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47641. sortedArray.sort(function (a, b) {
  47642. // Alpha index first
  47643. if (a._alphaIndex > b._alphaIndex) {
  47644. return 1;
  47645. }
  47646. if (a._alphaIndex < b._alphaIndex) {
  47647. return -1;
  47648. }
  47649. // Then distance to camera
  47650. if (a._distanceToCamera < b._distanceToCamera) {
  47651. return 1;
  47652. }
  47653. if (a._distanceToCamera > b._distanceToCamera) {
  47654. return -1;
  47655. }
  47656. return 0;
  47657. });
  47658. // Render sub meshes
  47659. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47660. for (index = 0; index < sortedArray.length; index++) {
  47661. renderSubMesh(sortedArray[index]);
  47662. }
  47663. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47664. }
  47665. };
  47666. };
  47667. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47668. var transform = scene.getTransformMatrix();
  47669. var meshPosition;
  47670. if (this.useCustomMeshPosition) {
  47671. meshPosition = this.customMeshPosition;
  47672. }
  47673. else if (this.attachedNode) {
  47674. meshPosition = this.attachedNode.position;
  47675. }
  47676. else {
  47677. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47678. }
  47679. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47680. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47681. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47682. if (this.invert)
  47683. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47684. };
  47685. // Static methods
  47686. /**
  47687. * Creates a default mesh for the Volumeric Light Scattering post-process
  47688. * @param {string} The mesh name
  47689. * @param {BABYLON.Scene} The scene where to create the mesh
  47690. * @return {BABYLON.Mesh} the default mesh
  47691. */
  47692. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47693. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47694. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47695. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47696. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47697. mesh.material = material;
  47698. return mesh;
  47699. };
  47700. __decorate([
  47701. BABYLON.serializeAsVector3()
  47702. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47703. __decorate([
  47704. BABYLON.serialize()
  47705. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47706. __decorate([
  47707. BABYLON.serialize()
  47708. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47709. __decorate([
  47710. BABYLON.serializeAsMeshReference()
  47711. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47712. __decorate([
  47713. BABYLON.serialize()
  47714. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47715. __decorate([
  47716. BABYLON.serialize()
  47717. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47718. __decorate([
  47719. BABYLON.serialize()
  47720. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47721. __decorate([
  47722. BABYLON.serialize()
  47723. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47724. __decorate([
  47725. BABYLON.serialize()
  47726. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47727. return VolumetricLightScatteringPostProcess;
  47728. }(BABYLON.PostProcess));
  47729. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47730. })(BABYLON || (BABYLON = {}));
  47731. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  47732. // BABYLON.JS Chromatic Aberration GLSL Shader
  47733. // Author: Olivier Guyot
  47734. // Separates very slightly R, G and B colors on the edges of the screen
  47735. // Inspired by Francois Tarlier & Martins Upitis
  47736. var BABYLON;
  47737. (function (BABYLON) {
  47738. var LensRenderingPipeline = (function (_super) {
  47739. __extends(LensRenderingPipeline, _super);
  47740. /**
  47741. * @constructor
  47742. *
  47743. * Effect parameters are as follow:
  47744. * {
  47745. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47746. * edge_blur: number; // from 0 to x (1 for realism)
  47747. * distortion: number; // from 0 to x (1 for realism)
  47748. * grain_amount: number; // from 0 to 1
  47749. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47750. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47751. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47752. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47753. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47754. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47755. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47756. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47757. * }
  47758. * Note: if an effect parameter is unset, effect is disabled
  47759. *
  47760. * @param {string} name - The rendering pipeline name
  47761. * @param {object} parameters - An object containing all parameters (see above)
  47762. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47763. * @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)
  47764. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47765. */
  47766. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47767. var _this = this;
  47768. if (ratio === void 0) { ratio = 1.0; }
  47769. _super.call(this, scene.getEngine(), name);
  47770. // Lens effects can be of the following:
  47771. // - chromatic aberration (slight shift of RGB colors)
  47772. // - blur on the edge of the lens
  47773. // - lens distortion
  47774. // - depth-of-field blur & highlights enhancing
  47775. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47776. // - grain effect (noise or custom texture)
  47777. // Two additional texture samplers are needed:
  47778. // - depth map (for depth-of-field)
  47779. // - grain texture
  47780. /**
  47781. * The chromatic aberration PostProcess id in the pipeline
  47782. * @type {string}
  47783. */
  47784. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47785. /**
  47786. * The highlights enhancing PostProcess id in the pipeline
  47787. * @type {string}
  47788. */
  47789. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47790. /**
  47791. * The depth-of-field PostProcess id in the pipeline
  47792. * @type {string}
  47793. */
  47794. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47795. this._scene = scene;
  47796. // Fetch texture samplers
  47797. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47798. if (parameters.grain_texture) {
  47799. this._grainTexture = parameters.grain_texture;
  47800. }
  47801. else {
  47802. this._createGrainTexture();
  47803. }
  47804. // save parameters
  47805. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47806. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47807. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47808. this._distortion = parameters.distortion ? parameters.distortion : 0;
  47809. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47810. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47811. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47812. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47813. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47814. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47815. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47816. // Create effects
  47817. this._createChromaticAberrationPostProcess(ratio);
  47818. this._createHighlightsPostProcess(ratio);
  47819. this._createDepthOfFieldPostProcess(ratio / 4);
  47820. // Set up pipeline
  47821. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47822. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47823. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47824. if (this._highlightsGain === -1) {
  47825. this._disableEffect(this.HighlightsEnhancingEffect, null);
  47826. }
  47827. // Finish
  47828. scene.postProcessRenderPipelineManager.addPipeline(this);
  47829. if (cameras) {
  47830. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47831. }
  47832. }
  47833. // public methods (self explanatory)
  47834. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47835. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47836. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47837. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47838. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47839. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47840. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47841. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47842. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47843. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47844. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47845. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47846. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47847. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47848. };
  47849. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47850. this._highlightsPostProcess.updateEffect();
  47851. };
  47852. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47853. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47854. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47855. this._highlightsGain = amount;
  47856. };
  47857. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47858. if (this._highlightsGain === -1) {
  47859. this._highlightsGain = 1.0;
  47860. }
  47861. this._highlightsThreshold = amount;
  47862. };
  47863. LensRenderingPipeline.prototype.disableHighlights = function () {
  47864. this._highlightsGain = -1;
  47865. };
  47866. /**
  47867. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47868. */
  47869. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47870. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47871. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47872. this._chromaticAberrationPostProcess = undefined;
  47873. this._highlightsPostProcess = undefined;
  47874. this._depthOfFieldPostProcess = undefined;
  47875. this._grainTexture.dispose();
  47876. if (disableDepthRender)
  47877. this._scene.disableDepthRenderer();
  47878. };
  47879. // colors shifting and distortion
  47880. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47881. var _this = this;
  47882. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47883. [], // samplers
  47884. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47885. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47886. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47887. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47888. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47889. };
  47890. };
  47891. // highlights enhancing
  47892. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47893. var _this = this;
  47894. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47895. [], // samplers
  47896. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47897. this._highlightsPostProcess.onApply = function (effect) {
  47898. effect.setFloat('gain', _this._highlightsGain);
  47899. effect.setFloat('threshold', _this._highlightsThreshold);
  47900. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47901. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47902. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47903. };
  47904. };
  47905. // colors shifting and distortion
  47906. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47907. var _this = this;
  47908. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47909. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47910. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47911. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47912. this._depthOfFieldPostProcess.onApply = function (effect) {
  47913. effect.setTexture("depthSampler", _this._depthTexture);
  47914. effect.setTexture("grainSampler", _this._grainTexture);
  47915. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47916. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47917. effect.setFloat('grain_amount', _this._grainAmount);
  47918. effect.setBool('blur_noise', _this._blurNoise);
  47919. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47920. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47921. effect.setFloat('distortion', _this._distortion);
  47922. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  47923. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  47924. effect.setFloat('aperture', _this._dofAperture);
  47925. effect.setFloat('darken', _this._dofDarken);
  47926. effect.setFloat('edge_blur', _this._edgeBlur);
  47927. effect.setBool('highlights', (_this._highlightsGain !== -1));
  47928. effect.setFloat('near', _this._scene.activeCamera.minZ);
  47929. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  47930. };
  47931. };
  47932. // creates a black and white random noise texture, 512x512
  47933. LensRenderingPipeline.prototype._createGrainTexture = function () {
  47934. var size = 512;
  47935. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47936. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47937. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47938. var context = this._grainTexture.getContext();
  47939. var rand = function (min, max) {
  47940. return Math.random() * (max - min) + min;
  47941. };
  47942. var value;
  47943. for (var x = 0; x < size; x++) {
  47944. for (var y = 0; y < size; y++) {
  47945. value = Math.floor(rand(0.42, 0.58) * 255);
  47946. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  47947. context.fillRect(x, y, 1, 1);
  47948. }
  47949. }
  47950. this._grainTexture.update(false);
  47951. };
  47952. return LensRenderingPipeline;
  47953. }(BABYLON.PostProcessRenderPipeline));
  47954. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  47955. })(BABYLON || (BABYLON = {}));
  47956. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  47957. //
  47958. // This post-process allows the modification of rendered colors by using
  47959. // a 'look-up table' (LUT). This effect is also called Color Grading.
  47960. //
  47961. // The object needs to be provided an url to a texture containing the color
  47962. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  47963. // Use an image editing software to tweak the LUT to match your needs.
  47964. //
  47965. // For an example of a color LUT, see here:
  47966. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  47967. // For explanations on color grading, see here:
  47968. // http://udn.epicgames.com/Three/ColorGrading.html
  47969. //
  47970. var BABYLON;
  47971. (function (BABYLON) {
  47972. var ColorCorrectionPostProcess = (function (_super) {
  47973. __extends(ColorCorrectionPostProcess, _super);
  47974. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  47975. var _this = this;
  47976. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  47977. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47978. this._colorTableTexture.anisotropicFilteringLevel = 1;
  47979. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47980. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47981. this.onApply = function (effect) {
  47982. effect.setTexture("colorTable", _this._colorTableTexture);
  47983. };
  47984. }
  47985. return ColorCorrectionPostProcess;
  47986. }(BABYLON.PostProcess));
  47987. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  47988. })(BABYLON || (BABYLON = {}));
  47989. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  47990. var BABYLON;
  47991. (function (BABYLON) {
  47992. var AnaglyphFreeCamera = (function (_super) {
  47993. __extends(AnaglyphFreeCamera, _super);
  47994. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  47995. _super.call(this, name, position, scene);
  47996. this.interaxialDistance = interaxialDistance;
  47997. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47998. }
  47999. AnaglyphFreeCamera.prototype.getClassName = function () {
  48000. return "AnaglyphFreeCamera";
  48001. };
  48002. return AnaglyphFreeCamera;
  48003. }(BABYLON.FreeCamera));
  48004. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48005. var AnaglyphArcRotateCamera = (function (_super) {
  48006. __extends(AnaglyphArcRotateCamera, _super);
  48007. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48008. _super.call(this, name, alpha, beta, radius, target, scene);
  48009. this.interaxialDistance = interaxialDistance;
  48010. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48011. }
  48012. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  48013. return "AnaglyphArcRotateCamera";
  48014. };
  48015. return AnaglyphArcRotateCamera;
  48016. }(BABYLON.ArcRotateCamera));
  48017. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48018. var AnaglyphGamepadCamera = (function (_super) {
  48019. __extends(AnaglyphGamepadCamera, _super);
  48020. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48021. _super.call(this, name, position, scene);
  48022. this.interaxialDistance = interaxialDistance;
  48023. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48024. }
  48025. AnaglyphGamepadCamera.prototype.getClassName = function () {
  48026. return "AnaglyphGamepadCamera";
  48027. };
  48028. return AnaglyphGamepadCamera;
  48029. }(BABYLON.GamepadCamera));
  48030. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48031. var AnaglyphUniversalCamera = (function (_super) {
  48032. __extends(AnaglyphUniversalCamera, _super);
  48033. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48034. _super.call(this, name, position, scene);
  48035. this.interaxialDistance = interaxialDistance;
  48036. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48037. }
  48038. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48039. return "AnaglyphUniversalCamera";
  48040. };
  48041. return AnaglyphUniversalCamera;
  48042. }(BABYLON.UniversalCamera));
  48043. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48044. var StereoscopicFreeCamera = (function (_super) {
  48045. __extends(StereoscopicFreeCamera, _super);
  48046. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48047. _super.call(this, name, position, scene);
  48048. this.interaxialDistance = interaxialDistance;
  48049. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48050. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48051. }
  48052. StereoscopicFreeCamera.prototype.getClassName = function () {
  48053. return "StereoscopicFreeCamera";
  48054. };
  48055. return StereoscopicFreeCamera;
  48056. }(BABYLON.FreeCamera));
  48057. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48058. var StereoscopicArcRotateCamera = (function (_super) {
  48059. __extends(StereoscopicArcRotateCamera, _super);
  48060. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48061. _super.call(this, name, alpha, beta, radius, target, scene);
  48062. this.interaxialDistance = interaxialDistance;
  48063. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48064. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48065. }
  48066. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48067. return "StereoscopicArcRotateCamera";
  48068. };
  48069. return StereoscopicArcRotateCamera;
  48070. }(BABYLON.ArcRotateCamera));
  48071. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48072. var StereoscopicGamepadCamera = (function (_super) {
  48073. __extends(StereoscopicGamepadCamera, _super);
  48074. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48075. _super.call(this, name, position, scene);
  48076. this.interaxialDistance = interaxialDistance;
  48077. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48078. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48079. }
  48080. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48081. return "StereoscopicGamepadCamera";
  48082. };
  48083. return StereoscopicGamepadCamera;
  48084. }(BABYLON.GamepadCamera));
  48085. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48086. var StereoscopicUniversalCamera = (function (_super) {
  48087. __extends(StereoscopicUniversalCamera, _super);
  48088. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48089. _super.call(this, name, position, scene);
  48090. this.interaxialDistance = interaxialDistance;
  48091. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48092. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48093. }
  48094. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48095. return "StereoscopicUniversalCamera";
  48096. };
  48097. return StereoscopicUniversalCamera;
  48098. }(BABYLON.UniversalCamera));
  48099. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48100. })(BABYLON || (BABYLON = {}));
  48101. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48102. var BABYLON;
  48103. (function (BABYLON) {
  48104. var HDRRenderingPipeline = (function (_super) {
  48105. __extends(HDRRenderingPipeline, _super);
  48106. /**
  48107. * @constructor
  48108. * @param {string} name - The rendering pipeline name
  48109. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48110. * @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)
  48111. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48112. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48113. */
  48114. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48115. var _this = this;
  48116. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48117. _super.call(this, scene.getEngine(), name);
  48118. /**
  48119. * Public members
  48120. */
  48121. // Gaussian Blur
  48122. /**
  48123. * Gaussian blur coefficient
  48124. * @type {number}
  48125. */
  48126. this.gaussCoeff = 0.3;
  48127. /**
  48128. * Gaussian blur mean
  48129. * @type {number}
  48130. */
  48131. this.gaussMean = 1.0;
  48132. /**
  48133. * Gaussian blur standard deviation
  48134. * @type {number}
  48135. */
  48136. this.gaussStandDev = 0.8;
  48137. /**
  48138. * Gaussian blur multiplier. Multiplies the blur effect
  48139. * @type {number}
  48140. */
  48141. this.gaussMultiplier = 4.0;
  48142. // HDR
  48143. /**
  48144. * Exposure, controls the overall intensity of the pipeline
  48145. * @type {number}
  48146. */
  48147. this.exposure = 1.0;
  48148. /**
  48149. * Minimum luminance that the post-process can output. Luminance is >= 0
  48150. * @type {number}
  48151. */
  48152. this.minimumLuminance = 1.0;
  48153. /**
  48154. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48155. * @type {number}
  48156. */
  48157. this.maximumLuminance = 1e20;
  48158. /**
  48159. * Increase rate for luminance: eye adaptation speed to dark
  48160. * @type {number}
  48161. */
  48162. this.luminanceIncreaserate = 0.5;
  48163. /**
  48164. * Decrease rate for luminance: eye adaptation speed to bright
  48165. * @type {number}
  48166. */
  48167. this.luminanceDecreaseRate = 0.5;
  48168. // Bright pass
  48169. /**
  48170. * Minimum luminance needed to compute HDR
  48171. * @type {number}
  48172. */
  48173. this.brightThreshold = 0.8;
  48174. this._needUpdate = true;
  48175. this._scene = scene;
  48176. // Bright pass
  48177. this._createBrightPassPostProcess(scene, ratio);
  48178. // Down sample X4
  48179. this._createDownSampleX4PostProcess(scene, ratio);
  48180. // Create gaussian blur post-processes
  48181. this._createGaussianBlurPostProcess(scene, ratio);
  48182. // Texture adder
  48183. this._createTextureAdderPostProcess(scene, ratio);
  48184. // Luminance generator
  48185. this._createLuminanceGeneratorPostProcess(scene);
  48186. // HDR
  48187. this._createHDRPostProcess(scene, ratio);
  48188. // Pass postprocess
  48189. if (originalPostProcess === null) {
  48190. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48191. }
  48192. else {
  48193. this._originalPostProcess = originalPostProcess;
  48194. }
  48195. // Configure pipeline
  48196. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48199. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48200. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48201. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48202. var addDownSamplerPostProcess = function (id) {
  48203. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48204. };
  48205. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48206. addDownSamplerPostProcess(i);
  48207. }
  48208. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48209. // Finish
  48210. scene.postProcessRenderPipelineManager.addPipeline(this);
  48211. if (cameras !== null) {
  48212. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48213. }
  48214. this.update();
  48215. }
  48216. /**
  48217. * Tells the pipeline to update its post-processes
  48218. */
  48219. HDRRenderingPipeline.prototype.update = function () {
  48220. this._needUpdate = true;
  48221. };
  48222. /**
  48223. * Returns the current calculated luminance
  48224. */
  48225. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48226. return this._hdrCurrentLuminance;
  48227. };
  48228. /**
  48229. * Returns the currently drawn luminance
  48230. */
  48231. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48232. return this._hdrOutputLuminance;
  48233. };
  48234. /**
  48235. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48236. */
  48237. HDRRenderingPipeline.prototype.dispose = function () {
  48238. this._originalPostProcess = undefined;
  48239. this._brightPassPostProcess = undefined;
  48240. this._downSampleX4PostProcess = undefined;
  48241. this._guassianBlurHPostProcess = undefined;
  48242. this._guassianBlurVPostProcess = undefined;
  48243. this._textureAdderPostProcess = undefined;
  48244. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48245. this._downSamplePostProcesses[i] = undefined;
  48246. }
  48247. this._hdrPostProcess = undefined;
  48248. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48249. };
  48250. /**
  48251. * Creates the HDR post-process and computes the luminance adaptation
  48252. */
  48253. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  48254. var _this = this;
  48255. var hdrLastLuminance = 0.0;
  48256. this._hdrOutputLuminance = -1.0;
  48257. this._hdrCurrentLuminance = 1.0;
  48258. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  48259. this._hdrPostProcess.onApply = function (effect) {
  48260. if (_this._hdrOutputLuminance < 0.0) {
  48261. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48262. }
  48263. else {
  48264. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  48265. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  48266. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  48267. }
  48268. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  48269. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  48270. }
  48271. else {
  48272. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48273. }
  48274. }
  48275. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  48276. hdrLastLuminance += scene.getEngine().getDeltaTime();
  48277. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48278. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48279. effect.setFloat("exposure", _this.exposure);
  48280. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  48281. _this._needUpdate = false;
  48282. };
  48283. };
  48284. /**
  48285. * Texture Adder post-process
  48286. */
  48287. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48288. var _this = this;
  48289. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  48290. this._textureAdderPostProcess.onApply = function (effect) {
  48291. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48292. };
  48293. };
  48294. /**
  48295. * Down sample X4 post-process
  48296. */
  48297. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48298. var _this = this;
  48299. var downSampleX4Offsets = new Array(32);
  48300. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  48301. this._downSampleX4PostProcess.onApply = function (effect) {
  48302. if (_this._needUpdate) {
  48303. var id = 0;
  48304. for (var i = -2; i < 2; i++) {
  48305. for (var j = -2; j < 2; j++) {
  48306. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  48307. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  48308. id += 2;
  48309. }
  48310. }
  48311. }
  48312. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48313. };
  48314. };
  48315. /**
  48316. * Bright pass post-process
  48317. */
  48318. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48319. var _this = this;
  48320. var brightOffsets = new Array(8);
  48321. var brightPassCallback = function (effect) {
  48322. if (_this._needUpdate) {
  48323. var sU = (1.0 / _this._brightPassPostProcess.width);
  48324. var sV = (1.0 / _this._brightPassPostProcess.height);
  48325. brightOffsets[0] = -0.5 * sU;
  48326. brightOffsets[1] = 0.5 * sV;
  48327. brightOffsets[2] = 0.5 * sU;
  48328. brightOffsets[3] = 0.5 * sV;
  48329. brightOffsets[4] = -0.5 * sU;
  48330. brightOffsets[5] = -0.5 * sV;
  48331. brightOffsets[6] = 0.5 * sU;
  48332. brightOffsets[7] = -0.5 * sV;
  48333. }
  48334. effect.setArray2("dsOffsets", brightOffsets);
  48335. effect.setFloat("brightThreshold", _this.brightThreshold);
  48336. };
  48337. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  48338. this._brightPassPostProcess.onApply = brightPassCallback;
  48339. };
  48340. /**
  48341. * Luminance generator. Creates the luminance post-process and down sample post-processes
  48342. */
  48343. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  48344. var _this = this;
  48345. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  48346. var luminanceOffsets = new Array(8);
  48347. var downSampleOffsets = new Array(18);
  48348. var halfDestPixelSize;
  48349. this._downSamplePostProcesses = new Array(lumSteps);
  48350. // Utils for luminance
  48351. var luminanceUpdateSourceOffsets = function (width, height) {
  48352. var sU = (1.0 / width);
  48353. var sV = (1.0 / height);
  48354. luminanceOffsets[0] = -0.5 * sU;
  48355. luminanceOffsets[1] = 0.5 * sV;
  48356. luminanceOffsets[2] = 0.5 * sU;
  48357. luminanceOffsets[3] = 0.5 * sV;
  48358. luminanceOffsets[4] = -0.5 * sU;
  48359. luminanceOffsets[5] = -0.5 * sV;
  48360. luminanceOffsets[6] = 0.5 * sU;
  48361. luminanceOffsets[7] = -0.5 * sV;
  48362. };
  48363. var luminanceUpdateDestOffsets = function (width, height) {
  48364. var id = 0;
  48365. for (var x = -1; x < 2; x++) {
  48366. for (var y = -1; y < 2; y++) {
  48367. downSampleOffsets[id] = (x) / width;
  48368. downSampleOffsets[id + 1] = (y) / height;
  48369. id += 2;
  48370. }
  48371. }
  48372. };
  48373. // Luminance callback
  48374. var luminanceCallback = function (effect) {
  48375. if (_this._needUpdate) {
  48376. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  48377. }
  48378. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48379. effect.setArray2("lumOffsets", luminanceOffsets);
  48380. };
  48381. // Down sample callbacks
  48382. var downSampleCallback = function (indice) {
  48383. var i = indice;
  48384. return function (effect) {
  48385. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48386. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48387. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  48388. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  48389. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  48390. effect.setArray2("dsOffsets", downSampleOffsets);
  48391. };
  48392. };
  48393. var downSampleAfterRenderCallback = function (effect) {
  48394. // Unpack result
  48395. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48396. 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);
  48397. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48398. };
  48399. // Create luminance post-process
  48400. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  48401. 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);
  48402. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  48403. // Create down sample post-processes
  48404. for (var i = lumSteps - 2; i >= 0; i--) {
  48405. var length = Math.pow(3, i);
  48406. ratio = { width: length, height: length };
  48407. var defines = "#define DOWN_SAMPLE\n";
  48408. if (i === 0) {
  48409. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  48410. }
  48411. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48412. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  48413. if (i === 0) {
  48414. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  48415. }
  48416. }
  48417. };
  48418. /**
  48419. * Gaussian blur post-processes. Horizontal and Vertical
  48420. */
  48421. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  48422. var _this = this;
  48423. var blurOffsetsW = new Array(9);
  48424. var blurOffsetsH = new Array(9);
  48425. var blurWeights = new Array(9);
  48426. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  48427. // Utils for gaussian blur
  48428. var calculateBlurOffsets = function (height) {
  48429. var lastOutputDimensions = {
  48430. width: scene.getEngine().getRenderWidth(),
  48431. height: scene.getEngine().getRenderHeight()
  48432. };
  48433. for (var i = 0; i < 9; i++) {
  48434. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48435. if (height) {
  48436. blurOffsetsH[i] = value;
  48437. }
  48438. else {
  48439. blurOffsetsW[i] = value;
  48440. }
  48441. }
  48442. };
  48443. var calculateWeights = function () {
  48444. var x = 0.0;
  48445. for (var i = 0; i < 9; i++) {
  48446. x = (i - 4.0) / 4.0;
  48447. 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));
  48448. }
  48449. };
  48450. // Callback
  48451. var gaussianBlurCallback = function (height) {
  48452. return function (effect) {
  48453. if (_this._needUpdate) {
  48454. calculateWeights();
  48455. calculateBlurOffsets(height);
  48456. }
  48457. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  48458. effect.setArray("blurWeights", blurWeights);
  48459. effect.setFloat("multiplier", _this.gaussMultiplier);
  48460. };
  48461. };
  48462. // Create horizontal gaussian blur post-processes
  48463. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  48464. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  48465. // Create vertical gaussian blur post-process
  48466. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  48467. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  48468. };
  48469. // Luminance generator
  48470. HDRRenderingPipeline.LUM_STEPS = 6;
  48471. return HDRRenderingPipeline;
  48472. }(BABYLON.PostProcessRenderPipeline));
  48473. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  48474. })(BABYLON || (BABYLON = {}));
  48475. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  48476. var BABYLON;
  48477. (function (BABYLON) {
  48478. var FaceAdjacencies = (function () {
  48479. function FaceAdjacencies() {
  48480. this.edges = new Array();
  48481. this.edgesConnectedCount = 0;
  48482. }
  48483. return FaceAdjacencies;
  48484. }());
  48485. var EdgesRenderer = (function () {
  48486. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  48487. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  48488. if (epsilon === void 0) { epsilon = 0.95; }
  48489. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  48490. this.edgesWidthScalerForOrthographic = 1000.0;
  48491. this.edgesWidthScalerForPerspective = 50.0;
  48492. this._linesPositions = new Array();
  48493. this._linesNormals = new Array();
  48494. this._linesIndices = new Array();
  48495. this._buffers = {};
  48496. this._checkVerticesInsteadOfIndices = false;
  48497. this._source = source;
  48498. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  48499. this._epsilon = epsilon;
  48500. this._prepareRessources();
  48501. this._generateEdgesLines();
  48502. }
  48503. EdgesRenderer.prototype._prepareRessources = function () {
  48504. if (this._lineShader) {
  48505. return;
  48506. }
  48507. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  48508. attributes: ["position", "normal"],
  48509. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  48510. });
  48511. this._lineShader.disableDepthWrite = true;
  48512. this._lineShader.backFaceCulling = false;
  48513. };
  48514. EdgesRenderer.prototype.dispose = function () {
  48515. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  48516. if (buffer) {
  48517. buffer.dispose();
  48518. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  48519. }
  48520. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  48521. if (buffer) {
  48522. buffer.dispose();
  48523. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  48524. }
  48525. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  48526. this._lineShader.dispose();
  48527. };
  48528. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  48529. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  48530. return 0;
  48531. }
  48532. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  48533. return 1;
  48534. }
  48535. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  48536. return 2;
  48537. }
  48538. return -1;
  48539. };
  48540. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  48541. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  48542. return 0;
  48543. }
  48544. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  48545. return 1;
  48546. }
  48547. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  48548. return 2;
  48549. }
  48550. return -1;
  48551. };
  48552. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  48553. var needToCreateLine;
  48554. if (edge === undefined) {
  48555. needToCreateLine = true;
  48556. }
  48557. else {
  48558. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  48559. needToCreateLine = dotProduct < this._epsilon;
  48560. }
  48561. if (needToCreateLine) {
  48562. var offset = this._linesPositions.length / 3;
  48563. var normal = p0.subtract(p1);
  48564. normal.normalize();
  48565. // Positions
  48566. this._linesPositions.push(p0.x);
  48567. this._linesPositions.push(p0.y);
  48568. this._linesPositions.push(p0.z);
  48569. this._linesPositions.push(p0.x);
  48570. this._linesPositions.push(p0.y);
  48571. this._linesPositions.push(p0.z);
  48572. this._linesPositions.push(p1.x);
  48573. this._linesPositions.push(p1.y);
  48574. this._linesPositions.push(p1.z);
  48575. this._linesPositions.push(p1.x);
  48576. this._linesPositions.push(p1.y);
  48577. this._linesPositions.push(p1.z);
  48578. // Normals
  48579. this._linesNormals.push(p1.x);
  48580. this._linesNormals.push(p1.y);
  48581. this._linesNormals.push(p1.z);
  48582. this._linesNormals.push(-1);
  48583. this._linesNormals.push(p1.x);
  48584. this._linesNormals.push(p1.y);
  48585. this._linesNormals.push(p1.z);
  48586. this._linesNormals.push(1);
  48587. this._linesNormals.push(p0.x);
  48588. this._linesNormals.push(p0.y);
  48589. this._linesNormals.push(p0.z);
  48590. this._linesNormals.push(-1);
  48591. this._linesNormals.push(p0.x);
  48592. this._linesNormals.push(p0.y);
  48593. this._linesNormals.push(p0.z);
  48594. this._linesNormals.push(1);
  48595. // Indices
  48596. this._linesIndices.push(offset);
  48597. this._linesIndices.push(offset + 1);
  48598. this._linesIndices.push(offset + 2);
  48599. this._linesIndices.push(offset);
  48600. this._linesIndices.push(offset + 2);
  48601. this._linesIndices.push(offset + 3);
  48602. }
  48603. };
  48604. EdgesRenderer.prototype._generateEdgesLines = function () {
  48605. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48606. var indices = this._source.getIndices();
  48607. // First let's find adjacencies
  48608. var adjacencies = new Array();
  48609. var faceNormals = new Array();
  48610. var index;
  48611. var faceAdjacencies;
  48612. // Prepare faces
  48613. for (index = 0; index < indices.length; index += 3) {
  48614. faceAdjacencies = new FaceAdjacencies();
  48615. var p0Index = indices[index];
  48616. var p1Index = indices[index + 1];
  48617. var p2Index = indices[index + 2];
  48618. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  48619. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  48620. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  48621. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  48622. faceNormal.normalize();
  48623. faceNormals.push(faceNormal);
  48624. adjacencies.push(faceAdjacencies);
  48625. }
  48626. // Scan
  48627. for (index = 0; index < adjacencies.length; index++) {
  48628. faceAdjacencies = adjacencies[index];
  48629. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  48630. var otherFaceAdjacencies = adjacencies[otherIndex];
  48631. if (faceAdjacencies.edgesConnectedCount === 3) {
  48632. break;
  48633. }
  48634. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  48635. continue;
  48636. }
  48637. var otherP0 = indices[otherIndex * 3];
  48638. var otherP1 = indices[otherIndex * 3 + 1];
  48639. var otherP2 = indices[otherIndex * 3 + 2];
  48640. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  48641. var otherEdgeIndex;
  48642. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  48643. continue;
  48644. }
  48645. switch (edgeIndex) {
  48646. case 0:
  48647. if (this._checkVerticesInsteadOfIndices) {
  48648. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48649. }
  48650. else {
  48651. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  48652. }
  48653. break;
  48654. case 1:
  48655. if (this._checkVerticesInsteadOfIndices) {
  48656. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48657. }
  48658. else {
  48659. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  48660. }
  48661. break;
  48662. case 2:
  48663. if (this._checkVerticesInsteadOfIndices) {
  48664. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48665. }
  48666. else {
  48667. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  48668. }
  48669. break;
  48670. }
  48671. if (otherEdgeIndex === -1) {
  48672. continue;
  48673. }
  48674. faceAdjacencies.edges[edgeIndex] = otherIndex;
  48675. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  48676. faceAdjacencies.edgesConnectedCount++;
  48677. otherFaceAdjacencies.edgesConnectedCount++;
  48678. if (faceAdjacencies.edgesConnectedCount === 3) {
  48679. break;
  48680. }
  48681. }
  48682. }
  48683. }
  48684. // Create lines
  48685. for (index = 0; index < adjacencies.length; index++) {
  48686. // 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
  48687. var current = adjacencies[index];
  48688. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  48689. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  48690. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  48691. }
  48692. // Merge into a single mesh
  48693. var engine = this._source.getScene().getEngine();
  48694. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  48695. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  48696. this._ib = engine.createIndexBuffer(this._linesIndices);
  48697. this._indicesCount = this._linesIndices.length;
  48698. };
  48699. EdgesRenderer.prototype.render = function () {
  48700. if (!this._lineShader.isReady()) {
  48701. return;
  48702. }
  48703. var scene = this._source.getScene();
  48704. var engine = scene.getEngine();
  48705. this._lineShader._preBind();
  48706. // VBOs
  48707. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  48708. scene.resetCachedMaterial();
  48709. this._lineShader.setColor4("color", this._source.edgesColor);
  48710. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  48711. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  48712. }
  48713. else {
  48714. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  48715. }
  48716. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  48717. this._lineShader.bind(this._source.getWorldMatrix());
  48718. // Draw order
  48719. engine.draw(true, 0, this._indicesCount);
  48720. this._lineShader.unbind();
  48721. engine.setDepthWrite(true);
  48722. };
  48723. return EdgesRenderer;
  48724. }());
  48725. BABYLON.EdgesRenderer = EdgesRenderer;
  48726. })(BABYLON || (BABYLON = {}));
  48727. //# sourceMappingURL=babylon.edgesRenderer.js.map
  48728. var BABYLON;
  48729. (function (BABYLON) {
  48730. (function (TonemappingOperator) {
  48731. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48732. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48733. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48734. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48735. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48736. var TonemappingOperator = BABYLON.TonemappingOperator;
  48737. ;
  48738. var TonemapPostProcess = (function (_super) {
  48739. __extends(TonemapPostProcess, _super);
  48740. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48741. var _this = this;
  48742. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48743. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48744. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  48745. this._operator = _operator;
  48746. this.exposureAdjustment = exposureAdjustment;
  48747. var defines = "#define ";
  48748. if (this._operator === TonemappingOperator.Hable)
  48749. defines += "HABLE_TONEMAPPING";
  48750. else if (this._operator === TonemappingOperator.Reinhard)
  48751. defines += "REINHARD_TONEMAPPING";
  48752. else if (this._operator === TonemappingOperator.HejiDawson)
  48753. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48754. else if (this._operator === TonemappingOperator.Photographic)
  48755. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48756. //sadly a second call to create the effect.
  48757. this.updateEffect(defines);
  48758. this.onApply = function (effect) {
  48759. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48760. };
  48761. }
  48762. return TonemapPostProcess;
  48763. }(BABYLON.PostProcess));
  48764. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48765. })(BABYLON || (BABYLON = {}));
  48766. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48767. var BABYLON;
  48768. (function (BABYLON) {
  48769. var ReflectionProbe = (function () {
  48770. function ReflectionProbe(name, size, scene, generateMipMaps) {
  48771. var _this = this;
  48772. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48773. this.name = name;
  48774. this._viewMatrix = BABYLON.Matrix.Identity();
  48775. this._target = BABYLON.Vector3.Zero();
  48776. this._add = BABYLON.Vector3.Zero();
  48777. this.invertYAxis = false;
  48778. this.position = BABYLON.Vector3.Zero();
  48779. this._scene = scene;
  48780. this._scene.reflectionProbes.push(this);
  48781. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  48782. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  48783. switch (faceIndex) {
  48784. case 0:
  48785. _this._add.copyFromFloats(1, 0, 0);
  48786. break;
  48787. case 1:
  48788. _this._add.copyFromFloats(-1, 0, 0);
  48789. break;
  48790. case 2:
  48791. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  48792. break;
  48793. case 3:
  48794. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  48795. break;
  48796. case 4:
  48797. _this._add.copyFromFloats(0, 0, 1);
  48798. break;
  48799. case 5:
  48800. _this._add.copyFromFloats(0, 0, -1);
  48801. break;
  48802. }
  48803. if (_this._attachedMesh) {
  48804. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  48805. }
  48806. _this.position.addToRef(_this._add, _this._target);
  48807. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  48808. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  48809. });
  48810. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  48811. scene.updateTransformMatrix(true);
  48812. });
  48813. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  48814. }
  48815. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  48816. get: function () {
  48817. return this._renderTargetTexture.refreshRate;
  48818. },
  48819. set: function (value) {
  48820. this._renderTargetTexture.refreshRate = value;
  48821. },
  48822. enumerable: true,
  48823. configurable: true
  48824. });
  48825. ReflectionProbe.prototype.getScene = function () {
  48826. return this._scene;
  48827. };
  48828. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  48829. get: function () {
  48830. return this._renderTargetTexture;
  48831. },
  48832. enumerable: true,
  48833. configurable: true
  48834. });
  48835. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  48836. get: function () {
  48837. return this._renderTargetTexture.renderList;
  48838. },
  48839. enumerable: true,
  48840. configurable: true
  48841. });
  48842. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  48843. this._attachedMesh = mesh;
  48844. };
  48845. ReflectionProbe.prototype.dispose = function () {
  48846. var index = this._scene.reflectionProbes.indexOf(this);
  48847. if (index !== -1) {
  48848. // Remove from the scene if found
  48849. this._scene.reflectionProbes.splice(index, 1);
  48850. }
  48851. if (this._renderTargetTexture) {
  48852. this._renderTargetTexture.dispose();
  48853. this._renderTargetTexture = null;
  48854. }
  48855. };
  48856. return ReflectionProbe;
  48857. }());
  48858. BABYLON.ReflectionProbe = ReflectionProbe;
  48859. })(BABYLON || (BABYLON = {}));
  48860. //# sourceMappingURL=babylon.reflectionProbe.js.map
  48861. var BABYLON;
  48862. (function (BABYLON) {
  48863. var SolidParticle = (function () {
  48864. /**
  48865. * Creates a Solid Particle object.
  48866. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48867. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48868. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48869. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  48870. * `shapeId` (integer) is the model shape identifier in the SPS.
  48871. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48872. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  48873. */
  48874. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48875. this.idx = 0; // particle global index
  48876. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  48877. this.position = BABYLON.Vector3.Zero(); // position
  48878. this.rotation = BABYLON.Vector3.Zero(); // rotation
  48879. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  48880. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  48881. this.velocity = BABYLON.Vector3.Zero(); // velocity
  48882. this.alive = true; // alive
  48883. this.isVisible = true; // visibility
  48884. this._pos = 0; // index of this particle in the global "positions" array
  48885. this.shapeId = 0; // model shape id
  48886. this.idxInShape = 0; // index of the particle in its shape id
  48887. this.idx = particleIndex;
  48888. this._pos = positionIndex;
  48889. this._model = model;
  48890. this.shapeId = shapeId;
  48891. this.idxInShape = idxInShape;
  48892. this._sps = sps;
  48893. if (modelBoundingInfo) {
  48894. this._modelBoundingInfo = modelBoundingInfo;
  48895. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48896. }
  48897. }
  48898. Object.defineProperty(SolidParticle.prototype, "scale", {
  48899. /**
  48900. * legacy support, changed scale to scaling
  48901. */
  48902. get: function () {
  48903. return this.scaling;
  48904. },
  48905. set: function (scale) {
  48906. this.scaling = scale;
  48907. },
  48908. enumerable: true,
  48909. configurable: true
  48910. });
  48911. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48912. /**
  48913. * legacy support, changed quaternion to rotationQuaternion
  48914. */
  48915. get: function () {
  48916. return this.rotationQuaternion;
  48917. },
  48918. set: function (q) {
  48919. this.rotationQuaternion = q;
  48920. },
  48921. enumerable: true,
  48922. configurable: true
  48923. });
  48924. /**
  48925. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48926. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48927. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  48928. */
  48929. SolidParticle.prototype.intersectsMesh = function (target) {
  48930. if (!this._boundingInfo || !target._boundingInfo) {
  48931. return false;
  48932. }
  48933. if (this._sps._bSphereOnly) {
  48934. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48935. }
  48936. return this._boundingInfo.intersects(target._boundingInfo, false);
  48937. };
  48938. return SolidParticle;
  48939. }());
  48940. BABYLON.SolidParticle = SolidParticle;
  48941. var ModelShape = (function () {
  48942. /**
  48943. * 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.
  48944. * SPS internal tool, don't use it manually.
  48945. */
  48946. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  48947. this.shapeID = id;
  48948. this._shape = shape;
  48949. this._shapeUV = shapeUV;
  48950. this._positionFunction = posFunction;
  48951. this._vertexFunction = vtxFunction;
  48952. }
  48953. return ModelShape;
  48954. }());
  48955. BABYLON.ModelShape = ModelShape;
  48956. })(BABYLON || (BABYLON = {}));
  48957. //# sourceMappingURL=babylon.solidParticle.js.map
  48958. var BABYLON;
  48959. (function (BABYLON) {
  48960. /**
  48961. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  48962. */
  48963. var SolidParticleSystem = (function () {
  48964. /**
  48965. * Creates a SPS (Solid Particle System) object.
  48966. * `name` (String) is the SPS name, this will be the underlying mesh name.
  48967. * `scene` (Scene) is the scene in which the SPS is added.
  48968. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  48969. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  48970. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  48971. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  48972. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  48973. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  48974. */
  48975. function SolidParticleSystem(name, scene, options) {
  48976. // public members
  48977. /**
  48978. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  48979. * Example : var p = SPS.particles[i];
  48980. */
  48981. this.particles = new Array();
  48982. /**
  48983. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  48984. */
  48985. this.nbParticles = 0;
  48986. /**
  48987. * If the particles must ever face the camera (default false). Useful for planar particles.
  48988. */
  48989. this.billboard = false;
  48990. /**
  48991. * Recompute normals when adding a shape
  48992. */
  48993. this.recomputeNormals = true;
  48994. /**
  48995. * This a counter ofr your own usage. It's not set by any SPS functions.
  48996. */
  48997. this.counter = 0;
  48998. /**
  48999. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49000. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49001. */
  49002. this.vars = {};
  49003. this._positions = new Array();
  49004. this._indices = new Array();
  49005. this._normals = new Array();
  49006. this._colors = new Array();
  49007. this._uvs = new Array();
  49008. this._index = 0; // indices index
  49009. this._updatable = true;
  49010. this._pickable = false;
  49011. this._isVisibilityBoxLocked = false;
  49012. this._alwaysVisible = false;
  49013. this._shapeCounter = 0;
  49014. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  49015. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49016. this._computeParticleColor = true;
  49017. this._computeParticleTexture = true;
  49018. this._computeParticleRotation = true;
  49019. this._computeParticleVertex = false;
  49020. this._computeBoundingBox = false;
  49021. this._cam_axisZ = BABYLON.Vector3.Zero();
  49022. this._cam_axisY = BABYLON.Vector3.Zero();
  49023. this._cam_axisX = BABYLON.Vector3.Zero();
  49024. this._axisX = BABYLON.Axis.X;
  49025. this._axisY = BABYLON.Axis.Y;
  49026. this._axisZ = BABYLON.Axis.Z;
  49027. this._camDir = BABYLON.Vector3.Zero();
  49028. this._rotMatrix = new BABYLON.Matrix();
  49029. this._invertMatrix = new BABYLON.Matrix();
  49030. this._rotated = BABYLON.Vector3.Zero();
  49031. this._quaternion = new BABYLON.Quaternion();
  49032. this._vertex = BABYLON.Vector3.Zero();
  49033. this._normal = BABYLON.Vector3.Zero();
  49034. this._yaw = 0.0;
  49035. this._pitch = 0.0;
  49036. this._roll = 0.0;
  49037. this._halfroll = 0.0;
  49038. this._halfpitch = 0.0;
  49039. this._halfyaw = 0.0;
  49040. this._sinRoll = 0.0;
  49041. this._cosRoll = 0.0;
  49042. this._sinPitch = 0.0;
  49043. this._cosPitch = 0.0;
  49044. this._sinYaw = 0.0;
  49045. this._cosYaw = 0.0;
  49046. this._w = 0.0;
  49047. this._minimum = BABYLON.Tmp.Vector3[0];
  49048. this._maximum = BABYLON.Tmp.Vector3[1];
  49049. this._scale = BABYLON.Tmp.Vector3[2];
  49050. this._translation = BABYLON.Tmp.Vector3[3];
  49051. this._minBbox = BABYLON.Tmp.Vector3[4];
  49052. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49053. this._particlesIntersect = false;
  49054. this._bSphereOnly = false;
  49055. this._bSphereRadiusFactor = 1.0;
  49056. this.name = name;
  49057. this._scene = scene;
  49058. this._camera = scene.activeCamera;
  49059. this._pickable = options ? options.isPickable : false;
  49060. this._particlesIntersect = options ? options.particleIntersection : false;
  49061. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49062. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49063. if (options && options.updatable) {
  49064. this._updatable = options.updatable;
  49065. }
  49066. else {
  49067. this._updatable = true;
  49068. }
  49069. if (this._pickable) {
  49070. this.pickedParticles = [];
  49071. }
  49072. }
  49073. /**
  49074. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49075. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49076. */
  49077. SolidParticleSystem.prototype.buildMesh = function () {
  49078. if (this.nbParticles === 0) {
  49079. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49080. this.addShape(triangle, 1);
  49081. triangle.dispose();
  49082. }
  49083. this._positions32 = new Float32Array(this._positions);
  49084. this._uvs32 = new Float32Array(this._uvs);
  49085. this._colors32 = new Float32Array(this._colors);
  49086. if (this.recomputeNormals) {
  49087. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49088. }
  49089. this._normals32 = new Float32Array(this._normals);
  49090. this._fixedNormal32 = new Float32Array(this._normals);
  49091. var vertexData = new BABYLON.VertexData();
  49092. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49093. vertexData.indices = this._indices;
  49094. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49095. if (this._uvs32) {
  49096. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49097. ;
  49098. }
  49099. if (this._colors32) {
  49100. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49101. }
  49102. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49103. vertexData.applyToMesh(mesh, this._updatable);
  49104. this.mesh = mesh;
  49105. this.mesh.isPickable = this._pickable;
  49106. // free memory
  49107. this._positions = null;
  49108. this._normals = null;
  49109. this._uvs = null;
  49110. this._colors = null;
  49111. if (!this._updatable) {
  49112. this.particles.length = 0;
  49113. }
  49114. return mesh;
  49115. };
  49116. /**
  49117. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49118. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49119. * Thus the particles generated from `digest()` have their property `position` set yet.
  49120. * `mesh` ( Mesh ) is the mesh to be digested
  49121. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49122. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49123. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49124. */
  49125. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49126. var size = (options && options.facetNb) || 1;
  49127. var number = (options && options.number);
  49128. var delta = (options && options.delta) || 0;
  49129. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49130. var meshInd = mesh.getIndices();
  49131. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49132. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49133. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49134. var f = 0; // facet counter
  49135. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49136. // compute size from number
  49137. if (number) {
  49138. number = (number > totalFacets) ? totalFacets : number;
  49139. size = Math.round(totalFacets / number);
  49140. delta = 0;
  49141. }
  49142. else {
  49143. size = (size > totalFacets) ? totalFacets : size;
  49144. }
  49145. var facetPos = []; // submesh positions
  49146. var facetInd = []; // submesh indices
  49147. var facetUV = []; // submesh UV
  49148. var facetCol = []; // submesh colors
  49149. var barycenter = BABYLON.Tmp.Vector3[0];
  49150. var rand;
  49151. var sizeO = size;
  49152. while (f < totalFacets) {
  49153. size = sizeO + Math.floor((1 + delta) * Math.random());
  49154. if (f > totalFacets - size) {
  49155. size = totalFacets - f;
  49156. }
  49157. // reset temp arrays
  49158. facetPos.length = 0;
  49159. facetInd.length = 0;
  49160. facetUV.length = 0;
  49161. facetCol.length = 0;
  49162. // iterate over "size" facets
  49163. var fi = 0;
  49164. for (var j = f * 3; j < (f + size) * 3; j++) {
  49165. facetInd.push(fi);
  49166. var i = meshInd[j];
  49167. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49168. if (meshUV) {
  49169. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49170. }
  49171. if (meshCol) {
  49172. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49173. }
  49174. fi++;
  49175. }
  49176. // create a model shape for each single particle
  49177. var idx = this.nbParticles;
  49178. var shape = this._posToShape(facetPos);
  49179. var shapeUV = this._uvsToShapeUV(facetUV);
  49180. // compute the barycenter of the shape
  49181. var v;
  49182. for (v = 0; v < shape.length; v++) {
  49183. barycenter.addInPlace(shape[v]);
  49184. }
  49185. barycenter.scaleInPlace(1 / shape.length);
  49186. // shift the shape from its barycenter to the origin
  49187. for (v = 0; v < shape.length; v++) {
  49188. shape[v].subtractInPlace(barycenter);
  49189. }
  49190. var bInfo;
  49191. if (this._particlesIntersect) {
  49192. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49193. }
  49194. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49195. // add the particle in the SPS
  49196. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49197. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49198. // initialize the particle position
  49199. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49200. this._index += shape.length;
  49201. idx++;
  49202. this.nbParticles++;
  49203. this._shapeCounter++;
  49204. f += size;
  49205. }
  49206. return this;
  49207. };
  49208. //reset copy
  49209. SolidParticleSystem.prototype._resetCopy = function () {
  49210. this._copy.position.x = 0;
  49211. this._copy.position.y = 0;
  49212. this._copy.position.z = 0;
  49213. this._copy.rotation.x = 0;
  49214. this._copy.rotation.y = 0;
  49215. this._copy.rotation.z = 0;
  49216. this._copy.rotationQuaternion = null;
  49217. this._copy.scaling.x = 1;
  49218. this._copy.scaling.y = 1;
  49219. this._copy.scaling.z = 1;
  49220. this._copy.uvs.x = 0;
  49221. this._copy.uvs.y = 0;
  49222. this._copy.uvs.z = 1;
  49223. this._copy.uvs.w = 1;
  49224. this._copy.color = null;
  49225. };
  49226. // _meshBuilder : inserts the shape model in the global SPS mesh
  49227. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49228. var i;
  49229. var u = 0;
  49230. var c = 0;
  49231. var n = 0;
  49232. this._resetCopy();
  49233. if (options && options.positionFunction) {
  49234. options.positionFunction(this._copy, idx, idxInShape);
  49235. }
  49236. if (this._copy.rotationQuaternion) {
  49237. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49238. }
  49239. else {
  49240. this._yaw = this._copy.rotation.y;
  49241. this._pitch = this._copy.rotation.x;
  49242. this._roll = this._copy.rotation.z;
  49243. this._quaternionRotationYPR();
  49244. }
  49245. this._quaternionToRotationMatrix();
  49246. for (i = 0; i < shape.length; i++) {
  49247. this._vertex.x = shape[i].x;
  49248. this._vertex.y = shape[i].y;
  49249. this._vertex.z = shape[i].z;
  49250. if (options && options.vertexFunction) {
  49251. options.vertexFunction(this._copy, this._vertex, i);
  49252. }
  49253. this._vertex.x *= this._copy.scaling.x;
  49254. this._vertex.y *= this._copy.scaling.y;
  49255. this._vertex.z *= this._copy.scaling.z;
  49256. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49257. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49258. if (meshUV) {
  49259. 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);
  49260. u += 2;
  49261. }
  49262. if (this._copy.color) {
  49263. this._color = this._copy.color;
  49264. }
  49265. else if (meshCol && meshCol[c] !== undefined) {
  49266. this._color.r = meshCol[c];
  49267. this._color.g = meshCol[c + 1];
  49268. this._color.b = meshCol[c + 2];
  49269. this._color.a = meshCol[c + 3];
  49270. }
  49271. else {
  49272. this._color.r = 1;
  49273. this._color.g = 1;
  49274. this._color.b = 1;
  49275. this._color.a = 1;
  49276. }
  49277. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49278. c += 4;
  49279. if (!this.recomputeNormals && meshNor) {
  49280. this._normal.x = meshNor[n];
  49281. this._normal.y = meshNor[n + 1];
  49282. this._normal.z = meshNor[n + 2];
  49283. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  49284. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49285. n += 3;
  49286. }
  49287. }
  49288. for (i = 0; i < meshInd.length; i++) {
  49289. indices.push(p + meshInd[i]);
  49290. }
  49291. if (this._pickable) {
  49292. var nbfaces = meshInd.length / 3;
  49293. for (i = 0; i < nbfaces; i++) {
  49294. this.pickedParticles.push({ idx: idx, faceId: i });
  49295. }
  49296. }
  49297. };
  49298. // returns a shape array from positions array
  49299. SolidParticleSystem.prototype._posToShape = function (positions) {
  49300. var shape = [];
  49301. for (var i = 0; i < positions.length; i += 3) {
  49302. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49303. }
  49304. return shape;
  49305. };
  49306. // returns a shapeUV array from a Vector4 uvs
  49307. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49308. var shapeUV = [];
  49309. if (uvs) {
  49310. for (var i = 0; i < uvs.length; i++)
  49311. shapeUV.push(uvs[i]);
  49312. }
  49313. return shapeUV;
  49314. };
  49315. // adds a new particle object in the particles array
  49316. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  49317. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  49318. };
  49319. /**
  49320. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49321. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49322. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  49323. * `nb` (positive integer) the number of particles to be created from this model
  49324. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  49325. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  49326. */
  49327. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49328. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49329. var meshInd = mesh.getIndices();
  49330. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49331. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49332. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49333. var bbInfo;
  49334. if (this._particlesIntersect) {
  49335. bbInfo = mesh.getBoundingInfo();
  49336. }
  49337. var shape = this._posToShape(meshPos);
  49338. var shapeUV = this._uvsToShapeUV(meshUV);
  49339. var posfunc = options ? options.positionFunction : null;
  49340. var vtxfunc = options ? options.vertexFunction : null;
  49341. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  49342. // particles
  49343. var idx = this.nbParticles;
  49344. for (var i = 0; i < nb; i++) {
  49345. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49346. if (this._updatable) {
  49347. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  49348. }
  49349. this._index += shape.length;
  49350. idx++;
  49351. }
  49352. this.nbParticles += nb;
  49353. this._shapeCounter++;
  49354. return this._shapeCounter - 1;
  49355. };
  49356. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49357. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49358. this._resetCopy();
  49359. if (particle._model._positionFunction) {
  49360. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49361. }
  49362. if (this._copy.rotationQuaternion) {
  49363. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49364. }
  49365. else {
  49366. this._yaw = this._copy.rotation.y;
  49367. this._pitch = this._copy.rotation.x;
  49368. this._roll = this._copy.rotation.z;
  49369. this._quaternionRotationYPR();
  49370. }
  49371. this._quaternionToRotationMatrix();
  49372. this._shape = particle._model._shape;
  49373. for (var pt = 0; pt < this._shape.length; pt++) {
  49374. this._vertex.x = this._shape[pt].x;
  49375. this._vertex.y = this._shape[pt].y;
  49376. this._vertex.z = this._shape[pt].z;
  49377. if (particle._model._vertexFunction) {
  49378. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49379. }
  49380. this._vertex.x *= this._copy.scaling.x;
  49381. this._vertex.y *= this._copy.scaling.y;
  49382. this._vertex.z *= this._copy.scaling.z;
  49383. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49384. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49385. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49386. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49387. }
  49388. particle.position.x = 0.0;
  49389. particle.position.y = 0.0;
  49390. particle.position.z = 0.0;
  49391. particle.rotation.x = 0.0;
  49392. particle.rotation.y = 0.0;
  49393. particle.rotation.z = 0.0;
  49394. particle.rotationQuaternion = null;
  49395. particle.scaling.x = 1.0;
  49396. particle.scaling.y = 1.0;
  49397. particle.scaling.z = 1.0;
  49398. };
  49399. /**
  49400. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49401. */
  49402. SolidParticleSystem.prototype.rebuildMesh = function () {
  49403. for (var p = 0; p < this.particles.length; p++) {
  49404. this._rebuildParticle(this.particles[p]);
  49405. }
  49406. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49407. };
  49408. /**
  49409. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49410. * This method calls `updateParticle()` for each particle of the SPS.
  49411. * For an animated SPS, it is usually called within the render loop.
  49412. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49413. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49414. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49415. */
  49416. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49417. if (start === void 0) { start = 0; }
  49418. if (end === void 0) { end = this.nbParticles - 1; }
  49419. if (update === void 0) { update = true; }
  49420. if (!this._updatable) {
  49421. return;
  49422. }
  49423. // custom beforeUpdate
  49424. this.beforeUpdateParticles(start, end, update);
  49425. this._cam_axisX.x = 1.0;
  49426. this._cam_axisX.y = 0.0;
  49427. this._cam_axisX.z = 0.0;
  49428. this._cam_axisY.x = 0.0;
  49429. this._cam_axisY.y = 1.0;
  49430. this._cam_axisY.z = 0.0;
  49431. this._cam_axisZ.x = 0.0;
  49432. this._cam_axisZ.y = 0.0;
  49433. this._cam_axisZ.z = 1.0;
  49434. // if the particles will always face the camera
  49435. if (this.billboard) {
  49436. // compute the camera position and un-rotate it by the current mesh rotation
  49437. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  49438. this._quaternionToRotationMatrix();
  49439. this._rotMatrix.invertToRef(this._invertMatrix);
  49440. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  49441. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49442. this._cam_axisZ.normalize();
  49443. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  49444. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  49445. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49446. this._cam_axisY.normalize();
  49447. this._cam_axisX.normalize();
  49448. }
  49449. }
  49450. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49451. var idx = 0;
  49452. var index = 0;
  49453. var colidx = 0;
  49454. var colorIndex = 0;
  49455. var uvidx = 0;
  49456. var uvIndex = 0;
  49457. var pt = 0;
  49458. if (this._computeBoundingBox) {
  49459. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49460. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49461. }
  49462. // particle loop
  49463. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  49464. for (var p = start; p <= end; p++) {
  49465. this._particle = this.particles[p];
  49466. this._shape = this._particle._model._shape;
  49467. this._shapeUV = this._particle._model._shapeUV;
  49468. // call to custom user function to update the particle properties
  49469. this.updateParticle(this._particle);
  49470. if (this._particle.isVisible) {
  49471. // particle rotation matrix
  49472. if (this.billboard) {
  49473. this._particle.rotation.x = 0.0;
  49474. this._particle.rotation.y = 0.0;
  49475. }
  49476. if (this._computeParticleRotation || this.billboard) {
  49477. if (this._particle.rotationQuaternion) {
  49478. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49479. }
  49480. else {
  49481. this._yaw = this._particle.rotation.y;
  49482. this._pitch = this._particle.rotation.x;
  49483. this._roll = this._particle.rotation.z;
  49484. this._quaternionRotationYPR();
  49485. }
  49486. this._quaternionToRotationMatrix();
  49487. }
  49488. // particle vertex loop
  49489. for (pt = 0; pt < this._shape.length; pt++) {
  49490. idx = index + pt * 3;
  49491. colidx = colorIndex + pt * 4;
  49492. uvidx = uvIndex + pt * 2;
  49493. this._vertex.x = this._shape[pt].x;
  49494. this._vertex.y = this._shape[pt].y;
  49495. this._vertex.z = this._shape[pt].z;
  49496. if (this._computeParticleVertex) {
  49497. this.updateParticleVertex(this._particle, this._vertex, pt);
  49498. }
  49499. // positions
  49500. this._vertex.x *= this._particle.scaling.x;
  49501. this._vertex.y *= this._particle.scaling.y;
  49502. this._vertex.z *= this._particle.scaling.z;
  49503. 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];
  49504. 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;
  49505. 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;
  49506. 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;
  49507. 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;
  49508. 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;
  49509. 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;
  49510. if (this._computeBoundingBox) {
  49511. if (this._positions32[idx] < this._minimum.x) {
  49512. this._minimum.x = this._positions32[idx];
  49513. }
  49514. if (this._positions32[idx] > this._maximum.x) {
  49515. this._maximum.x = this._positions32[idx];
  49516. }
  49517. if (this._positions32[idx + 1] < this._minimum.y) {
  49518. this._minimum.y = this._positions32[idx + 1];
  49519. }
  49520. if (this._positions32[idx + 1] > this._maximum.y) {
  49521. this._maximum.y = this._positions32[idx + 1];
  49522. }
  49523. if (this._positions32[idx + 2] < this._minimum.z) {
  49524. this._minimum.z = this._positions32[idx + 2];
  49525. }
  49526. if (this._positions32[idx + 2] > this._maximum.z) {
  49527. this._maximum.z = this._positions32[idx + 2];
  49528. }
  49529. }
  49530. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  49531. if (!this._computeParticleVertex) {
  49532. this._normal.x = this._fixedNormal32[idx];
  49533. this._normal.y = this._fixedNormal32[idx + 1];
  49534. this._normal.z = this._fixedNormal32[idx + 2];
  49535. 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];
  49536. 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;
  49537. 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;
  49538. 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;
  49539. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49540. 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;
  49541. 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;
  49542. }
  49543. if (this._computeParticleColor) {
  49544. this._colors32[colidx] = this._particle.color.r;
  49545. this._colors32[colidx + 1] = this._particle.color.g;
  49546. this._colors32[colidx + 2] = this._particle.color.b;
  49547. this._colors32[colidx + 3] = this._particle.color.a;
  49548. }
  49549. if (this._computeParticleTexture) {
  49550. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49551. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49552. }
  49553. }
  49554. }
  49555. else {
  49556. for (pt = 0; pt < this._shape.length; pt++) {
  49557. idx = index + pt * 3;
  49558. colidx = colorIndex + pt * 4;
  49559. uvidx = uvIndex + pt * 2;
  49560. this._positions32[idx] = this._camera.position.x;
  49561. this._positions32[idx + 1] = this._camera.position.y;
  49562. this._positions32[idx + 2] = this._camera.position.z;
  49563. this._normals32[idx] = 0.0;
  49564. this._normals32[idx + 1] = 0.0;
  49565. this._normals32[idx + 2] = 0.0;
  49566. if (this._computeParticleColor) {
  49567. this._colors32[colidx] = this._particle.color.r;
  49568. this._colors32[colidx + 1] = this._particle.color.g;
  49569. this._colors32[colidx + 2] = this._particle.color.b;
  49570. this._colors32[colidx + 3] = this._particle.color.a;
  49571. }
  49572. if (this._computeParticleTexture) {
  49573. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49574. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49575. }
  49576. }
  49577. }
  49578. // if the particle intersections must be computed : update the bbInfo
  49579. if (this._particlesIntersect) {
  49580. var bInfo = this._particle._boundingInfo;
  49581. var bBox = bInfo.boundingBox;
  49582. var bSphere = bInfo.boundingSphere;
  49583. if (!this._bSphereOnly) {
  49584. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49585. for (var b = 0; b < bBox.vectors.length; b++) {
  49586. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49587. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49588. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49589. 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];
  49590. 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;
  49591. 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;
  49592. 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;
  49593. 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;
  49594. 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;
  49595. 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;
  49596. }
  49597. bBox._update(this.mesh._worldMatrix);
  49598. }
  49599. // place and scale the particle bouding sphere in the SPS local system, then update it
  49600. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49601. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49602. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49603. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49604. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49605. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49606. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49607. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49608. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49609. 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));
  49610. bSphere._update(this.mesh._worldMatrix);
  49611. }
  49612. // increment indexes for the next particle
  49613. index = idx + 3;
  49614. colorIndex = colidx + 4;
  49615. uvIndex = uvidx + 2;
  49616. }
  49617. // if the VBO must be updated
  49618. if (update) {
  49619. if (this._computeParticleColor) {
  49620. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49621. }
  49622. if (this._computeParticleTexture) {
  49623. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49624. }
  49625. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49626. if (!this.mesh.areNormalsFrozen) {
  49627. if (this._computeParticleVertex) {
  49628. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49629. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  49630. for (var i = 0; i < this._normals32.length; i++) {
  49631. this._fixedNormal32[i] = this._normals32[i];
  49632. }
  49633. }
  49634. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49635. }
  49636. }
  49637. if (this._computeBoundingBox) {
  49638. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49639. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49640. }
  49641. this.afterUpdateParticles(start, end, update);
  49642. };
  49643. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49644. this._halfroll = this._roll * 0.5;
  49645. this._halfpitch = this._pitch * 0.5;
  49646. this._halfyaw = this._yaw * 0.5;
  49647. this._sinRoll = Math.sin(this._halfroll);
  49648. this._cosRoll = Math.cos(this._halfroll);
  49649. this._sinPitch = Math.sin(this._halfpitch);
  49650. this._cosPitch = Math.cos(this._halfpitch);
  49651. this._sinYaw = Math.sin(this._halfyaw);
  49652. this._cosYaw = Math.cos(this._halfyaw);
  49653. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  49654. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  49655. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  49656. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  49657. };
  49658. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49659. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49660. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49661. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49662. this._rotMatrix.m[3] = 0;
  49663. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49664. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49665. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49666. this._rotMatrix.m[7] = 0;
  49667. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49668. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49669. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49670. this._rotMatrix.m[11] = 0;
  49671. this._rotMatrix.m[12] = 0;
  49672. this._rotMatrix.m[13] = 0;
  49673. this._rotMatrix.m[14] = 0;
  49674. this._rotMatrix.m[15] = 1.0;
  49675. };
  49676. /**
  49677. * Disposes the SPS
  49678. */
  49679. SolidParticleSystem.prototype.dispose = function () {
  49680. this.mesh.dispose();
  49681. this.vars = null;
  49682. // drop references to internal big arrays for the GC
  49683. this._positions = null;
  49684. this._indices = null;
  49685. this._normals = null;
  49686. this._uvs = null;
  49687. this._colors = null;
  49688. this._positions32 = null;
  49689. this._normals32 = null;
  49690. this._fixedNormal32 = null;
  49691. this._uvs32 = null;
  49692. this._colors32 = null;
  49693. this.pickedParticles = null;
  49694. };
  49695. /**
  49696. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49697. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49698. */
  49699. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49700. if (!this._isVisibilityBoxLocked) {
  49701. this.mesh.refreshBoundingInfo();
  49702. }
  49703. };
  49704. /**
  49705. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49706. * @param size the size (float) of the visibility box
  49707. * note : this doesn't lock the SPS mesh bounding box.
  49708. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49709. */
  49710. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49711. var vis = size / 2;
  49712. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49713. };
  49714. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49715. // getter and setter
  49716. get: function () {
  49717. return this._alwaysVisible;
  49718. },
  49719. /**
  49720. * Sets the SPS as always visible or not
  49721. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49722. */
  49723. set: function (val) {
  49724. this._alwaysVisible = val;
  49725. this.mesh.alwaysSelectAsActiveMesh = val;
  49726. },
  49727. enumerable: true,
  49728. configurable: true
  49729. });
  49730. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49731. get: function () {
  49732. return this._isVisibilityBoxLocked;
  49733. },
  49734. /**
  49735. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49736. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49737. */
  49738. set: function (val) {
  49739. this._isVisibilityBoxLocked = val;
  49740. this.mesh.getBoundingInfo().isLocked = val;
  49741. },
  49742. enumerable: true,
  49743. configurable: true
  49744. });
  49745. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49746. // getters
  49747. get: function () {
  49748. return this._computeParticleRotation;
  49749. },
  49750. // Optimizer setters
  49751. /**
  49752. * Tells to `setParticles()` to compute the particle rotations or not.
  49753. * Default value : true. The SPS is faster when it's set to false.
  49754. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49755. */
  49756. set: function (val) {
  49757. this._computeParticleRotation = val;
  49758. },
  49759. enumerable: true,
  49760. configurable: true
  49761. });
  49762. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49763. get: function () {
  49764. return this._computeParticleColor;
  49765. },
  49766. /**
  49767. * Tells to `setParticles()` to compute the particle colors or not.
  49768. * Default value : true. The SPS is faster when it's set to false.
  49769. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49770. */
  49771. set: function (val) {
  49772. this._computeParticleColor = val;
  49773. },
  49774. enumerable: true,
  49775. configurable: true
  49776. });
  49777. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49778. get: function () {
  49779. return this._computeParticleTexture;
  49780. },
  49781. /**
  49782. * Tells to `setParticles()` to compute the particle textures or not.
  49783. * Default value : true. The SPS is faster when it's set to false.
  49784. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49785. */
  49786. set: function (val) {
  49787. this._computeParticleTexture = val;
  49788. },
  49789. enumerable: true,
  49790. configurable: true
  49791. });
  49792. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49793. get: function () {
  49794. return this._computeParticleVertex;
  49795. },
  49796. /**
  49797. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49798. * Default value : false. The SPS is faster when it's set to false.
  49799. * Note : the particle custom vertex positions aren't stored values.
  49800. */
  49801. set: function (val) {
  49802. this._computeParticleVertex = val;
  49803. },
  49804. enumerable: true,
  49805. configurable: true
  49806. });
  49807. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49808. get: function () {
  49809. return this._computeBoundingBox;
  49810. },
  49811. /**
  49812. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49813. */
  49814. set: function (val) {
  49815. this._computeBoundingBox = val;
  49816. },
  49817. enumerable: true,
  49818. configurable: true
  49819. });
  49820. // =======================================================================
  49821. // Particle behavior logic
  49822. // these following methods may be overwritten by the user to fit his needs
  49823. /**
  49824. * This function does nothing. It may be overwritten to set all the particle first values.
  49825. * The SPS doesn't call this function, you may have to call it by your own.
  49826. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49827. */
  49828. SolidParticleSystem.prototype.initParticles = function () {
  49829. };
  49830. /**
  49831. * This function does nothing. It may be overwritten to recycle a particle.
  49832. * The SPS doesn't call this function, you may have to call it by your own.
  49833. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49834. */
  49835. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49836. return particle;
  49837. };
  49838. /**
  49839. * Updates a particle : this function should be overwritten by the user.
  49840. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49841. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49842. * ex : just set a particle position or velocity and recycle conditions
  49843. */
  49844. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49845. return particle;
  49846. };
  49847. /**
  49848. * Updates a vertex of a particle : it can be overwritten by the user.
  49849. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49850. * @param particle the current particle
  49851. * @param vertex the current index of the current particle
  49852. * @param pt the index of the current vertex in the particle shape
  49853. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49854. * ex : just set a vertex particle position
  49855. */
  49856. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49857. return vertex;
  49858. };
  49859. /**
  49860. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49861. * This does nothing and may be overwritten by the user.
  49862. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49863. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49864. * @param update the boolean update value actually passed to setParticles()
  49865. */
  49866. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49867. };
  49868. /**
  49869. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49870. * This will be passed three parameters.
  49871. * This does nothing and may be overwritten by the user.
  49872. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49873. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49874. * @param update the boolean update value actually passed to setParticles()
  49875. */
  49876. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49877. };
  49878. return SolidParticleSystem;
  49879. }());
  49880. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49881. })(BABYLON || (BABYLON = {}));
  49882. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  49883. var BABYLON;
  49884. (function (BABYLON) {
  49885. var Internals;
  49886. (function (Internals) {
  49887. var FileFaceOrientation = (function () {
  49888. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  49889. this.name = name;
  49890. this.worldAxisForNormal = worldAxisForNormal;
  49891. this.worldAxisForFileX = worldAxisForFileX;
  49892. this.worldAxisForFileY = worldAxisForFileY;
  49893. }
  49894. return FileFaceOrientation;
  49895. }());
  49896. ;
  49897. /**
  49898. * Helper class dealing with the extraction of spherical polynomial dataArray
  49899. * from a cube map.
  49900. */
  49901. var CubeMapToSphericalPolynomialTools = (function () {
  49902. function CubeMapToSphericalPolynomialTools() {
  49903. }
  49904. /**
  49905. * Converts a cubemap to the according Spherical Polynomial data.
  49906. * This extracts the first 3 orders only as they are the only one used in the lighting.
  49907. *
  49908. * @param cubeInfo The Cube map to extract the information from.
  49909. * @return The Spherical Polynomial data.
  49910. */
  49911. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  49912. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  49913. var totalSolidAngle = 0.0;
  49914. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  49915. var du = 2.0 / cubeInfo.size;
  49916. var dv = du;
  49917. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  49918. var minUV = du * 0.5 - 1.0;
  49919. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49920. var fileFace = this.FileFaces[faceIndex];
  49921. var dataArray = cubeInfo[fileFace.name];
  49922. var v = minUV;
  49923. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  49924. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  49925. // Because SP is still linear, so summation is fine in that basis.
  49926. for (var y = 0; y < cubeInfo.size; y++) {
  49927. var u = minUV;
  49928. for (var x = 0; x < cubeInfo.size; x++) {
  49929. // World direction (not normalised)
  49930. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  49931. worldDirection.normalize();
  49932. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  49933. if (1) {
  49934. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  49935. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  49936. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  49937. var color = new BABYLON.Color3(r, g, b);
  49938. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49939. }
  49940. else {
  49941. if (faceIndex == 0) {
  49942. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49943. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49944. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49945. }
  49946. else if (faceIndex == 1) {
  49947. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49948. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49949. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49950. }
  49951. else if (faceIndex == 2) {
  49952. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49953. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49954. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49955. }
  49956. else if (faceIndex == 3) {
  49957. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49958. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49959. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49960. }
  49961. else if (faceIndex == 4) {
  49962. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49963. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49964. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49965. }
  49966. else if (faceIndex == 5) {
  49967. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49968. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49969. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49970. }
  49971. 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]);
  49972. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49973. }
  49974. totalSolidAngle += deltaSolidAngle;
  49975. u += du;
  49976. }
  49977. v += dv;
  49978. }
  49979. }
  49980. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  49981. var correction = correctSolidAngle / totalSolidAngle;
  49982. sphericalHarmonics.scale(correction);
  49983. // Additionally scale by pi -- audit needed
  49984. sphericalHarmonics.scale(1.0 / Math.PI);
  49985. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  49986. };
  49987. CubeMapToSphericalPolynomialTools.FileFaces = [
  49988. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  49989. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  49990. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  49991. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  49992. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  49993. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  49994. ];
  49995. return CubeMapToSphericalPolynomialTools;
  49996. }());
  49997. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  49998. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49999. })(BABYLON || (BABYLON = {}));
  50000. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  50001. var BABYLON;
  50002. (function (BABYLON) {
  50003. var Internals;
  50004. (function (Internals) {
  50005. /**
  50006. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50007. */
  50008. var PanoramaToCubeMapTools = (function () {
  50009. function PanoramaToCubeMapTools() {
  50010. }
  50011. /**
  50012. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50013. *
  50014. * @param float32Array The source data.
  50015. * @param inputWidth The width of the input panorama.
  50016. * @param inputhHeight The height of the input panorama.
  50017. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50018. * @return The cubemap data
  50019. */
  50020. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50021. if (!float32Array) {
  50022. throw "ConvertPanoramaToCubemap: input cannot be null";
  50023. }
  50024. if (float32Array.length != inputWidth * inputHeight * 3) {
  50025. throw "ConvertPanoramaToCubemap: input size is wrong";
  50026. }
  50027. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50028. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50029. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50030. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50031. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50032. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50033. return {
  50034. front: textureFront,
  50035. back: textureBack,
  50036. left: textureLeft,
  50037. right: textureRight,
  50038. up: textureUp,
  50039. down: textureDown,
  50040. size: size
  50041. };
  50042. };
  50043. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50044. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50045. var textureArray = new Float32Array(buffer);
  50046. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50047. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50048. var dy = 1 / texSize;
  50049. var fy = 0;
  50050. for (var y = 0; y < texSize; y++) {
  50051. var xv1 = faceData[0];
  50052. var xv2 = faceData[2];
  50053. for (var x = 0; x < texSize; x++) {
  50054. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50055. v.normalize();
  50056. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50057. // 3 channels per pixels
  50058. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50059. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50060. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50061. xv1 = xv1.add(rotDX1);
  50062. xv2 = xv2.add(rotDX2);
  50063. }
  50064. fy += dy;
  50065. }
  50066. return textureArray;
  50067. };
  50068. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50069. var theta = Math.atan2(vDir.z, vDir.x);
  50070. var phi = Math.acos(vDir.y);
  50071. while (theta < -Math.PI)
  50072. theta += 2 * Math.PI;
  50073. while (theta > Math.PI)
  50074. theta -= 2 * Math.PI;
  50075. var dx = theta / Math.PI;
  50076. var dy = phi / Math.PI;
  50077. // recenter.
  50078. dx = dx * 0.5 + 0.5;
  50079. var px = Math.round(dx * inputWidth);
  50080. if (px < 0)
  50081. px = 0;
  50082. else if (px >= inputWidth)
  50083. px = inputWidth - 1;
  50084. var py = Math.round(dy * inputHeight);
  50085. if (py < 0)
  50086. py = 0;
  50087. else if (py >= inputHeight)
  50088. py = inputHeight - 1;
  50089. var inputY = (inputHeight - py - 1);
  50090. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50091. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50092. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50093. return {
  50094. r: r,
  50095. g: g,
  50096. b: b
  50097. };
  50098. };
  50099. PanoramaToCubeMapTools.FACE_FRONT = [
  50100. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50101. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50102. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50103. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50104. ];
  50105. PanoramaToCubeMapTools.FACE_BACK = [
  50106. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50107. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50108. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50109. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50110. ];
  50111. PanoramaToCubeMapTools.FACE_RIGHT = [
  50112. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50113. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50114. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50115. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50116. ];
  50117. PanoramaToCubeMapTools.FACE_LEFT = [
  50118. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50119. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50120. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50121. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50122. ];
  50123. PanoramaToCubeMapTools.FACE_DOWN = [
  50124. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50125. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50126. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50127. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50128. ];
  50129. PanoramaToCubeMapTools.FACE_UP = [
  50130. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50131. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50132. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50133. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50134. ];
  50135. return PanoramaToCubeMapTools;
  50136. }());
  50137. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50138. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50139. })(BABYLON || (BABYLON = {}));
  50140. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50141. var BABYLON;
  50142. (function (BABYLON) {
  50143. var Internals;
  50144. (function (Internals) {
  50145. ;
  50146. /**
  50147. * This groups tools to convert HDR texture to native colors array.
  50148. */
  50149. var HDRTools = (function () {
  50150. function HDRTools() {
  50151. }
  50152. HDRTools.Ldexp = function (mantissa, exponent) {
  50153. if (exponent > 1023) {
  50154. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50155. }
  50156. if (exponent < -1074) {
  50157. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50158. }
  50159. return mantissa * Math.pow(2, exponent);
  50160. };
  50161. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50162. if (exponent > 0) {
  50163. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50164. float32array[index + 0] = red * exponent;
  50165. float32array[index + 1] = green * exponent;
  50166. float32array[index + 2] = blue * exponent;
  50167. }
  50168. else {
  50169. float32array[index + 0] = 0;
  50170. float32array[index + 1] = 0;
  50171. float32array[index + 2] = 0;
  50172. }
  50173. };
  50174. HDRTools.readStringLine = function (uint8array, startIndex) {
  50175. var line = "";
  50176. var character = "";
  50177. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50178. character = String.fromCharCode(uint8array[i]);
  50179. if (character == "\n") {
  50180. break;
  50181. }
  50182. line += character;
  50183. }
  50184. return line;
  50185. };
  50186. /**
  50187. * Reads header information from an RGBE texture stored in a native array.
  50188. * More information on this format are available here:
  50189. * https://en.wikipedia.org/wiki/RGBE_image_format
  50190. *
  50191. * @param uint8array The binary file stored in native array.
  50192. * @return The header information.
  50193. */
  50194. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50195. var height = 0;
  50196. var width = 0;
  50197. var line = this.readStringLine(uint8array, 0);
  50198. if (line[0] != '#' || line[1] != '?') {
  50199. throw "Bad HDR Format.";
  50200. }
  50201. var endOfHeader = false;
  50202. var findFormat = false;
  50203. var lineIndex = 0;
  50204. do {
  50205. lineIndex += (line.length + 1);
  50206. line = this.readStringLine(uint8array, lineIndex);
  50207. if (line == "FORMAT=32-bit_rle_rgbe") {
  50208. findFormat = true;
  50209. }
  50210. else if (line.length == 0) {
  50211. endOfHeader = true;
  50212. }
  50213. } while (!endOfHeader);
  50214. if (!findFormat) {
  50215. throw "HDR Bad header format, unsupported FORMAT";
  50216. }
  50217. lineIndex += (line.length + 1);
  50218. line = this.readStringLine(uint8array, lineIndex);
  50219. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50220. var match = sizeRegexp.exec(line);
  50221. // TODO. Support +Y and -X if needed.
  50222. if (match.length < 3) {
  50223. throw "HDR Bad header format, no size";
  50224. }
  50225. width = parseInt(match[2]);
  50226. height = parseInt(match[1]);
  50227. if (width < 8 || width > 0x7fff) {
  50228. throw "HDR Bad header format, unsupported size";
  50229. }
  50230. lineIndex += (line.length + 1);
  50231. return {
  50232. height: height,
  50233. width: width,
  50234. dataPosition: lineIndex
  50235. };
  50236. };
  50237. /**
  50238. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50239. * This RGBE texture needs to store the information as a panorama.
  50240. *
  50241. * More information on this format are available here:
  50242. * https://en.wikipedia.org/wiki/RGBE_image_format
  50243. *
  50244. * @param buffer The binary file stored in an array buffer.
  50245. * @param size The expected size of the extracted cubemap.
  50246. * @return The Cube Map information.
  50247. */
  50248. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50249. var uint8array = new Uint8Array(buffer);
  50250. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50251. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50252. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50253. return cubeMapData;
  50254. };
  50255. /**
  50256. * Returns the pixels data extracted from an RGBE texture.
  50257. * This pixels will be stored left to right up to down in the R G B order in one array.
  50258. *
  50259. * More information on this format are available here:
  50260. * https://en.wikipedia.org/wiki/RGBE_image_format
  50261. *
  50262. * @param uint8array The binary file stored in an array buffer.
  50263. * @param hdrInfo The header information of the file.
  50264. * @return The pixels data in RGB right to left up to down order.
  50265. */
  50266. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50267. // Keep for multi format supports.
  50268. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50269. };
  50270. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50271. var num_scanlines = hdrInfo.height;
  50272. var scanline_width = hdrInfo.width;
  50273. var a, b, c, d, count;
  50274. var dataIndex = hdrInfo.dataPosition;
  50275. var index = 0, endIndex = 0, i = 0;
  50276. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50277. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50278. // 3 channels of 4 bytes per pixel in float.
  50279. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50280. var resultArray = new Float32Array(resultBuffer);
  50281. // read in each successive scanline
  50282. while (num_scanlines > 0) {
  50283. a = uint8array[dataIndex++];
  50284. b = uint8array[dataIndex++];
  50285. c = uint8array[dataIndex++];
  50286. d = uint8array[dataIndex++];
  50287. if (a != 2 || b != 2 || (c & 0x80)) {
  50288. // this file is not run length encoded
  50289. throw "HDR Bad header format, not RLE";
  50290. }
  50291. if (((c << 8) | d) != scanline_width) {
  50292. throw "HDR Bad header format, wrong scan line width";
  50293. }
  50294. index = 0;
  50295. // read each of the four channels for the scanline into the buffer
  50296. for (i = 0; i < 4; i++) {
  50297. endIndex = (i + 1) * scanline_width;
  50298. while (index < endIndex) {
  50299. a = uint8array[dataIndex++];
  50300. b = uint8array[dataIndex++];
  50301. if (a > 128) {
  50302. // a run of the same value
  50303. count = a - 128;
  50304. if ((count == 0) || (count > endIndex - index)) {
  50305. throw "HDR Bad Format, bad scanline data (run)";
  50306. }
  50307. while (count-- > 0) {
  50308. scanLineArray[index++] = b;
  50309. }
  50310. }
  50311. else {
  50312. // a non-run
  50313. count = a;
  50314. if ((count == 0) || (count > endIndex - index)) {
  50315. throw "HDR Bad Format, bad scanline data (non-run)";
  50316. }
  50317. scanLineArray[index++] = b;
  50318. if (--count > 0) {
  50319. for (var j = 0; j < count; j++) {
  50320. scanLineArray[index++] = uint8array[dataIndex++];
  50321. }
  50322. }
  50323. }
  50324. }
  50325. }
  50326. // now convert data from buffer into floats
  50327. for (i = 0; i < scanline_width; i++) {
  50328. a = scanLineArray[i];
  50329. b = scanLineArray[i + scanline_width];
  50330. c = scanLineArray[i + 2 * scanline_width];
  50331. d = scanLineArray[i + 3 * scanline_width];
  50332. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50333. }
  50334. num_scanlines--;
  50335. }
  50336. return resultArray;
  50337. };
  50338. return HDRTools;
  50339. }());
  50340. Internals.HDRTools = HDRTools;
  50341. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50342. })(BABYLON || (BABYLON = {}));
  50343. //# sourceMappingURL=babylon.tools.hdr.js.map
  50344. //_______________________________________________________________
  50345. // Extracted from CubeMapGen:
  50346. // https://code.google.com/archive/p/cubemapgen/
  50347. //
  50348. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50349. //_______________________________________________________________
  50350. var BABYLON;
  50351. (function (BABYLON) {
  50352. var Internals;
  50353. (function (Internals) {
  50354. /**
  50355. * The bounding box information used during the conversion process.
  50356. */
  50357. var CMGBoundinBox = (function () {
  50358. function CMGBoundinBox() {
  50359. this.min = new BABYLON.Vector3(0, 0, 0);
  50360. this.max = new BABYLON.Vector3(0, 0, 0);
  50361. this.clear();
  50362. }
  50363. CMGBoundinBox.prototype.clear = function () {
  50364. this.min.x = CMGBoundinBox.MAX;
  50365. this.min.y = CMGBoundinBox.MAX;
  50366. this.min.z = CMGBoundinBox.MAX;
  50367. this.max.x = CMGBoundinBox.MIN;
  50368. this.max.y = CMGBoundinBox.MIN;
  50369. this.max.z = CMGBoundinBox.MIN;
  50370. };
  50371. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50372. this.min.x = Math.min(this.min.x, x);
  50373. this.min.y = Math.min(this.min.y, y);
  50374. this.min.z = Math.min(this.min.z, z);
  50375. this.max.x = Math.max(this.max.x, x);
  50376. this.max.y = Math.max(this.max.y, y);
  50377. this.max.z = Math.max(this.max.z, z);
  50378. };
  50379. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50380. this.min.x = Math.max(this.min.x, x);
  50381. this.min.y = Math.max(this.min.y, y);
  50382. this.min.z = Math.max(this.min.z, z);
  50383. };
  50384. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50385. this.max.x = Math.min(this.max.x, x);
  50386. this.max.y = Math.min(this.max.y, y);
  50387. this.max.z = Math.min(this.max.z, z);
  50388. };
  50389. CMGBoundinBox.prototype.empty = function () {
  50390. if ((this.min.x > this.max.y) ||
  50391. (this.min.y > this.max.y) ||
  50392. (this.min.z > this.max.y)) {
  50393. return true;
  50394. }
  50395. else {
  50396. return false;
  50397. }
  50398. };
  50399. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50400. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50401. return CMGBoundinBox;
  50402. }());
  50403. /**
  50404. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50405. * required by the glossinees of a material.
  50406. *
  50407. * This only supports the cosine drop power as well as Warp fixup generation method.
  50408. *
  50409. * This is using the process from CubeMapGen described here:
  50410. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50411. */
  50412. var PMREMGenerator = (function () {
  50413. /**
  50414. * Constructor of the generator.
  50415. *
  50416. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50417. * @param inputSize The size of the cubemap faces
  50418. * @param outputSize The size of the output cubemap faces
  50419. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50420. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50421. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50422. * @param specularPower The max specular level of the desired cubemap
  50423. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50424. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50425. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50426. */
  50427. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50428. this.input = input;
  50429. this.inputSize = inputSize;
  50430. this.outputSize = outputSize;
  50431. this.maxNumMipLevels = maxNumMipLevels;
  50432. this.numChannels = numChannels;
  50433. this.isFloat = isFloat;
  50434. this.specularPower = specularPower;
  50435. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50436. this.excludeBase = excludeBase;
  50437. this.fixup = fixup;
  50438. this._outputSurface = [];
  50439. this._numMipLevels = 0;
  50440. }
  50441. /**
  50442. * Launches the filter process and return the result.
  50443. *
  50444. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50445. */
  50446. PMREMGenerator.prototype.filterCubeMap = function () {
  50447. // Init cubemap processor
  50448. this.init();
  50449. // Filters the cubemap
  50450. this.filterCubeMapMipChain();
  50451. // Returns the filtered mips.
  50452. return this._outputSurface;
  50453. };
  50454. PMREMGenerator.prototype.init = function () {
  50455. var i;
  50456. var j;
  50457. var mipLevelSize;
  50458. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50459. if (this.maxNumMipLevels == 0) {
  50460. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50461. }
  50462. //first miplevel size
  50463. mipLevelSize = this.outputSize;
  50464. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50465. for (j = 0; j < this.maxNumMipLevels; j++) {
  50466. this._outputSurface.length++;
  50467. this._outputSurface[j] = [];
  50468. //Iterate over faces for output images
  50469. for (i = 0; i < 6; i++) {
  50470. this._outputSurface[j].length++;
  50471. // Initializes a new array for the output.
  50472. if (this.isFloat) {
  50473. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50474. }
  50475. else {
  50476. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50477. }
  50478. }
  50479. //next mip level is half size
  50480. mipLevelSize >>= 1;
  50481. this._numMipLevels++;
  50482. //terminate if mip chain becomes too small
  50483. if (mipLevelSize == 0) {
  50484. this.maxNumMipLevels = j;
  50485. return;
  50486. }
  50487. }
  50488. };
  50489. //--------------------------------------------------------------------------------------
  50490. //Cube map filtering and mip chain generation.
  50491. // the cube map filtereing is specified using a number of parameters:
  50492. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50493. // indicates the region of the hemisphere to filter over for each tap.
  50494. //
  50495. // Note that the top mip level is also a filtered version of the original input images
  50496. // as well in order to create mip chains for diffuse environment illumination.
  50497. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50498. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50499. //
  50500. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50501. // is a_InitialMipAngle
  50502. //
  50503. // The angle for the subsequent levels of the mip chain are specified by their parents
  50504. // filtering angle and a per-level scale and bias
  50505. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50506. //
  50507. //--------------------------------------------------------------------------------------
  50508. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50509. // First, take count of the lighting model to modify SpecularPower
  50510. // 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;
  50511. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50512. //Cone angle start (for generating subsequent mip levels)
  50513. var currentSpecularPower = this.specularPower;
  50514. //Build filter lookup tables based on the source miplevel size
  50515. this.precomputeFilterLookupTables(this.inputSize);
  50516. // Note that we need to filter the first level before generating mipmap
  50517. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50518. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50519. // TODO : Write a function to copy and scale the base mipmap in output
  50520. // I am just lazy here and just put a high specular power value, and do some if.
  50521. if (this.excludeBase && (levelIndex == 0)) {
  50522. // 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).
  50523. currentSpecularPower = 100000.0;
  50524. }
  50525. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50526. var srcCubeImage = this.input;
  50527. var dstCubeImage = this._outputSurface[levelIndex];
  50528. var dstSize = this.outputSize >> levelIndex;
  50529. // Compute required angle.
  50530. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50531. // filter cube surfaces
  50532. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50533. // fix seams
  50534. if (this.fixup) {
  50535. this.fixupCubeEdges(dstCubeImage, dstSize);
  50536. }
  50537. // Decrease the specular power to generate the mipmap chain
  50538. // TODO : Use another method for Exclude (see first comment at start of the function
  50539. if (this.excludeBase && (levelIndex == 0)) {
  50540. currentSpecularPower = this.specularPower;
  50541. }
  50542. currentSpecularPower *= this.cosinePowerDropPerMip;
  50543. }
  50544. };
  50545. //--------------------------------------------------------------------------------------
  50546. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50547. // It allow to optimize the texel to access base on the specular power.
  50548. //--------------------------------------------------------------------------------------
  50549. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50550. // We want to find the alpha such that:
  50551. // cos(alpha)^cosinePower = epsilon
  50552. // That's: acos(epsilon^(1/cosinePower))
  50553. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50554. var angle = 180.0;
  50555. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50556. angle *= 180.0 / Math.PI; // Convert to degree
  50557. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50558. return angle;
  50559. };
  50560. //--------------------------------------------------------------------------------------
  50561. //Builds the following lookup tables prior to filtering:
  50562. // -normalizer cube map
  50563. // -tap weight lookup table
  50564. //
  50565. //--------------------------------------------------------------------------------------
  50566. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50567. var srcTexelAngle;
  50568. var iCubeFace;
  50569. //clear pre-existing normalizer cube map
  50570. this._normCubeMap = [];
  50571. //Normalized vectors per cubeface and per-texel solid angle
  50572. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50573. };
  50574. //--------------------------------------------------------------------------------------
  50575. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50576. //
  50577. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50578. //
  50579. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50580. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50581. // below
  50582. //--------------------------------------------------------------------------------------
  50583. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50584. var iCubeFace;
  50585. var u;
  50586. var v;
  50587. //iterate over cube faces
  50588. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50589. //First three channels for norm cube, and last channel for solid angle
  50590. this._normCubeMap.push(new Float32Array(size * size * 4));
  50591. //fast texture walk, build normalizer cube map
  50592. var facesData = this.input[iCubeFace];
  50593. for (v = 0; v < size; v++) {
  50594. for (u = 0; u < size; u++) {
  50595. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50596. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50597. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50598. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50599. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50600. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50601. }
  50602. }
  50603. }
  50604. };
  50605. //--------------------------------------------------------------------------------------
  50606. // Convert cubemap face texel coordinates and face idx to 3D vector
  50607. // note the U and V coords are integer coords and range from 0 to size-1
  50608. // this routine can be used to generate a normalizer cube map
  50609. //--------------------------------------------------------------------------------------
  50610. // SL BEGIN
  50611. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50612. var nvcU;
  50613. var nvcV;
  50614. var tempVec;
  50615. // Change from original AMD code
  50616. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50617. // + 0.5f is for texel center addressing
  50618. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50619. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50620. // warp fixup
  50621. if (fixup && size > 1) {
  50622. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50623. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50624. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50625. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50626. }
  50627. // Get current vector
  50628. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50629. // U contribution
  50630. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50631. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50632. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50633. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50634. // V contribution and Sum
  50635. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50636. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50637. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50638. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50639. //add face axis
  50640. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50641. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50642. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50643. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50644. //normalize vector
  50645. PMREMGenerator._vectorTemp.normalize();
  50646. return PMREMGenerator._vectorTemp;
  50647. };
  50648. //--------------------------------------------------------------------------------------
  50649. // Convert 3D vector to cubemap face texel coordinates and face idx
  50650. // note the U and V coords are integer coords and range from 0 to size-1
  50651. // this routine can be used to generate a normalizer cube map
  50652. //
  50653. // returns face IDX and texel coords
  50654. //--------------------------------------------------------------------------------------
  50655. // SL BEGIN
  50656. /*
  50657. Mapping Texture Coordinates to Cube Map Faces
  50658. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50659. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50660. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50661. map arrangement in Pixar's RenderMan package.
  50662. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50663. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50664. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50665. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50666. the major axis direction). The target column in the table below explains how the major axis direction
  50667. maps to the 2D image of a particular cube map target.
  50668. major axis
  50669. direction target sc tc ma
  50670. ---------- --------------------------------- --- --- ---
  50671. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50672. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50673. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50674. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50675. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50676. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50677. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50678. an updated (s,t) is calculated as follows
  50679. s = ( sc/|ma| + 1 ) / 2
  50680. t = ( tc/|ma| + 1 ) / 2
  50681. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50682. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50683. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50684. */
  50685. // Note this method return U and V in range from 0 to size-1
  50686. // SL END
  50687. // Store the information in vector3 for convenience (faceindex, u, v)
  50688. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50689. var maxCoord;
  50690. var faceIdx;
  50691. //absolute value 3
  50692. var absX = Math.abs(x);
  50693. var absY = Math.abs(y);
  50694. var absZ = Math.abs(z);
  50695. if (absX >= absY && absX >= absZ) {
  50696. maxCoord = absX;
  50697. if (x >= 0) {
  50698. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50699. }
  50700. else {
  50701. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50702. }
  50703. }
  50704. else if (absY >= absX && absY >= absZ) {
  50705. maxCoord = absY;
  50706. if (y >= 0) {
  50707. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50708. }
  50709. else {
  50710. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50711. }
  50712. }
  50713. else {
  50714. maxCoord = absZ;
  50715. if (z >= 0) {
  50716. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50717. }
  50718. else {
  50719. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50720. }
  50721. }
  50722. //divide through by max coord so face vector lies on cube face
  50723. var scale = 1 / maxCoord;
  50724. x *= scale;
  50725. y *= scale;
  50726. z *= scale;
  50727. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50728. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50729. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50730. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50731. // Modify original AMD code to return value from 0 to Size - 1
  50732. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50733. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50734. PMREMGenerator._vectorTemp.x = faceIdx;
  50735. PMREMGenerator._vectorTemp.y = u;
  50736. PMREMGenerator._vectorTemp.z = v;
  50737. return PMREMGenerator._vectorTemp;
  50738. };
  50739. //--------------------------------------------------------------------------------------
  50740. //Original code from Ignacio CastaÒo
  50741. // This formula is from Manne ÷hrstrˆm's thesis.
  50742. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50743. // cube face and return the area of the projection of that portion on the
  50744. // surface of the sphere.
  50745. //--------------------------------------------------------------------------------------
  50746. PMREMGenerator.prototype.areaElement = function (x, y) {
  50747. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50748. };
  50749. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50750. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50751. // (+ 0.5f is for texel center addressing)
  50752. u = (2.0 * (u + 0.5) / size) - 1.0;
  50753. v = (2.0 * (v + 0.5) / size) - 1.0;
  50754. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50755. var invResolution = 1.0 / size;
  50756. // U and V are the -1..1 texture coordinate on the current face.
  50757. // Get projected area for this texel
  50758. var x0 = u - invResolution;
  50759. var y0 = v - invResolution;
  50760. var x1 = u + invResolution;
  50761. var y1 = v + invResolution;
  50762. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50763. return solidAngle;
  50764. };
  50765. //--------------------------------------------------------------------------------------
  50766. //The key to the speed of these filtering routines is to quickly define a per-face
  50767. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50768. // Later these pixels are selectively processed based on their dot products to see if
  50769. // they reside within the filtering cone.
  50770. //
  50771. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50772. // of the number of texels needed to be covered in width and height order to filter the
  50773. // region. the bounding box for the center taps face is defined first, and if the
  50774. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50775. // defined next
  50776. //--------------------------------------------------------------------------------------
  50777. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50778. // note that pixels within these regions may be rejected
  50779. // based on the anlge
  50780. var iCubeFace;
  50781. var u;
  50782. var v;
  50783. // bounding box per face to specify region to process
  50784. var filterExtents = [];
  50785. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50786. filterExtents.push(new CMGBoundinBox());
  50787. }
  50788. // min angle a src texel can cover (in degrees)
  50789. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  50790. // angle about center tap to define filter cone
  50791. // filter angle is 1/2 the cone angle
  50792. var filterAngle = filterConeAngle / 2.0;
  50793. //ensure filter angle is larger than a texel
  50794. if (filterAngle < srcTexelAngle) {
  50795. filterAngle = srcTexelAngle;
  50796. }
  50797. //ensure filter cone is always smaller than the hemisphere
  50798. if (filterAngle > 90.0) {
  50799. filterAngle = 90.0;
  50800. }
  50801. // the maximum number of texels in 1D the filter cone angle will cover
  50802. // used to determine bounding box size for filter extents
  50803. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  50804. // ensure conservative region always covers at least one texel
  50805. if (filterSize < 1) {
  50806. filterSize = 1;
  50807. }
  50808. // dotProdThresh threshold based on cone angle to determine whether or not taps
  50809. // reside within the cone angle
  50810. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  50811. // process required faces
  50812. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50813. //iterate over dst cube map face texel
  50814. for (v = 0; v < dstSize; v++) {
  50815. for (u = 0; u < dstSize; u++) {
  50816. //get center tap direction
  50817. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  50818. //clear old per-face filter extents
  50819. this.clearFilterExtents(filterExtents);
  50820. //define per-face filter extents
  50821. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  50822. //perform filtering of src faces using filter extents
  50823. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  50824. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  50825. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  50826. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  50827. }
  50828. }
  50829. }
  50830. };
  50831. //--------------------------------------------------------------------------------------
  50832. //Clear filter extents for the 6 cube map faces
  50833. //--------------------------------------------------------------------------------------
  50834. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  50835. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  50836. filterExtents[iCubeFaces].clear();
  50837. }
  50838. };
  50839. //--------------------------------------------------------------------------------------
  50840. //Define per-face bounding box filter extents
  50841. //
  50842. // These define conservative texel regions in each of the faces the filter can possibly
  50843. // process. When the pixels in the regions are actually processed, the dot product
  50844. // between the tap vector and the center tap vector is used to determine the weight of
  50845. // the tap and whether or not the tap is within the cone.
  50846. //
  50847. //--------------------------------------------------------------------------------------
  50848. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  50849. //neighboring face and bleed over amount, and width of BBOX for
  50850. // left, right, top, and bottom edges of this face
  50851. var bleedOverAmount = [0, 0, 0, 0];
  50852. var bleedOverBBoxMin = [0, 0, 0, 0];
  50853. var bleedOverBBoxMax = [0, 0, 0, 0];
  50854. var neighborFace;
  50855. var neighborEdge;
  50856. var oppositeFaceIdx;
  50857. //get face idx, and u, v info from center tap dir
  50858. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  50859. var faceIdx = result.x;
  50860. var u = result.y;
  50861. var v = result.z;
  50862. //define bbox size within face
  50863. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  50864. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  50865. filterExtents[faceIdx].clampMin(0, 0, 0);
  50866. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  50867. //u and v extent in face corresponding to center tap
  50868. var minU = filterExtents[faceIdx].min.x;
  50869. var minV = filterExtents[faceIdx].min.y;
  50870. var maxU = filterExtents[faceIdx].max.x;
  50871. var maxV = filterExtents[faceIdx].max.y;
  50872. //bleed over amounts for face across u=0 edge (left)
  50873. bleedOverAmount[0] = (bboxSize - u);
  50874. bleedOverBBoxMin[0] = minV;
  50875. bleedOverBBoxMax[0] = maxV;
  50876. //bleed over amounts for face across u=1 edge (right)
  50877. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  50878. bleedOverBBoxMin[1] = minV;
  50879. bleedOverBBoxMax[1] = maxV;
  50880. //bleed over to face across v=0 edge (up)
  50881. bleedOverAmount[2] = (bboxSize - v);
  50882. bleedOverBBoxMin[2] = minU;
  50883. bleedOverBBoxMax[2] = maxU;
  50884. //bleed over to face across v=1 edge (down)
  50885. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  50886. bleedOverBBoxMin[3] = minU;
  50887. bleedOverBBoxMax[3] = maxU;
  50888. //compute bleed over regions in neighboring faces
  50889. for (var i = 0; i < 4; i++) {
  50890. if (bleedOverAmount[i] > 0) {
  50891. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  50892. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  50893. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  50894. // be flipped: the cases are
  50895. // if a left edge mates with a left or bottom edge on the neighbor
  50896. // if a top edge mates with a top or right edge on the neighbor
  50897. // if a right edge mates with a right or top edge on the neighbor
  50898. // if a bottom edge mates with a bottom or left edge on the neighbor
  50899. //Seeing as the edges are enumerated as follows
  50900. // left =0
  50901. // right =1
  50902. // top =2
  50903. // bottom =3
  50904. //
  50905. // so if the edge enums are the same, or the sum of the enums == 3,
  50906. // the bbox needs to be flipped
  50907. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  50908. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  50909. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  50910. }
  50911. //The way the bounding box is extended onto the neighboring face
  50912. // depends on which edge of neighboring face abuts with this one
  50913. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  50914. case PMREMGenerator.CP_EDGE_LEFT:
  50915. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  50916. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50917. break;
  50918. case PMREMGenerator.CP_EDGE_RIGHT:
  50919. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  50920. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50921. break;
  50922. case PMREMGenerator.CP_EDGE_TOP:
  50923. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  50924. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  50925. break;
  50926. case PMREMGenerator.CP_EDGE_BOTTOM:
  50927. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  50928. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  50929. break;
  50930. }
  50931. //clamp filter extents in non-center tap faces to remain within surface
  50932. filterExtents[neighborFace].clampMin(0, 0, 0);
  50933. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  50934. }
  50935. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  50936. // from the center tap face, then process the opposite face entirely for now.
  50937. //Note that the cases in which this happens, what usually happens is that
  50938. // more than one edge bleeds onto the opposite face, and the bounding box
  50939. // encompasses the entire cube map face.
  50940. if (bleedOverAmount[i] > srcSize) {
  50941. //determine opposite face
  50942. switch (faceIdx) {
  50943. case PMREMGenerator.CP_FACE_X_POS:
  50944. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50945. break;
  50946. case PMREMGenerator.CP_FACE_X_NEG:
  50947. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  50948. break;
  50949. case PMREMGenerator.CP_FACE_Y_POS:
  50950. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50951. break;
  50952. case PMREMGenerator.CP_FACE_Y_NEG:
  50953. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50954. break;
  50955. case PMREMGenerator.CP_FACE_Z_POS:
  50956. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50957. break;
  50958. case PMREMGenerator.CP_FACE_Z_NEG:
  50959. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50960. break;
  50961. default:
  50962. break;
  50963. }
  50964. //just encompass entire face for now
  50965. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  50966. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  50967. }
  50968. }
  50969. };
  50970. //--------------------------------------------------------------------------------------
  50971. //ProcessFilterExtents
  50972. // Process bounding box in each cube face
  50973. //
  50974. //--------------------------------------------------------------------------------------
  50975. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  50976. //accumulators are 64-bit floats in order to have the precision needed
  50977. // over a summation of a large number of pixels
  50978. var dstAccum = [0, 0, 0, 0];
  50979. var weightAccum = 0;
  50980. var k = 0;
  50981. var nSrcChannels = this.numChannels;
  50982. // norm cube map and srcCubeMap have same face width
  50983. var faceWidth = srcSize;
  50984. //amount to add to pointer to move to next scanline in images
  50985. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  50986. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  50987. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  50988. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  50989. // iterate over cubefaces
  50990. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  50991. //if bbox is non empty
  50992. if (!filterExtents[iFaceIdx].empty()) {
  50993. var uStart = filterExtents[iFaceIdx].min.x;
  50994. var vStart = filterExtents[iFaceIdx].min.y;
  50995. var uEnd = filterExtents[iFaceIdx].max.x;
  50996. var vEnd = filterExtents[iFaceIdx].max.y;
  50997. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  50998. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  50999. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51000. for (var v = vStart; v <= vEnd; v++) {
  51001. var normCubeRowWalk = 0;
  51002. var srcCubeRowWalk = 0;
  51003. for (var u = uStart; u <= uEnd; u++) {
  51004. //pointer to direction in cube map associated with texel
  51005. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51006. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51007. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51008. //check dot product to see if texel is within cone
  51009. var tapDotProd = texelVectX * centerTapDir.x +
  51010. texelVectY * centerTapDir.y +
  51011. texelVectZ * centerTapDir.z;
  51012. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51013. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51014. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51015. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51016. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51017. // so just adding one to specularpower do the trick.
  51018. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51019. //iterate over channels
  51020. for (k = 0; k < nSrcChannels; k++) {
  51021. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51022. srcCubeRowWalk++;
  51023. }
  51024. weightAccum += weight; //accumulate weight
  51025. }
  51026. else {
  51027. //step across source pixel
  51028. srcCubeRowWalk += nSrcChannels;
  51029. }
  51030. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51031. }
  51032. startIndexNormCubeMap += normCubePitch;
  51033. startIndexSrcCubeMap += srcCubePitch;
  51034. }
  51035. }
  51036. }
  51037. //divide through by weights if weight is non zero
  51038. if (weightAccum != 0.0) {
  51039. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51040. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51041. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51042. if (this.numChannels > 3) {
  51043. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51044. }
  51045. }
  51046. else {
  51047. // otherwise sample nearest
  51048. // get face idx and u, v texel coordinate in face
  51049. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51050. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51051. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51052. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51053. if (this.numChannels > 3) {
  51054. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51055. }
  51056. }
  51057. return PMREMGenerator._vectorTemp;
  51058. };
  51059. //--------------------------------------------------------------------------------------
  51060. // Fixup cube edges
  51061. //
  51062. // average texels on cube map faces across the edges
  51063. // WARP/BENT Method Only.
  51064. //--------------------------------------------------------------------------------------
  51065. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51066. var k;
  51067. var j;
  51068. var i;
  51069. var iFace;
  51070. var iCorner = 0;
  51071. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51072. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51073. // note that if functionality to filter across the three texels for each corner, then
  51074. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51075. var cornerPtr = [
  51076. [[], [], []],
  51077. [[], [], []],
  51078. [[], [], []],
  51079. [[], [], []],
  51080. [[], [], []],
  51081. [[], [], []],
  51082. [[], [], []],
  51083. [[], [], []]
  51084. ];
  51085. //if there is no fixup, or fixup width = 0, do nothing
  51086. if (cubeMapSize < 1) {
  51087. return;
  51088. }
  51089. //special case 1x1 cubemap, average face colors
  51090. if (cubeMapSize == 1) {
  51091. //iterate over channels
  51092. for (k = 0; k < this.numChannels; k++) {
  51093. var accum = 0.0;
  51094. //iterate over faces to accumulate face colors
  51095. for (iFace = 0; iFace < 6; iFace++) {
  51096. accum += cubeMap[iFace][k];
  51097. }
  51098. //compute average over 6 face colors
  51099. accum /= 6.0;
  51100. //iterate over faces to distribute face colors
  51101. for (iFace = 0; iFace < 6; iFace++) {
  51102. cubeMap[iFace][k] = accum;
  51103. }
  51104. }
  51105. return;
  51106. }
  51107. //iterate over faces to collect list of corner texel pointers
  51108. for (iFace = 0; iFace < 6; iFace++) {
  51109. //the 4 corner pointers for this face
  51110. faceCornerStartIndicies[0] = [iFace, 0];
  51111. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51112. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51113. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51114. //iterate over face corners to collect cube corner pointers
  51115. for (iCorner = 0; iCorner < 4; iCorner++) {
  51116. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51117. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51118. cornerNumPtrs[corner]++;
  51119. }
  51120. }
  51121. //iterate over corners to average across corner tap values
  51122. for (iCorner = 0; iCorner < 8; iCorner++) {
  51123. for (k = 0; k < this.numChannels; k++) {
  51124. var cornerTapAccum = 0.0;
  51125. //iterate over corner texels and average results
  51126. for (i = 0; i < 3; i++) {
  51127. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51128. }
  51129. //divide by 3 to compute average of corner tap values
  51130. cornerTapAccum *= (1.0 / 3.0);
  51131. //iterate over corner texels and average results
  51132. for (i = 0; i < 3; i++) {
  51133. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51134. }
  51135. }
  51136. }
  51137. //iterate over the twelve edges of the cube to average across edges
  51138. for (i = 0; i < 12; i++) {
  51139. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51140. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51141. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51142. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51143. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51144. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51145. var edgeWalk = 0;
  51146. var neighborEdgeWalk = 0;
  51147. //Determine walking pointers based on edge type
  51148. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51149. switch (edge) {
  51150. case PMREMGenerator.CP_EDGE_LEFT:
  51151. // no change to faceEdgeStartPtr
  51152. edgeWalk = this.numChannels * cubeMapSize;
  51153. break;
  51154. case PMREMGenerator.CP_EDGE_RIGHT:
  51155. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51156. edgeWalk = this.numChannels * cubeMapSize;
  51157. break;
  51158. case PMREMGenerator.CP_EDGE_TOP:
  51159. // no change to faceEdgeStartPtr
  51160. edgeWalk = this.numChannels;
  51161. break;
  51162. case PMREMGenerator.CP_EDGE_BOTTOM:
  51163. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51164. edgeWalk = this.numChannels;
  51165. break;
  51166. }
  51167. //For certain types of edge abutments, the neighbor edge walk needs to
  51168. // be flipped: the cases are
  51169. // if a left edge mates with a left or bottom edge on the neighbor
  51170. // if a top edge mates with a top or right edge on the neighbor
  51171. // if a right edge mates with a right or top edge on the neighbor
  51172. // if a bottom edge mates with a bottom or left edge on the neighbor
  51173. //Seeing as the edges are enumerated as follows
  51174. // left =0
  51175. // right =1
  51176. // top =2
  51177. // bottom =3
  51178. //
  51179. //If the edge enums are the same, or the sum of the enums == 3,
  51180. // the neighbor edge walk needs to be flipped
  51181. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51182. switch (neighborEdge) {
  51183. case PMREMGenerator.CP_EDGE_LEFT:
  51184. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51185. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51186. break;
  51187. case PMREMGenerator.CP_EDGE_RIGHT:
  51188. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51189. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51190. break;
  51191. case PMREMGenerator.CP_EDGE_TOP:
  51192. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51193. neighborEdgeWalk = -this.numChannels;
  51194. break;
  51195. case PMREMGenerator.CP_EDGE_BOTTOM:
  51196. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51197. neighborEdgeWalk = -this.numChannels;
  51198. break;
  51199. }
  51200. }
  51201. else {
  51202. //swapped direction neighbor edge walk
  51203. switch (neighborEdge) {
  51204. case PMREMGenerator.CP_EDGE_LEFT:
  51205. //no change to neighborEdgeStartPtr for this case since it points
  51206. // to the upper left corner already
  51207. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51208. break;
  51209. case PMREMGenerator.CP_EDGE_RIGHT:
  51210. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51211. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51212. break;
  51213. case PMREMGenerator.CP_EDGE_TOP:
  51214. //no change to neighborEdgeStartPtr for this case since it points
  51215. // to the upper left corner already
  51216. neighborEdgeWalk = this.numChannels;
  51217. break;
  51218. case PMREMGenerator.CP_EDGE_BOTTOM:
  51219. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51220. neighborEdgeWalk = this.numChannels;
  51221. break;
  51222. }
  51223. }
  51224. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51225. //nearby neighborhood
  51226. //step ahead one texel on edge
  51227. edgeStartIndex += edgeWalk;
  51228. neighborEdgeStartIndex += neighborEdgeWalk;
  51229. // note that this loop does not process the corner texels, since they have already been
  51230. // averaged across faces across earlier
  51231. for (j = 1; j < (cubeMapSize - 1); j++) {
  51232. //for each set of taps along edge, average them
  51233. // and rewrite the results into the edges
  51234. for (k = 0; k < this.numChannels; k++) {
  51235. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51236. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51237. //compute average of tap intensity values
  51238. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51239. //propagate average of taps to edge taps
  51240. cubeMap[face][edgeStartIndex + k] = avgTap;
  51241. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51242. }
  51243. edgeStartIndex += edgeWalk;
  51244. neighborEdgeStartIndex += neighborEdgeWalk;
  51245. }
  51246. }
  51247. };
  51248. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51249. PMREMGenerator.CP_UDIR = 0;
  51250. PMREMGenerator.CP_VDIR = 1;
  51251. PMREMGenerator.CP_FACEAXIS = 2;
  51252. //used to index cube faces
  51253. PMREMGenerator.CP_FACE_X_POS = 0;
  51254. PMREMGenerator.CP_FACE_X_NEG = 1;
  51255. PMREMGenerator.CP_FACE_Y_POS = 2;
  51256. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51257. PMREMGenerator.CP_FACE_Z_POS = 4;
  51258. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51259. //used to index image edges
  51260. // NOTE.. the actual number corresponding to the edge is important
  51261. // do not change these, or the code will break
  51262. //
  51263. // CP_EDGE_LEFT is u = 0
  51264. // CP_EDGE_RIGHT is u = width-1
  51265. // CP_EDGE_TOP is v = 0
  51266. // CP_EDGE_BOTTOM is v = height-1
  51267. PMREMGenerator.CP_EDGE_LEFT = 0;
  51268. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51269. PMREMGenerator.CP_EDGE_TOP = 2;
  51270. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51271. //corners of CUBE map (P or N specifys if it corresponds to the
  51272. // positive or negative direction each of X, Y, and Z
  51273. PMREMGenerator.CP_CORNER_NNN = 0;
  51274. PMREMGenerator.CP_CORNER_NNP = 1;
  51275. PMREMGenerator.CP_CORNER_NPN = 2;
  51276. PMREMGenerator.CP_CORNER_NPP = 3;
  51277. PMREMGenerator.CP_CORNER_PNN = 4;
  51278. PMREMGenerator.CP_CORNER_PNP = 5;
  51279. PMREMGenerator.CP_CORNER_PPN = 6;
  51280. PMREMGenerator.CP_CORNER_PPP = 7;
  51281. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51282. //3x2 matrices that map cube map indexing vectors in 3d
  51283. // (after face selection and divide through by the
  51284. // _ABSOLUTE VALUE_ of the max coord)
  51285. // into NVC space
  51286. //Note this currently assumes the D3D cube face ordering and orientation
  51287. PMREMGenerator._sgFace2DMapping = [
  51288. //XPOS face
  51289. [[0, 0, -1],
  51290. [0, -1, 0],
  51291. [1, 0, 0]],
  51292. //XNEG face
  51293. [[0, 0, 1],
  51294. [0, -1, 0],
  51295. [-1, 0, 0]],
  51296. //YPOS face
  51297. [[1, 0, 0],
  51298. [0, 0, 1],
  51299. [0, 1, 0]],
  51300. //YNEG face
  51301. [[1, 0, 0],
  51302. [0, 0, -1],
  51303. [0, -1, 0]],
  51304. //ZPOS face
  51305. [[1, 0, 0],
  51306. [0, -1, 0],
  51307. [0, 0, 1]],
  51308. //ZNEG face
  51309. [[-1, 0, 0],
  51310. [0, -1, 0],
  51311. [0, 0, -1]],
  51312. ];
  51313. //------------------------------------------------------------------------------
  51314. // D3D cube map face specification
  51315. // mapping from 3D x,y,z cube map lookup coordinates
  51316. // to 2D within face u,v coordinates
  51317. //
  51318. // --------------------> U direction
  51319. // | (within-face texture space)
  51320. // | _____
  51321. // | | |
  51322. // | | +Y |
  51323. // | _____|_____|_____ _____
  51324. // | | | | | |
  51325. // | | -X | +Z | +X | -Z |
  51326. // | |_____|_____|_____|_____|
  51327. // | | |
  51328. // | | -Y |
  51329. // | |_____|
  51330. // |
  51331. // v V direction
  51332. // (within-face texture space)
  51333. //------------------------------------------------------------------------------
  51334. //Information about neighbors and how texture coorrdinates change across faces
  51335. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51336. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51337. //Note this currently assumes the D3D cube face ordering and orientation
  51338. PMREMGenerator._sgCubeNgh = [
  51339. //XPOS face
  51340. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51341. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51342. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51343. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51344. //XNEG face
  51345. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51346. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51347. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51348. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51349. //YPOS face
  51350. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51351. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51352. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51353. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51354. //YNEG face
  51355. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51356. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51357. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51358. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51359. //ZPOS face
  51360. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51361. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51362. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51363. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51364. //ZNEG face
  51365. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51366. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51367. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51368. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51369. ];
  51370. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51371. // this table is used to average over the edges.
  51372. PMREMGenerator._sgCubeEdgeList = [
  51373. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51374. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51375. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51376. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51377. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51378. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51379. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51380. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51381. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51382. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51383. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51384. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51385. ];
  51386. //Information about which of the 8 cube corners are correspond to the
  51387. // the 4 corners in each cube face
  51388. // the order is upper left, upper right, lower left, lower right
  51389. PMREMGenerator._sgCubeCornerList = [
  51390. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51391. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51392. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51393. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51394. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51395. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51396. ];
  51397. return PMREMGenerator;
  51398. }());
  51399. Internals.PMREMGenerator = PMREMGenerator;
  51400. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51401. })(BABYLON || (BABYLON = {}));
  51402. //# sourceMappingURL=babylon.tools.pmremgenerator.js.map
  51403. var BABYLON;
  51404. (function (BABYLON) {
  51405. /**
  51406. * This represents a texture coming from an HDR input.
  51407. *
  51408. * The only supported format is currently panorama picture stored in RGBE format.
  51409. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51410. */
  51411. var HDRCubeTexture = (function (_super) {
  51412. __extends(HDRCubeTexture, _super);
  51413. /**
  51414. * Instantiates an HDRTexture from the following parameters.
  51415. *
  51416. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51417. * @param scene The scene the texture will be used in
  51418. * @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.
  51419. * @param noMipmap Forces to not generate the mipmap if true
  51420. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51421. * @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)
  51422. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51423. */
  51424. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  51425. if (noMipmap === void 0) { noMipmap = false; }
  51426. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51427. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51428. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51429. _super.call(this, scene);
  51430. this._useInGammaSpace = false;
  51431. this._generateHarmonics = true;
  51432. this._isBABYLONPreprocessed = false;
  51433. /**
  51434. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51435. */
  51436. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51437. /**
  51438. * The spherical polynomial data extracted from the texture.
  51439. */
  51440. this.sphericalPolynomial = null;
  51441. /**
  51442. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51443. * This is usefull at run time to apply the good shader.
  51444. */
  51445. this.isPMREM = false;
  51446. if (!url) {
  51447. return;
  51448. }
  51449. this.name = url;
  51450. this.url = url;
  51451. this.hasAlpha = false;
  51452. this.isCube = true;
  51453. this._textureMatrix = BABYLON.Matrix.Identity();
  51454. if (size) {
  51455. this._isBABYLONPreprocessed = false;
  51456. this._noMipmap = noMipmap;
  51457. this._size = size;
  51458. this._useInGammaSpace = useInGammaSpace;
  51459. this._usePMREMGenerator = usePMREMGenerator &&
  51460. scene.getEngine().getCaps().textureLOD &&
  51461. this.getScene().getEngine().getCaps().textureFloat &&
  51462. !this._useInGammaSpace;
  51463. }
  51464. else {
  51465. this._isBABYLONPreprocessed = true;
  51466. this._noMipmap = false;
  51467. this._useInGammaSpace = false;
  51468. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51469. this.getScene().getEngine().getCaps().textureFloat &&
  51470. !this._useInGammaSpace;
  51471. }
  51472. this.isPMREM = this._usePMREMGenerator;
  51473. this._texture = this._getFromCache(url, this._noMipmap);
  51474. if (!this._texture) {
  51475. if (!scene.useDelayedTextureLoading) {
  51476. this.loadTexture();
  51477. }
  51478. else {
  51479. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51480. }
  51481. }
  51482. }
  51483. /**
  51484. * Occurs when the file is a preprocessed .babylon.hdr file.
  51485. */
  51486. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51487. var _this = this;
  51488. var mipLevels = 0;
  51489. var floatArrayView = null;
  51490. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51491. var mips = [];
  51492. var startIndex = 30;
  51493. for (var level = 0; level < mipLevels; level++) {
  51494. mips.push([]);
  51495. // Fill each pixel of the mip level.
  51496. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51497. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51498. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51499. mips[level].push(faceData);
  51500. startIndex += faceSize;
  51501. }
  51502. }
  51503. return mips;
  51504. } : null;
  51505. var callback = function (buffer) {
  51506. // Create Native Array Views
  51507. var intArrayView = new Int32Array(buffer);
  51508. floatArrayView = new Float32Array(buffer);
  51509. // Fill header.
  51510. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51511. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51512. // Update Texture Information.
  51513. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51514. // Fill polynomial information.
  51515. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51516. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51517. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51518. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51519. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51520. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51521. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51522. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51523. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51524. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51525. // Fill pixel data.
  51526. mipLevels = intArrayView[29]; // Number of mip levels.
  51527. var startIndex = 30;
  51528. var data = [];
  51529. var faceSize = Math.pow(_this._size, 2) * 3;
  51530. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51531. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51532. startIndex += faceSize;
  51533. }
  51534. var results = [];
  51535. var byteArray = null;
  51536. // Push each faces.
  51537. for (var k = 0; k < 6; k++) {
  51538. var dataFace = null;
  51539. // If special cases.
  51540. if (!mipmapGenerator) {
  51541. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51542. dataFace = data[j];
  51543. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51544. // 3 channels of 1 bytes per pixel in bytes.
  51545. var byteBuffer = new ArrayBuffer(faceSize);
  51546. byteArray = new Uint8Array(byteBuffer);
  51547. }
  51548. for (var i = 0; i < _this._size * _this._size; i++) {
  51549. // Put in gamma space if requested.
  51550. if (_this._useInGammaSpace) {
  51551. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51552. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51553. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51554. }
  51555. // Convert to int texture for fallback.
  51556. if (byteArray) {
  51557. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51558. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51559. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51560. // May use luminance instead if the result is not accurate.
  51561. var max = Math.max(Math.max(r, g), b);
  51562. if (max > 255) {
  51563. var scale = 255 / max;
  51564. r *= scale;
  51565. g *= scale;
  51566. b *= scale;
  51567. }
  51568. byteArray[(i * 3) + 0] = r;
  51569. byteArray[(i * 3) + 1] = g;
  51570. byteArray[(i * 3) + 2] = b;
  51571. }
  51572. }
  51573. }
  51574. else {
  51575. dataFace = data[k];
  51576. }
  51577. // Fill the array accordingly.
  51578. if (byteArray) {
  51579. results.push(byteArray);
  51580. }
  51581. else {
  51582. results.push(dataFace);
  51583. }
  51584. }
  51585. return results;
  51586. };
  51587. 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);
  51588. };
  51589. /**
  51590. * Occurs when the file is raw .hdr file.
  51591. */
  51592. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51593. var _this = this;
  51594. var callback = function (buffer) {
  51595. // Extract the raw linear data.
  51596. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51597. // Generate harmonics if needed.
  51598. if (_this._generateHarmonics) {
  51599. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51600. }
  51601. var results = [];
  51602. var byteArray = null;
  51603. // Push each faces.
  51604. for (var j = 0; j < 6; j++) {
  51605. // Create uintarray fallback.
  51606. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51607. // 3 channels of 1 bytes per pixel in bytes.
  51608. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51609. byteArray = new Uint8Array(byteBuffer);
  51610. }
  51611. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51612. // If special cases.
  51613. if (_this._useInGammaSpace || byteArray) {
  51614. for (var i = 0; i < _this._size * _this._size; i++) {
  51615. // Put in gamma space if requested.
  51616. if (_this._useInGammaSpace) {
  51617. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51618. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51619. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51620. }
  51621. // Convert to int texture for fallback.
  51622. if (byteArray) {
  51623. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51624. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51625. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51626. // May use luminance instead if the result is not accurate.
  51627. var max = Math.max(Math.max(r, g), b);
  51628. if (max > 255) {
  51629. var scale = 255 / max;
  51630. r *= scale;
  51631. g *= scale;
  51632. b *= scale;
  51633. }
  51634. byteArray[(i * 3) + 0] = r;
  51635. byteArray[(i * 3) + 1] = g;
  51636. byteArray[(i * 3) + 2] = b;
  51637. }
  51638. }
  51639. }
  51640. if (byteArray) {
  51641. results.push(byteArray);
  51642. }
  51643. else {
  51644. results.push(dataFace);
  51645. }
  51646. }
  51647. return results;
  51648. };
  51649. var mipmapGenerator = null;
  51650. if (!this._noMipmap &&
  51651. this._usePMREMGenerator) {
  51652. mipmapGenerator = function (data) {
  51653. // Custom setup of the generator matching with the PBR shader values.
  51654. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51655. return generator.filterCubeMap();
  51656. };
  51657. }
  51658. 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);
  51659. };
  51660. /**
  51661. * Starts the loading process of the texture.
  51662. */
  51663. HDRCubeTexture.prototype.loadTexture = function () {
  51664. if (this._isBABYLONPreprocessed) {
  51665. this.loadBabylonTexture();
  51666. }
  51667. else {
  51668. this.loadHDRTexture();
  51669. }
  51670. };
  51671. HDRCubeTexture.prototype.clone = function () {
  51672. var size = this._isBABYLONPreprocessed ? null : this._size;
  51673. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51674. // Base texture
  51675. newTexture.level = this.level;
  51676. newTexture.wrapU = this.wrapU;
  51677. newTexture.wrapV = this.wrapV;
  51678. newTexture.coordinatesIndex = this.coordinatesIndex;
  51679. newTexture.coordinatesMode = this.coordinatesMode;
  51680. return newTexture;
  51681. };
  51682. // Methods
  51683. HDRCubeTexture.prototype.delayLoad = function () {
  51684. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51685. return;
  51686. }
  51687. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51688. this._texture = this._getFromCache(this.url, this._noMipmap);
  51689. if (!this._texture) {
  51690. this.loadTexture();
  51691. }
  51692. };
  51693. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51694. return this._textureMatrix;
  51695. };
  51696. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51697. var texture = null;
  51698. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51699. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51700. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  51701. texture.name = parsedTexture.name;
  51702. texture.hasAlpha = parsedTexture.hasAlpha;
  51703. texture.level = parsedTexture.level;
  51704. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51705. }
  51706. return texture;
  51707. };
  51708. HDRCubeTexture.prototype.serialize = function () {
  51709. if (!this.name) {
  51710. return null;
  51711. }
  51712. var serializationObject = {};
  51713. serializationObject.name = this.name;
  51714. serializationObject.hasAlpha = this.hasAlpha;
  51715. serializationObject.isCube = true;
  51716. serializationObject.level = this.level;
  51717. serializationObject.size = this._size;
  51718. serializationObject.coordinatesMode = this.coordinatesMode;
  51719. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51720. serializationObject.generateHarmonics = this._generateHarmonics;
  51721. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51722. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51723. serializationObject.customType = "BABYLON.HDRCubeTexture";
  51724. return serializationObject;
  51725. };
  51726. /**
  51727. * Saves as a file the data contained in the texture in a binary format.
  51728. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51729. * as the spherical used in the lighting.
  51730. * @param url The HDR file url.
  51731. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51732. * @param onError Method called if any error happens during download.
  51733. * @return The packed binary data.
  51734. */
  51735. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51736. if (onError === void 0) { onError = null; }
  51737. var callback = function (buffer) {
  51738. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51739. // Returns a URL you can use as a href.
  51740. var objUrl = window.URL.createObjectURL(data);
  51741. // Simulates a link to it and click to dowload.
  51742. var a = document.createElement("a");
  51743. document.body.appendChild(a);
  51744. a.style.display = "none";
  51745. a.href = objUrl;
  51746. a.download = "envmap.babylon.hdr";
  51747. a.click();
  51748. };
  51749. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51750. };
  51751. /**
  51752. * Serializes the data contained in the texture in a binary format.
  51753. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51754. * as the spherical used in the lighting.
  51755. * @param url The HDR file url.
  51756. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51757. * @param onError Method called if any error happens during download.
  51758. * @return The packed binary data.
  51759. */
  51760. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51761. if (onError === void 0) { onError = null; }
  51762. // Needs the url tho create the texture.
  51763. if (!url) {
  51764. return null;
  51765. }
  51766. // Check Power of two size.
  51767. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51768. return null;
  51769. }
  51770. var getDataCallback = function (dataBuffer) {
  51771. // Extract the raw linear data.
  51772. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51773. // Generate harmonics if needed.
  51774. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51775. // Generate seamless faces
  51776. var mipGeneratorArray = [];
  51777. // Data are known to be in +X +Y +Z -X -Y -Z
  51778. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51779. mipGeneratorArray.push(cubeData.right); // +X
  51780. mipGeneratorArray.push(cubeData.left); // -X
  51781. mipGeneratorArray.push(cubeData.up); // +Y
  51782. mipGeneratorArray.push(cubeData.down); // -Y
  51783. mipGeneratorArray.push(cubeData.front); // +Z
  51784. mipGeneratorArray.push(cubeData.back); // -Z
  51785. // Custom setup of the generator matching with the PBR shader values.
  51786. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51787. var mippedData = generator.filterCubeMap();
  51788. // Compute required byte length.
  51789. var byteLength = 1 * 4; // Raw Data Version int32.
  51790. byteLength += 4; // CubeMap max mip face size int32.
  51791. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  51792. // Add data size.
  51793. byteLength += 4; // Number of mip levels int32.
  51794. for (var level = 0; level < mippedData.length; level++) {
  51795. var mipSize = size >> level;
  51796. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  51797. }
  51798. // Prepare binary structure.
  51799. var buffer = new ArrayBuffer(byteLength);
  51800. var intArrayView = new Int32Array(buffer);
  51801. var floatArrayView = new Float32Array(buffer);
  51802. // Fill header.
  51803. intArrayView[0] = 1; // Version 1.
  51804. intArrayView[1] = size; // CubeMap max mip face size.
  51805. // Fill polynomial information.
  51806. sphericalPolynomial.x.toArray(floatArrayView, 2);
  51807. sphericalPolynomial.y.toArray(floatArrayView, 5);
  51808. sphericalPolynomial.z.toArray(floatArrayView, 8);
  51809. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  51810. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  51811. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  51812. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  51813. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  51814. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  51815. // Fill pixel data.
  51816. intArrayView[29] = mippedData.length; // Number of mip levels.
  51817. var startIndex = 30;
  51818. for (var level = 0; level < mippedData.length; level++) {
  51819. // Fill each pixel of the mip level.
  51820. var faceSize = Math.pow(size >> level, 2) * 3;
  51821. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51822. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  51823. startIndex += faceSize;
  51824. }
  51825. }
  51826. // Callback.
  51827. callback(buffer);
  51828. };
  51829. // Download and process.
  51830. BABYLON.Tools.LoadFile(url, function (data) {
  51831. getDataCallback(data);
  51832. }, null, null, true, onError);
  51833. };
  51834. HDRCubeTexture._facesMapping = [
  51835. "right",
  51836. "up",
  51837. "front",
  51838. "left",
  51839. "down",
  51840. "back"
  51841. ];
  51842. return HDRCubeTexture;
  51843. }(BABYLON.BaseTexture));
  51844. BABYLON.HDRCubeTexture = HDRCubeTexture;
  51845. })(BABYLON || (BABYLON = {}));
  51846. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  51847. var BABYLON;
  51848. (function (BABYLON) {
  51849. var Debug;
  51850. (function (Debug) {
  51851. /**
  51852. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  51853. */
  51854. var SkeletonViewer = (function () {
  51855. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  51856. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  51857. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  51858. this.skeleton = skeleton;
  51859. this.mesh = mesh;
  51860. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  51861. this.renderingGroupId = renderingGroupId;
  51862. this.color = BABYLON.Color3.White();
  51863. this._debugLines = [];
  51864. this._isEnabled = false;
  51865. this._scene = scene;
  51866. this.update();
  51867. this._renderFunction = this.update.bind(this);
  51868. }
  51869. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  51870. get: function () {
  51871. return this._isEnabled;
  51872. },
  51873. set: function (value) {
  51874. if (this._isEnabled === value) {
  51875. return;
  51876. }
  51877. this._isEnabled = value;
  51878. if (value) {
  51879. this._scene.registerBeforeRender(this._renderFunction);
  51880. }
  51881. else {
  51882. this._scene.unregisterBeforeRender(this._renderFunction);
  51883. }
  51884. },
  51885. enumerable: true,
  51886. configurable: true
  51887. });
  51888. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  51889. if (x === void 0) { x = 0; }
  51890. if (y === void 0) { y = 0; }
  51891. if (z === void 0) { z = 0; }
  51892. var tmat = BABYLON.Tmp.Matrix[0];
  51893. var parentBone = bone.getParent();
  51894. tmat.copyFrom(bone.getLocalMatrix());
  51895. if (x !== 0 || y !== 0 || z !== 0) {
  51896. var tmat2 = BABYLON.Tmp.Matrix[1];
  51897. BABYLON.Matrix.IdentityToRef(tmat2);
  51898. tmat2.m[12] = x;
  51899. tmat2.m[13] = y;
  51900. tmat2.m[14] = z;
  51901. tmat2.multiplyToRef(tmat, tmat);
  51902. }
  51903. if (parentBone) {
  51904. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  51905. }
  51906. tmat.multiplyToRef(meshMat, tmat);
  51907. position.x = tmat.m[12];
  51908. position.y = tmat.m[13];
  51909. position.z = tmat.m[14];
  51910. };
  51911. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  51912. var len = bones.length;
  51913. for (var i = 0; i < len; i++) {
  51914. var bone = bones[i];
  51915. var points = this._debugLines[i];
  51916. if (!points) {
  51917. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51918. this._debugLines[i] = points;
  51919. }
  51920. this._getBonePosition(points[0], bone, meshMat);
  51921. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  51922. }
  51923. };
  51924. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  51925. var len = bones.length;
  51926. var boneNum = 0;
  51927. for (var i = len - 1; i >= 0; i--) {
  51928. var childBone = bones[i];
  51929. var parentBone = childBone.getParent();
  51930. if (!parentBone) {
  51931. continue;
  51932. }
  51933. var points = this._debugLines[boneNum];
  51934. if (!points) {
  51935. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51936. this._debugLines[boneNum] = points;
  51937. }
  51938. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  51939. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  51940. boneNum++;
  51941. }
  51942. };
  51943. SkeletonViewer.prototype.update = function () {
  51944. if (this.autoUpdateBonesMatrices) {
  51945. this.skeleton.computeAbsoluteTransforms();
  51946. }
  51947. if (this.skeleton.bones[0].length === undefined) {
  51948. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  51949. }
  51950. else {
  51951. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  51952. }
  51953. if (!this._debugMesh) {
  51954. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  51955. this._debugMesh.renderingGroupId = this.renderingGroupId;
  51956. }
  51957. else {
  51958. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  51959. }
  51960. this._debugMesh.color = this.color;
  51961. };
  51962. SkeletonViewer.prototype.dispose = function () {
  51963. if (this._debugMesh) {
  51964. this.isEnabled = false;
  51965. this._debugMesh.dispose();
  51966. this._debugMesh = null;
  51967. }
  51968. };
  51969. return SkeletonViewer;
  51970. }());
  51971. Debug.SkeletonViewer = SkeletonViewer;
  51972. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  51973. })(BABYLON || (BABYLON = {}));
  51974. //# sourceMappingURL=babylon.skeletonViewer.js.map
  51975. var BABYLON;
  51976. (function (BABYLON) {
  51977. var Debug;
  51978. (function (Debug) {
  51979. var AxesViewer = (function () {
  51980. function AxesViewer(scene, scaleLines) {
  51981. if (scaleLines === void 0) { scaleLines = 1; }
  51982. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51983. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51984. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51985. this.scaleLines = 1;
  51986. this.scaleLines = scaleLines;
  51987. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  51988. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  51989. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  51990. this._xmesh.renderingGroupId = 2;
  51991. this._ymesh.renderingGroupId = 2;
  51992. this._zmesh.renderingGroupId = 2;
  51993. this._xmesh.material.checkReadyOnlyOnce = true;
  51994. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  51995. this._ymesh.material.checkReadyOnlyOnce = true;
  51996. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  51997. this._zmesh.material.checkReadyOnlyOnce = true;
  51998. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  51999. this.scene = scene;
  52000. }
  52001. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  52002. var scaleLines = this.scaleLines;
  52003. var point1 = this._xline[0];
  52004. var point2 = this._xline[1];
  52005. point1.x = position.x;
  52006. point1.y = position.y;
  52007. point1.z = position.z;
  52008. point2.x = point1.x + xaxis.x * scaleLines;
  52009. point2.y = point1.y + xaxis.y * scaleLines;
  52010. point2.z = point1.z + xaxis.z * scaleLines;
  52011. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  52012. point1 = this._yline[0];
  52013. point2 = this._yline[1];
  52014. point1.x = position.x;
  52015. point1.y = position.y;
  52016. point1.z = position.z;
  52017. point2.x = point1.x + yaxis.x * scaleLines;
  52018. point2.y = point1.y + yaxis.y * scaleLines;
  52019. point2.z = point1.z + yaxis.z * scaleLines;
  52020. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  52021. point1 = this._zline[0];
  52022. point2 = this._zline[1];
  52023. point1.x = position.x;
  52024. point1.y = position.y;
  52025. point1.z = position.z;
  52026. point2.x = point1.x + zaxis.x * scaleLines;
  52027. point2.y = point1.y + zaxis.y * scaleLines;
  52028. point2.z = point1.z + zaxis.z * scaleLines;
  52029. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  52030. };
  52031. AxesViewer.prototype.dispose = function () {
  52032. if (this._xmesh) {
  52033. this._xmesh.dispose();
  52034. this._ymesh.dispose();
  52035. this._zmesh.dispose();
  52036. this._xmesh = null;
  52037. this._ymesh = null;
  52038. this._zmesh = null;
  52039. this._xline = null;
  52040. this._yline = null;
  52041. this._zline = null;
  52042. this.scene = null;
  52043. }
  52044. };
  52045. return AxesViewer;
  52046. }());
  52047. Debug.AxesViewer = AxesViewer;
  52048. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52049. })(BABYLON || (BABYLON = {}));
  52050. //# sourceMappingURL=babylon.axesViewer.js.map
  52051. var BABYLON;
  52052. (function (BABYLON) {
  52053. var Debug;
  52054. (function (Debug) {
  52055. var BoneAxesViewer = (function (_super) {
  52056. __extends(BoneAxesViewer, _super);
  52057. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52058. if (scaleLines === void 0) { scaleLines = 1; }
  52059. _super.call(this, scene, scaleLines);
  52060. this.pos = BABYLON.Vector3.Zero();
  52061. this.xaxis = BABYLON.Vector3.Zero();
  52062. this.yaxis = BABYLON.Vector3.Zero();
  52063. this.zaxis = BABYLON.Vector3.Zero();
  52064. this.mesh = mesh;
  52065. this.bone = bone;
  52066. }
  52067. BoneAxesViewer.prototype.update = function () {
  52068. var bone = this.bone;
  52069. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52070. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52071. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52072. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52073. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52074. };
  52075. BoneAxesViewer.prototype.dispose = function () {
  52076. if (this.pos) {
  52077. this.pos = null;
  52078. this.xaxis = null;
  52079. this.yaxis = null;
  52080. this.zaxis = null;
  52081. this.mesh = null;
  52082. this.bone = null;
  52083. _super.prototype.dispose.call(this);
  52084. }
  52085. };
  52086. return BoneAxesViewer;
  52087. }(Debug.AxesViewer));
  52088. Debug.BoneAxesViewer = BoneAxesViewer;
  52089. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52090. })(BABYLON || (BABYLON = {}));
  52091. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52092. var BABYLON;
  52093. (function (BABYLON) {
  52094. /**
  52095. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52096. * It can help converting any input color in a desired output one. This can then be used to create effects
  52097. * from sepia, black and white to sixties or futuristic rendering...
  52098. *
  52099. * The only supported format is currently 3dl.
  52100. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52101. */
  52102. var ColorGradingTexture = (function (_super) {
  52103. __extends(ColorGradingTexture, _super);
  52104. /**
  52105. * Instantiates a ColorGradingTexture from the following parameters.
  52106. *
  52107. * @param url The location of the color gradind data (currently only supporting 3dl)
  52108. * @param scene The scene the texture will be used in
  52109. */
  52110. function ColorGradingTexture(url, scene) {
  52111. _super.call(this, scene);
  52112. if (!url) {
  52113. return;
  52114. }
  52115. this._textureMatrix = BABYLON.Matrix.Identity();
  52116. this.name = url;
  52117. this.url = url;
  52118. this.hasAlpha = false;
  52119. this.isCube = false;
  52120. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52121. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52122. this.anisotropicFilteringLevel = 1;
  52123. this._texture = this._getFromCache(url, true);
  52124. if (!this._texture) {
  52125. if (!scene.useDelayedTextureLoading) {
  52126. this.loadTexture();
  52127. }
  52128. else {
  52129. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52130. }
  52131. }
  52132. }
  52133. /**
  52134. * Returns the texture matrix used in most of the material.
  52135. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52136. */
  52137. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52138. return this._textureMatrix;
  52139. };
  52140. /**
  52141. * Occurs when the file being loaded is a .3dl LUT file.
  52142. */
  52143. ColorGradingTexture.prototype.load3dlTexture = function () {
  52144. var _this = this;
  52145. var mipLevels = 0;
  52146. var floatArrayView = null;
  52147. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52148. this._texture = texture;
  52149. var callback = function (text) {
  52150. var data;
  52151. var tempData;
  52152. var line;
  52153. var lines = text.split('\n');
  52154. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52155. var maxColor = 0;
  52156. for (var i = 0; i < lines.length; i++) {
  52157. line = lines[i];
  52158. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52159. continue;
  52160. if (line.indexOf('#') === 0)
  52161. continue;
  52162. var words = line.split(" ");
  52163. if (size === 0) {
  52164. // Number of space + one
  52165. size = words.length;
  52166. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52167. tempData = new Float32Array(size * size * size * 4);
  52168. continue;
  52169. }
  52170. if (size != 0) {
  52171. var r = Math.max(parseInt(words[0]), 0);
  52172. var g = Math.max(parseInt(words[1]), 0);
  52173. var b = Math.max(parseInt(words[2]), 0);
  52174. maxColor = Math.max(r, maxColor);
  52175. maxColor = Math.max(g, maxColor);
  52176. maxColor = Math.max(b, maxColor);
  52177. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52178. tempData[pixelStorageIndex + 0] = r;
  52179. tempData[pixelStorageIndex + 1] = g;
  52180. tempData[pixelStorageIndex + 2] = b;
  52181. tempData[pixelStorageIndex + 3] = 0;
  52182. pixelIndexSlice++;
  52183. if (pixelIndexSlice % size == 0) {
  52184. pixelIndexH++;
  52185. pixelIndexSlice = 0;
  52186. if (pixelIndexH % size == 0) {
  52187. pixelIndexW++;
  52188. pixelIndexH = 0;
  52189. }
  52190. }
  52191. }
  52192. }
  52193. for (var i = 0; i < tempData.length; i++) {
  52194. var value = tempData[i];
  52195. data[i] = (value / maxColor * 255);
  52196. }
  52197. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52198. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52199. };
  52200. BABYLON.Tools.LoadFile(this.url, callback);
  52201. return this._texture;
  52202. };
  52203. /**
  52204. * Starts the loading process of the texture.
  52205. */
  52206. ColorGradingTexture.prototype.loadTexture = function () {
  52207. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52208. this.load3dlTexture();
  52209. }
  52210. };
  52211. /**
  52212. * Clones the color gradind texture.
  52213. */
  52214. ColorGradingTexture.prototype.clone = function () {
  52215. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52216. // Base texture
  52217. newTexture.level = this.level;
  52218. return newTexture;
  52219. };
  52220. /**
  52221. * Called during delayed load for textures.
  52222. */
  52223. ColorGradingTexture.prototype.delayLoad = function () {
  52224. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52225. return;
  52226. }
  52227. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52228. this._texture = this._getFromCache(this.url, true);
  52229. if (!this._texture) {
  52230. this.loadTexture();
  52231. }
  52232. };
  52233. /**
  52234. * Binds the color grading to the shader.
  52235. * @param colorGrading The texture to bind
  52236. * @param effect The effect to bind to
  52237. */
  52238. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52239. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52240. var x = colorGrading.level; // Texture Level
  52241. var y = colorGrading.getSize().height; // Texture Size example with 8
  52242. var z = y - 1.0; // SizeMinusOne 8 - 1
  52243. var w = 1 / y; // Space of 1 slice 1 / 8
  52244. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  52245. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  52246. 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
  52247. 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
  52248. 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
  52249. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  52250. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  52251. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  52252. };
  52253. /**
  52254. * Prepare the list of uniforms associated with the ColorGrading effects.
  52255. * @param uniformsList The list of uniforms used in the effect
  52256. * @param samplersList The list of samplers used in the effect
  52257. */
  52258. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  52259. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  52260. samplersList.push("cameraColorGrading2DSampler");
  52261. };
  52262. /**
  52263. * Parses a color grading texture serialized by Babylon.
  52264. * @param parsedTexture The texture information being parsedTexture
  52265. * @param scene The scene to load the texture in
  52266. * @param rootUrl The root url of the data assets to load
  52267. * @return A color gradind texture
  52268. */
  52269. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52270. var texture = null;
  52271. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52272. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  52273. texture.name = parsedTexture.name;
  52274. texture.level = parsedTexture.level;
  52275. }
  52276. return texture;
  52277. };
  52278. /**
  52279. * Serializes the LUT texture to json format.
  52280. */
  52281. ColorGradingTexture.prototype.serialize = function () {
  52282. if (!this.name) {
  52283. return null;
  52284. }
  52285. var serializationObject = {};
  52286. serializationObject.name = this.name;
  52287. serializationObject.level = this.level;
  52288. serializationObject.customType = "BABYLON.ColorGradingTexture";
  52289. return serializationObject;
  52290. };
  52291. /**
  52292. * Empty line regex stored for GC.
  52293. */
  52294. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  52295. return ColorGradingTexture;
  52296. }(BABYLON.BaseTexture));
  52297. BABYLON.ColorGradingTexture = ColorGradingTexture;
  52298. })(BABYLON || (BABYLON = {}));
  52299. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  52300. var BABYLON;
  52301. (function (BABYLON) {
  52302. /**
  52303. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52304. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52305. * 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;
  52306. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52307. */
  52308. var ColorCurves = (function () {
  52309. function ColorCurves() {
  52310. this._dirty = true;
  52311. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  52312. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  52313. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52314. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  52315. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52316. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  52317. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  52318. this._globalHue = 30;
  52319. this._globalDensity = 0;
  52320. this._globalSaturation = 0;
  52321. this._globalExposure = 0;
  52322. this._highlightsHue = 30;
  52323. this._highlightsDensity = 0;
  52324. this._highlightsSaturation = 0;
  52325. this._highlightsExposure = 0;
  52326. this._midtonesHue = 30;
  52327. this._midtonesDensity = 0;
  52328. this._midtonesSaturation = 0;
  52329. this._midtonesExposure = 0;
  52330. this._shadowsHue = 30;
  52331. this._shadowsDensity = 0;
  52332. this._shadowsSaturation = 0;
  52333. this._shadowsExposure = 0;
  52334. }
  52335. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  52336. /**
  52337. * Gets the global Hue value.
  52338. * 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).
  52339. */
  52340. get: function () {
  52341. return this._globalHue;
  52342. },
  52343. /**
  52344. * Sets the global Hue value.
  52345. * 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).
  52346. */
  52347. set: function (value) {
  52348. this._globalHue = value;
  52349. this._dirty = true;
  52350. },
  52351. enumerable: true,
  52352. configurable: true
  52353. });
  52354. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  52355. /**
  52356. * Gets the global Density value.
  52357. * 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.
  52358. * Values less than zero provide a filter of opposite hue.
  52359. */
  52360. get: function () {
  52361. return this._globalDensity;
  52362. },
  52363. /**
  52364. * Sets the global Density value.
  52365. * 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.
  52366. * Values less than zero provide a filter of opposite hue.
  52367. */
  52368. set: function (value) {
  52369. this._globalDensity = value;
  52370. this._dirty = true;
  52371. },
  52372. enumerable: true,
  52373. configurable: true
  52374. });
  52375. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  52376. /**
  52377. * Gets the global Saturation value.
  52378. * 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.
  52379. */
  52380. get: function () {
  52381. return this._globalSaturation;
  52382. },
  52383. /**
  52384. * Sets the global Saturation value.
  52385. * 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.
  52386. */
  52387. set: function (value) {
  52388. this._globalSaturation = value;
  52389. this._dirty = true;
  52390. },
  52391. enumerable: true,
  52392. configurable: true
  52393. });
  52394. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  52395. /**
  52396. * Gets the highlights Hue value.
  52397. * 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).
  52398. */
  52399. get: function () {
  52400. return this._highlightsHue;
  52401. },
  52402. /**
  52403. * Sets the highlights Hue value.
  52404. * 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).
  52405. */
  52406. set: function (value) {
  52407. this._highlightsHue = value;
  52408. this._dirty = true;
  52409. },
  52410. enumerable: true,
  52411. configurable: true
  52412. });
  52413. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  52414. /**
  52415. * Gets the highlights Density value.
  52416. * 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.
  52417. * Values less than zero provide a filter of opposite hue.
  52418. */
  52419. get: function () {
  52420. return this._highlightsDensity;
  52421. },
  52422. /**
  52423. * Sets the highlights Density value.
  52424. * 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.
  52425. * Values less than zero provide a filter of opposite hue.
  52426. */
  52427. set: function (value) {
  52428. this._highlightsDensity = value;
  52429. this._dirty = true;
  52430. },
  52431. enumerable: true,
  52432. configurable: true
  52433. });
  52434. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  52435. /**
  52436. * Gets the highlights Saturation value.
  52437. * 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.
  52438. */
  52439. get: function () {
  52440. return this._highlightsSaturation;
  52441. },
  52442. /**
  52443. * Sets the highlights Saturation value.
  52444. * 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.
  52445. */
  52446. set: function (value) {
  52447. this._highlightsSaturation = value;
  52448. this._dirty = true;
  52449. },
  52450. enumerable: true,
  52451. configurable: true
  52452. });
  52453. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  52454. /**
  52455. * Gets the highlights Exposure value.
  52456. * 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.
  52457. */
  52458. get: function () {
  52459. return this._highlightsExposure;
  52460. },
  52461. /**
  52462. * Sets the highlights Exposure value.
  52463. * 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.
  52464. */
  52465. set: function (value) {
  52466. this._highlightsExposure = value;
  52467. this._dirty = true;
  52468. },
  52469. enumerable: true,
  52470. configurable: true
  52471. });
  52472. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  52473. /**
  52474. * Gets the midtones Hue value.
  52475. * 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).
  52476. */
  52477. get: function () {
  52478. return this._midtonesHue;
  52479. },
  52480. /**
  52481. * Sets the midtones Hue value.
  52482. * 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).
  52483. */
  52484. set: function (value) {
  52485. this._midtonesHue = value;
  52486. this._dirty = true;
  52487. },
  52488. enumerable: true,
  52489. configurable: true
  52490. });
  52491. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  52492. /**
  52493. * Gets the midtones Density value.
  52494. * 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.
  52495. * Values less than zero provide a filter of opposite hue.
  52496. */
  52497. get: function () {
  52498. return this._midtonesDensity;
  52499. },
  52500. /**
  52501. * Sets the midtones Density value.
  52502. * 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.
  52503. * Values less than zero provide a filter of opposite hue.
  52504. */
  52505. set: function (value) {
  52506. this._midtonesDensity = value;
  52507. this._dirty = true;
  52508. },
  52509. enumerable: true,
  52510. configurable: true
  52511. });
  52512. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  52513. /**
  52514. * Gets the midtones Saturation value.
  52515. * 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.
  52516. */
  52517. get: function () {
  52518. return this._midtonesSaturation;
  52519. },
  52520. /**
  52521. * Sets the midtones Saturation value.
  52522. * 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.
  52523. */
  52524. set: function (value) {
  52525. this._midtonesSaturation = value;
  52526. this._dirty = true;
  52527. },
  52528. enumerable: true,
  52529. configurable: true
  52530. });
  52531. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  52532. /**
  52533. * Gets the midtones Exposure value.
  52534. * 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.
  52535. */
  52536. get: function () {
  52537. return this._midtonesExposure;
  52538. },
  52539. /**
  52540. * Sets the midtones Exposure value.
  52541. * 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.
  52542. */
  52543. set: function (value) {
  52544. this._midtonesExposure = value;
  52545. this._dirty = true;
  52546. },
  52547. enumerable: true,
  52548. configurable: true
  52549. });
  52550. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  52551. /**
  52552. * Gets the shadows Hue value.
  52553. * 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).
  52554. */
  52555. get: function () {
  52556. return this._shadowsHue;
  52557. },
  52558. /**
  52559. * Sets the shadows Hue value.
  52560. * 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).
  52561. */
  52562. set: function (value) {
  52563. this._shadowsHue = value;
  52564. this._dirty = true;
  52565. },
  52566. enumerable: true,
  52567. configurable: true
  52568. });
  52569. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  52570. /**
  52571. * Gets the shadows Density value.
  52572. * 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.
  52573. * Values less than zero provide a filter of opposite hue.
  52574. */
  52575. get: function () {
  52576. return this._shadowsDensity;
  52577. },
  52578. /**
  52579. * Sets the shadows Density value.
  52580. * 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.
  52581. * Values less than zero provide a filter of opposite hue.
  52582. */
  52583. set: function (value) {
  52584. this._shadowsDensity = value;
  52585. this._dirty = true;
  52586. },
  52587. enumerable: true,
  52588. configurable: true
  52589. });
  52590. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  52591. /**
  52592. * Gets the shadows Saturation value.
  52593. * 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.
  52594. */
  52595. get: function () {
  52596. return this._shadowsSaturation;
  52597. },
  52598. /**
  52599. * Sets the shadows Saturation value.
  52600. * 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.
  52601. */
  52602. set: function (value) {
  52603. this._shadowsSaturation = value;
  52604. this._dirty = true;
  52605. },
  52606. enumerable: true,
  52607. configurable: true
  52608. });
  52609. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  52610. /**
  52611. * Gets the shadows Exposure value.
  52612. * 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.
  52613. */
  52614. get: function () {
  52615. return this._shadowsExposure;
  52616. },
  52617. /**
  52618. * Sets the shadows Exposure value.
  52619. * 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.
  52620. */
  52621. set: function (value) {
  52622. this._shadowsExposure = value;
  52623. this._dirty = true;
  52624. },
  52625. enumerable: true,
  52626. configurable: true
  52627. });
  52628. /**
  52629. * Binds the color curves to the shader.
  52630. * @param colorCurves The color curve to bind
  52631. * @param effect The effect to bind to
  52632. */
  52633. ColorCurves.Bind = function (colorCurves, effect) {
  52634. if (colorCurves._dirty) {
  52635. colorCurves._dirty = false;
  52636. // Fill in global info.
  52637. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  52638. // Compute highlights info.
  52639. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  52640. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  52641. // Compute midtones info.
  52642. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  52643. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  52644. // Compute shadows info.
  52645. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  52646. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  52647. // Compute deltas (neutral is midtones).
  52648. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  52649. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  52650. }
  52651. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  52652. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  52653. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  52654. };
  52655. /**
  52656. * Prepare the list of uniforms associated with the ColorCurves effects.
  52657. * @param uniformsList The list of uniforms used in the effect
  52658. */
  52659. ColorCurves.PrepareUniforms = function (uniformsList) {
  52660. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  52661. };
  52662. /**
  52663. * Returns color grading data based on a hue, density, saturation and exposure value.
  52664. * @param filterHue The hue of the color filter.
  52665. * @param filterDensity The density of the color filter.
  52666. * @param saturation The saturation.
  52667. * @param exposure The exposure.
  52668. * @param result The result data container.
  52669. */
  52670. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  52671. if (hue == null) {
  52672. return;
  52673. }
  52674. hue = ColorCurves.clamp(hue, 0, 360);
  52675. density = ColorCurves.clamp(density, -100, 100);
  52676. saturation = ColorCurves.clamp(saturation, -100, 100);
  52677. exposure = ColorCurves.clamp(exposure, -100, 100);
  52678. // Remap the slider/config filter density with non-linear mapping and also scale by half
  52679. // so that the maximum filter density is only 50% control. This provides fine control
  52680. // for small values and reasonable range.
  52681. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  52682. density *= 0.5;
  52683. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  52684. if (density < 0) {
  52685. density *= -1;
  52686. hue = (hue + 180) % 360;
  52687. }
  52688. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  52689. result.scaleToRef(2, result);
  52690. result.a = 1 + 0.01 * saturation;
  52691. };
  52692. /**
  52693. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  52694. * @param value The input slider value in range [-100,100].
  52695. * @returns Adjusted value.
  52696. */
  52697. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  52698. value /= 100;
  52699. var x = Math.abs(value);
  52700. x = Math.pow(x, 2);
  52701. if (value < 0) {
  52702. x *= -1;
  52703. }
  52704. x *= 100;
  52705. return x;
  52706. };
  52707. /**
  52708. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  52709. * @param hue The hue (H) input.
  52710. * @param saturation The saturation (S) input.
  52711. * @param brightness The brightness (B) input.
  52712. * @result An RGBA color represented as Vector4.
  52713. */
  52714. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  52715. var h = ColorCurves.clamp(hue, 0, 360);
  52716. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  52717. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  52718. if (s === 0) {
  52719. result.r = v;
  52720. result.g = v;
  52721. result.b = v;
  52722. }
  52723. else {
  52724. // sector 0 to 5
  52725. h /= 60;
  52726. var i = Math.floor(h);
  52727. // fractional part of h
  52728. var f = h - i;
  52729. var p = v * (1 - s);
  52730. var q = v * (1 - s * f);
  52731. var t = v * (1 - s * (1 - f));
  52732. switch (i) {
  52733. case 0:
  52734. result.r = v;
  52735. result.g = t;
  52736. result.b = p;
  52737. break;
  52738. case 1:
  52739. result.r = q;
  52740. result.g = v;
  52741. result.b = p;
  52742. break;
  52743. case 2:
  52744. result.r = p;
  52745. result.g = v;
  52746. result.b = t;
  52747. break;
  52748. case 3:
  52749. result.r = p;
  52750. result.g = q;
  52751. result.b = v;
  52752. break;
  52753. case 4:
  52754. result.r = t;
  52755. result.g = p;
  52756. result.b = v;
  52757. break;
  52758. default:
  52759. result.r = v;
  52760. result.g = p;
  52761. result.b = q;
  52762. break;
  52763. }
  52764. }
  52765. result.a = 1;
  52766. };
  52767. /**
  52768. * Returns a value clamped between min and max
  52769. * @param value The value to clamp
  52770. * @param min The minimum of value
  52771. * @param max The maximum of value
  52772. * @returns The clamped value.
  52773. */
  52774. ColorCurves.clamp = function (value, min, max) {
  52775. return Math.min(Math.max(value, min), max);
  52776. };
  52777. /**
  52778. * Clones the current color curve instance.
  52779. * @return The cloned curves
  52780. */
  52781. ColorCurves.prototype.clone = function () {
  52782. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  52783. };
  52784. /**
  52785. * Serializes the current color curve instance to a json representation.
  52786. * @return a JSON representation
  52787. */
  52788. ColorCurves.prototype.serialize = function () {
  52789. return BABYLON.SerializationHelper.Serialize(this);
  52790. };
  52791. /**
  52792. * Parses the color curve from a json representation.
  52793. * @param source the JSON source to parse
  52794. * @return The parsed curves
  52795. */
  52796. ColorCurves.Parse = function (source) {
  52797. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  52798. };
  52799. __decorate([
  52800. BABYLON.serialize()
  52801. ], ColorCurves.prototype, "_globalHue", void 0);
  52802. __decorate([
  52803. BABYLON.serialize()
  52804. ], ColorCurves.prototype, "_globalDensity", void 0);
  52805. __decorate([
  52806. BABYLON.serialize()
  52807. ], ColorCurves.prototype, "_globalSaturation", void 0);
  52808. __decorate([
  52809. BABYLON.serialize()
  52810. ], ColorCurves.prototype, "_globalExposure", void 0);
  52811. __decorate([
  52812. BABYLON.serialize()
  52813. ], ColorCurves.prototype, "_highlightsHue", void 0);
  52814. __decorate([
  52815. BABYLON.serialize()
  52816. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  52817. __decorate([
  52818. BABYLON.serialize()
  52819. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  52820. __decorate([
  52821. BABYLON.serialize()
  52822. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  52823. __decorate([
  52824. BABYLON.serialize()
  52825. ], ColorCurves.prototype, "_midtonesHue", void 0);
  52826. __decorate([
  52827. BABYLON.serialize()
  52828. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  52829. __decorate([
  52830. BABYLON.serialize()
  52831. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  52832. __decorate([
  52833. BABYLON.serialize()
  52834. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  52835. return ColorCurves;
  52836. }());
  52837. BABYLON.ColorCurves = ColorCurves;
  52838. })(BABYLON || (BABYLON = {}));
  52839. //# sourceMappingURL=babylon.colorCurves.js.map
  52840. var BABYLON;
  52841. (function (BABYLON) {
  52842. var PBRMaterialDefines = (function (_super) {
  52843. __extends(PBRMaterialDefines, _super);
  52844. function PBRMaterialDefines() {
  52845. _super.call(this);
  52846. this.ALBEDO = false;
  52847. this.AMBIENT = false;
  52848. this.OPACITY = false;
  52849. this.OPACITYRGB = false;
  52850. this.REFLECTION = false;
  52851. this.EMISSIVE = false;
  52852. this.REFLECTIVITY = false;
  52853. this.BUMP = false;
  52854. this.PARALLAX = false;
  52855. this.PARALLAXOCCLUSION = false;
  52856. this.SPECULAROVERALPHA = false;
  52857. this.CLIPPLANE = false;
  52858. this.ALPHATEST = false;
  52859. this.ALPHAFROMALBEDO = false;
  52860. this.POINTSIZE = false;
  52861. this.FOG = false;
  52862. this.SPECULARTERM = false;
  52863. this.OPACITYFRESNEL = false;
  52864. this.EMISSIVEFRESNEL = false;
  52865. this.FRESNEL = false;
  52866. this.NORMAL = false;
  52867. this.UV1 = false;
  52868. this.UV2 = false;
  52869. this.VERTEXCOLOR = false;
  52870. this.VERTEXALPHA = false;
  52871. this.NUM_BONE_INFLUENCERS = 0;
  52872. this.BonesPerMesh = 0;
  52873. this.INSTANCES = false;
  52874. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  52875. this.MICROSURFACEAUTOMATIC = false;
  52876. this.EMISSIVEASILLUMINATION = false;
  52877. this.LINKEMISSIVEWITHALBEDO = false;
  52878. this.LIGHTMAP = false;
  52879. this.USELIGHTMAPASSHADOWMAP = false;
  52880. this.REFLECTIONMAP_3D = false;
  52881. this.REFLECTIONMAP_SPHERICAL = false;
  52882. this.REFLECTIONMAP_PLANAR = false;
  52883. this.REFLECTIONMAP_CUBIC = false;
  52884. this.REFLECTIONMAP_PROJECTION = false;
  52885. this.REFLECTIONMAP_SKYBOX = false;
  52886. this.REFLECTIONMAP_EXPLICIT = false;
  52887. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  52888. this.INVERTCUBICMAP = false;
  52889. this.LOGARITHMICDEPTH = false;
  52890. this.CAMERATONEMAP = false;
  52891. this.CAMERACONTRAST = false;
  52892. this.CAMERACOLORGRADING = false;
  52893. this.CAMERACOLORCURVES = false;
  52894. this.OVERLOADEDVALUES = false;
  52895. this.OVERLOADEDSHADOWVALUES = false;
  52896. this.USESPHERICALFROMREFLECTIONMAP = false;
  52897. this.REFRACTION = false;
  52898. this.REFRACTIONMAP_3D = false;
  52899. this.LINKREFRACTIONTOTRANSPARENCY = false;
  52900. this.REFRACTIONMAPINLINEARSPACE = false;
  52901. this.LODBASEDMICROSFURACE = false;
  52902. this.USEPHYSICALLIGHTFALLOFF = false;
  52903. this.RADIANCEOVERALPHA = false;
  52904. this.USEPMREMREFLECTION = false;
  52905. this.USEPMREMREFRACTION = false;
  52906. this.OPENGLNORMALMAP = false;
  52907. this.INVERTNORMALMAPX = false;
  52908. this.INVERTNORMALMAPY = false;
  52909. this.SHADOWFULLFLOAT = false;
  52910. this.METALLICWORKFLOW = false;
  52911. this.METALLICROUGHNESSGSTOREINALPHA = false;
  52912. this.METALLICROUGHNESSGSTOREINGREEN = false;
  52913. this.rebuild();
  52914. }
  52915. return PBRMaterialDefines;
  52916. }(BABYLON.MaterialDefines));
  52917. /**
  52918. * The Physically based material of BJS.
  52919. *
  52920. * This offers the main features of a standard PBR material.
  52921. * For more information, please refer to the documentation :
  52922. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  52923. */
  52924. var PBRMaterial = (function (_super) {
  52925. __extends(PBRMaterial, _super);
  52926. /**
  52927. * Instantiates a new PBRMaterial instance.
  52928. *
  52929. * @param name The material name
  52930. * @param scene The scene the material will be use in.
  52931. */
  52932. function PBRMaterial(name, scene) {
  52933. var _this = this;
  52934. _super.call(this, name, scene);
  52935. /**
  52936. * Intensity of the direct lights e.g. the four lights available in your scene.
  52937. * This impacts both the direct diffuse and specular highlights.
  52938. */
  52939. this.directIntensity = 1.0;
  52940. /**
  52941. * Intensity of the emissive part of the material.
  52942. * This helps controlling the emissive effect without modifying the emissive color.
  52943. */
  52944. this.emissiveIntensity = 1.0;
  52945. /**
  52946. * Intensity of the environment e.g. how much the environment will light the object
  52947. * either through harmonics for rough material or through the refelction for shiny ones.
  52948. */
  52949. this.environmentIntensity = 1.0;
  52950. /**
  52951. * This is a special control allowing the reduction of the specular highlights coming from the
  52952. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  52953. */
  52954. this.specularIntensity = 1.0;
  52955. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  52956. /**
  52957. * Debug Control allowing disabling the bump map on this material.
  52958. */
  52959. this.disableBumpMap = false;
  52960. /**
  52961. * Debug Control helping enforcing or dropping the darkness of shadows.
  52962. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  52963. */
  52964. this.overloadedShadowIntensity = 1.0;
  52965. /**
  52966. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  52967. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  52968. */
  52969. this.overloadedShadeIntensity = 1.0;
  52970. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  52971. /**
  52972. * The camera exposure used on this material.
  52973. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  52974. * This corresponds to a photographic exposure.
  52975. */
  52976. this.cameraExposure = 1.0;
  52977. /**
  52978. * The camera contrast used on this material.
  52979. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  52980. */
  52981. this.cameraContrast = 1.0;
  52982. /**
  52983. * Color Grading 2D Lookup Texture.
  52984. * This allows special effects like sepia, black and white to sixties rendering style.
  52985. */
  52986. this.cameraColorGradingTexture = null;
  52987. /**
  52988. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52989. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52990. * 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;
  52991. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52992. */
  52993. this.cameraColorCurves = null;
  52994. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  52995. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  52996. /**
  52997. * Debug Control allowing to overload the ambient color.
  52998. * This as to be use with the overloadedAmbientIntensity parameter.
  52999. */
  53000. this.overloadedAmbient = BABYLON.Color3.White();
  53001. /**
  53002. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  53003. */
  53004. this.overloadedAmbientIntensity = 0.0;
  53005. /**
  53006. * Debug Control allowing to overload the albedo color.
  53007. * This as to be use with the overloadedAlbedoIntensity parameter.
  53008. */
  53009. this.overloadedAlbedo = BABYLON.Color3.White();
  53010. /**
  53011. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  53012. */
  53013. this.overloadedAlbedoIntensity = 0.0;
  53014. /**
  53015. * Debug Control allowing to overload the reflectivity color.
  53016. * This as to be use with the overloadedReflectivityIntensity parameter.
  53017. */
  53018. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  53019. /**
  53020. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  53021. */
  53022. this.overloadedReflectivityIntensity = 0.0;
  53023. /**
  53024. * Debug Control allowing to overload the emissive color.
  53025. * This as to be use with the overloadedEmissiveIntensity parameter.
  53026. */
  53027. this.overloadedEmissive = BABYLON.Color3.White();
  53028. /**
  53029. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  53030. */
  53031. this.overloadedEmissiveIntensity = 0.0;
  53032. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  53033. /**
  53034. * Debug Control allowing to overload the reflection color.
  53035. * This as to be use with the overloadedReflectionIntensity parameter.
  53036. */
  53037. this.overloadedReflection = BABYLON.Color3.White();
  53038. /**
  53039. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  53040. */
  53041. this.overloadedReflectionIntensity = 0.0;
  53042. /**
  53043. * Debug Control allowing to overload the microsurface.
  53044. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53045. */
  53046. this.overloadedMicroSurface = 0.0;
  53047. /**
  53048. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53049. */
  53050. this.overloadedMicroSurfaceIntensity = 0.0;
  53051. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  53052. /**
  53053. * AKA Occlusion Texture Intensity in other nomenclature.
  53054. */
  53055. this.ambientTextureStrength = 1.0;
  53056. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53057. /**
  53058. * AKA Diffuse Color in other nomenclature.
  53059. */
  53060. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53061. /**
  53062. * AKA Specular Color in other nomenclature.
  53063. */
  53064. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53065. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53066. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53067. /**
  53068. * AKA Glossiness in other nomenclature.
  53069. */
  53070. this.microSurface = 0.9;
  53071. /**
  53072. * source material index of refraction (IOR)' / 'destination material IOR.
  53073. */
  53074. this.indexOfRefraction = 0.66;
  53075. /**
  53076. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53077. */
  53078. this.invertRefractionY = false;
  53079. /**
  53080. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53081. * Materials half opaque for instance using refraction could benefit from this control.
  53082. */
  53083. this.linkRefractionWithTransparency = false;
  53084. /**
  53085. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53086. */
  53087. this.linkEmissiveWithAlbedo = false;
  53088. this.useLightmapAsShadowmap = false;
  53089. /**
  53090. * In this mode, the emissive informtaion will always be added to the lighting once.
  53091. * A light for instance can be thought as emissive.
  53092. */
  53093. this.useEmissiveAsIllumination = false;
  53094. /**
  53095. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53096. */
  53097. this.useAlphaFromAlbedoTexture = false;
  53098. /**
  53099. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53100. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53101. */
  53102. this.useSpecularOverAlpha = true;
  53103. /**
  53104. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53105. */
  53106. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53107. /**
  53108. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  53109. */
  53110. this.useRoughnessFromMetallicTextureAlpha = true;
  53111. /**
  53112. * Specifies if the metallic texture contains the roughness information in its green channel.
  53113. */
  53114. this.useRoughnessFromMetallicTextureGreen = false;
  53115. /**
  53116. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53117. * The material will try to infer what glossiness each pixel should be.
  53118. */
  53119. this.useAutoMicroSurfaceFromReflectivityMap = false;
  53120. /**
  53121. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53122. * the creation of the material.
  53123. */
  53124. this.useScalarInLinearSpace = false;
  53125. /**
  53126. * BJS is using an harcoded light falloff based on a manually sets up range.
  53127. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53128. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53129. */
  53130. this.usePhysicalLightFalloff = true;
  53131. /**
  53132. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53133. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53134. */
  53135. this.useRadianceOverAlpha = true;
  53136. /**
  53137. * Allows using the bump map in parallax mode.
  53138. */
  53139. this.useParallax = false;
  53140. /**
  53141. * Allows using the bump map in parallax occlusion mode.
  53142. */
  53143. this.useParallaxOcclusion = false;
  53144. /**
  53145. * Controls the scale bias of the parallax mode.
  53146. */
  53147. this.parallaxScaleBias = 0.05;
  53148. /**
  53149. * If sets to true, disables all the lights affecting the material.
  53150. */
  53151. this.disableLighting = false;
  53152. /**
  53153. * Number of Simultaneous lights allowed on the material.
  53154. */
  53155. this.maxSimultaneousLights = 4;
  53156. /**
  53157. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53158. */
  53159. this.invertNormalMapX = false;
  53160. /**
  53161. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53162. */
  53163. this.invertNormalMapY = false;
  53164. this._renderTargets = new BABYLON.SmartArray(16);
  53165. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53166. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53167. this._tempColor = new BABYLON.Color3();
  53168. this._defines = new PBRMaterialDefines();
  53169. this._cachedDefines = new PBRMaterialDefines();
  53170. this._myScene = null;
  53171. this._myShadowGenerator = null;
  53172. this._cachedDefines.BonesPerMesh = -1;
  53173. this.getRenderTargetTextures = function () {
  53174. _this._renderTargets.reset();
  53175. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53176. _this._renderTargets.push(_this.reflectionTexture);
  53177. }
  53178. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53179. _this._renderTargets.push(_this.refractionTexture);
  53180. }
  53181. return _this._renderTargets;
  53182. };
  53183. }
  53184. PBRMaterial.prototype.getClassName = function () {
  53185. return "PBRMaterial";
  53186. };
  53187. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53188. get: function () {
  53189. return this._useLogarithmicDepth;
  53190. },
  53191. set: function (value) {
  53192. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53193. },
  53194. enumerable: true,
  53195. configurable: true
  53196. });
  53197. PBRMaterial.prototype.needAlphaBlending = function () {
  53198. if (this.linkRefractionWithTransparency) {
  53199. return false;
  53200. }
  53201. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53202. };
  53203. PBRMaterial.prototype.needAlphaTesting = function () {
  53204. if (this.linkRefractionWithTransparency) {
  53205. return false;
  53206. }
  53207. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53208. };
  53209. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53210. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53211. };
  53212. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53213. return this.albedoTexture;
  53214. };
  53215. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53216. if (!mesh) {
  53217. return true;
  53218. }
  53219. if (this._defines.INSTANCES !== useInstances) {
  53220. return false;
  53221. }
  53222. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53223. return true;
  53224. }
  53225. return false;
  53226. };
  53227. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53228. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53229. };
  53230. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53231. if (!useScalarInLinear) {
  53232. color.toLinearSpaceToRef(ref);
  53233. }
  53234. else {
  53235. ref.r = color.r;
  53236. ref.g = color.g;
  53237. ref.b = color.b;
  53238. }
  53239. };
  53240. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53241. var lightIndex = 0;
  53242. var depthValuesAlreadySet = false;
  53243. for (var index = 0; index < scene.lights.length; index++) {
  53244. var light = scene.lights[index];
  53245. if (!light.isEnabled()) {
  53246. continue;
  53247. }
  53248. if (!light.canAffectMesh(mesh)) {
  53249. continue;
  53250. }
  53251. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  53252. // GAMMA CORRECTION.
  53253. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  53254. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  53255. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  53256. if (defines["SPECULARTERM"]) {
  53257. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  53258. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  53259. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  53260. }
  53261. // Shadows
  53262. if (scene.shadowsEnabled) {
  53263. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  53264. }
  53265. lightIndex++;
  53266. if (lightIndex === maxSimultaneousLights)
  53267. break;
  53268. }
  53269. };
  53270. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  53271. if (this.checkReadyOnlyOnce) {
  53272. if (this._wasPreviouslyReady) {
  53273. return true;
  53274. }
  53275. }
  53276. var scene = this.getScene();
  53277. var engine = scene.getEngine();
  53278. var needNormals = false;
  53279. var needUVs = false;
  53280. this._defines.reset();
  53281. if (scene.lightsEnabled && !this.disableLighting) {
  53282. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  53283. }
  53284. if (!this.checkReadyOnEveryCall) {
  53285. if (this._renderId === scene.getRenderId()) {
  53286. if (this._checkCache(scene, mesh, useInstances)) {
  53287. return true;
  53288. }
  53289. }
  53290. }
  53291. if (scene.texturesEnabled) {
  53292. if (scene.getEngine().getCaps().textureLOD) {
  53293. this._defines.LODBASEDMICROSFURACE = true;
  53294. }
  53295. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53296. if (!this.albedoTexture.isReady()) {
  53297. return false;
  53298. }
  53299. else {
  53300. needUVs = true;
  53301. this._defines.ALBEDO = true;
  53302. }
  53303. }
  53304. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53305. if (!this.ambientTexture.isReady()) {
  53306. return false;
  53307. }
  53308. else {
  53309. needUVs = true;
  53310. this._defines.AMBIENT = true;
  53311. }
  53312. }
  53313. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53314. if (!this.opacityTexture.isReady()) {
  53315. return false;
  53316. }
  53317. else {
  53318. needUVs = true;
  53319. this._defines.OPACITY = true;
  53320. if (this.opacityTexture.getAlphaFromRGB) {
  53321. this._defines.OPACITYRGB = true;
  53322. }
  53323. }
  53324. }
  53325. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53326. if (!this.reflectionTexture.isReady()) {
  53327. return false;
  53328. }
  53329. else {
  53330. needNormals = true;
  53331. this._defines.REFLECTION = true;
  53332. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  53333. this._defines.INVERTCUBICMAP = true;
  53334. }
  53335. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  53336. switch (this.reflectionTexture.coordinatesMode) {
  53337. case BABYLON.Texture.CUBIC_MODE:
  53338. case BABYLON.Texture.INVCUBIC_MODE:
  53339. this._defines.REFLECTIONMAP_CUBIC = true;
  53340. break;
  53341. case BABYLON.Texture.EXPLICIT_MODE:
  53342. this._defines.REFLECTIONMAP_EXPLICIT = true;
  53343. break;
  53344. case BABYLON.Texture.PLANAR_MODE:
  53345. this._defines.REFLECTIONMAP_PLANAR = true;
  53346. break;
  53347. case BABYLON.Texture.PROJECTION_MODE:
  53348. this._defines.REFLECTIONMAP_PROJECTION = true;
  53349. break;
  53350. case BABYLON.Texture.SKYBOX_MODE:
  53351. this._defines.REFLECTIONMAP_SKYBOX = true;
  53352. break;
  53353. case BABYLON.Texture.SPHERICAL_MODE:
  53354. this._defines.REFLECTIONMAP_SPHERICAL = true;
  53355. break;
  53356. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  53357. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  53358. break;
  53359. }
  53360. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  53361. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  53362. needNormals = true;
  53363. if (this.reflectionTexture.isPMREM) {
  53364. this._defines.USEPMREMREFLECTION = true;
  53365. }
  53366. }
  53367. }
  53368. }
  53369. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53370. if (!this.lightmapTexture.isReady()) {
  53371. return false;
  53372. }
  53373. else {
  53374. needUVs = true;
  53375. this._defines.LIGHTMAP = true;
  53376. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  53377. }
  53378. }
  53379. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53380. if (!this.emissiveTexture.isReady()) {
  53381. return false;
  53382. }
  53383. else {
  53384. needUVs = true;
  53385. this._defines.EMISSIVE = true;
  53386. }
  53387. }
  53388. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53389. if (this.metallicTexture) {
  53390. if (!this.metallicTexture.isReady()) {
  53391. return false;
  53392. }
  53393. else {
  53394. needUVs = true;
  53395. this._defines.METALLICWORKFLOW = true;
  53396. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  53397. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  53398. }
  53399. }
  53400. else if (this.reflectivityTexture) {
  53401. if (!this.reflectivityTexture.isReady()) {
  53402. return false;
  53403. }
  53404. else {
  53405. needUVs = true;
  53406. this._defines.REFLECTIVITY = true;
  53407. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  53408. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  53409. }
  53410. }
  53411. }
  53412. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53413. if (!this.bumpTexture.isReady()) {
  53414. return false;
  53415. }
  53416. else {
  53417. needUVs = true;
  53418. this._defines.BUMP = true;
  53419. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53420. this._defines.PARALLAX = true;
  53421. if (this.useParallaxOcclusion) {
  53422. this._defines.PARALLAXOCCLUSION = true;
  53423. }
  53424. }
  53425. if (this.invertNormalMapX) {
  53426. this._defines.INVERTNORMALMAPX = true;
  53427. }
  53428. if (this.invertNormalMapY) {
  53429. this._defines.INVERTNORMALMAPY = true;
  53430. }
  53431. }
  53432. }
  53433. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53434. if (!this.refractionTexture.isReady()) {
  53435. return false;
  53436. }
  53437. else {
  53438. needUVs = true;
  53439. this._defines.REFRACTION = true;
  53440. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  53441. if (this.linkRefractionWithTransparency) {
  53442. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  53443. }
  53444. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  53445. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  53446. if (this.refractionTexture.isPMREM) {
  53447. this._defines.USEPMREMREFRACTION = true;
  53448. }
  53449. }
  53450. }
  53451. }
  53452. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53453. if (!this.cameraColorGradingTexture.isReady()) {
  53454. return false;
  53455. }
  53456. else {
  53457. this._defines.CAMERACOLORGRADING = true;
  53458. }
  53459. }
  53460. }
  53461. // Effect
  53462. if (scene.clipPlane) {
  53463. this._defines.CLIPPLANE = true;
  53464. }
  53465. if (engine.getAlphaTesting()) {
  53466. this._defines.ALPHATEST = true;
  53467. }
  53468. if (this._shouldUseAlphaFromAlbedoTexture()) {
  53469. this._defines.ALPHAFROMALBEDO = true;
  53470. }
  53471. if (this.useEmissiveAsIllumination) {
  53472. this._defines.EMISSIVEASILLUMINATION = true;
  53473. }
  53474. if (this.linkEmissiveWithAlbedo) {
  53475. this._defines.LINKEMISSIVEWITHALBEDO = true;
  53476. }
  53477. if (this.useLogarithmicDepth) {
  53478. this._defines.LOGARITHMICDEPTH = true;
  53479. }
  53480. if (this.cameraContrast != 1) {
  53481. this._defines.CAMERACONTRAST = true;
  53482. }
  53483. if (this.cameraExposure != 1) {
  53484. this._defines.CAMERATONEMAP = true;
  53485. }
  53486. if (this.cameraColorCurves) {
  53487. this._defines.CAMERACOLORCURVES = true;
  53488. }
  53489. if (this.overloadedShadeIntensity != 1 ||
  53490. this.overloadedShadowIntensity != 1) {
  53491. this._defines.OVERLOADEDSHADOWVALUES = true;
  53492. }
  53493. if (this.overloadedMicroSurfaceIntensity > 0 ||
  53494. this.overloadedEmissiveIntensity > 0 ||
  53495. this.overloadedReflectivityIntensity > 0 ||
  53496. this.overloadedAlbedoIntensity > 0 ||
  53497. this.overloadedAmbientIntensity > 0 ||
  53498. this.overloadedReflectionIntensity > 0) {
  53499. this._defines.OVERLOADEDVALUES = true;
  53500. }
  53501. // Point size
  53502. if (this.pointsCloud || scene.forcePointsCloud) {
  53503. this._defines.POINTSIZE = true;
  53504. }
  53505. // Fog
  53506. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53507. this._defines.FOG = true;
  53508. }
  53509. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53510. // Fresnel
  53511. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  53512. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53513. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53514. this._defines.OPACITYFRESNEL = true;
  53515. }
  53516. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53517. this._defines.EMISSIVEFRESNEL = true;
  53518. }
  53519. needNormals = true;
  53520. this._defines.FRESNEL = true;
  53521. }
  53522. }
  53523. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  53524. this._defines.SPECULAROVERALPHA = true;
  53525. }
  53526. if (this.usePhysicalLightFalloff) {
  53527. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  53528. }
  53529. if (this.useRadianceOverAlpha) {
  53530. this._defines.RADIANCEOVERALPHA = true;
  53531. }
  53532. // Attribs
  53533. if (mesh) {
  53534. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53535. this._defines.NORMAL = true;
  53536. }
  53537. if (needUVs) {
  53538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53539. this._defines.UV1 = true;
  53540. }
  53541. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53542. this._defines.UV2 = true;
  53543. }
  53544. }
  53545. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53546. this._defines.VERTEXCOLOR = true;
  53547. if (mesh.hasVertexAlpha) {
  53548. this._defines.VERTEXALPHA = true;
  53549. }
  53550. }
  53551. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53552. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  53553. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  53554. }
  53555. // Instances
  53556. if (useInstances) {
  53557. this._defines.INSTANCES = true;
  53558. }
  53559. }
  53560. // Get correct effect
  53561. if (!this._defines.isEqual(this._cachedDefines)) {
  53562. this._defines.cloneTo(this._cachedDefines);
  53563. scene.resetCachedMaterial();
  53564. // Fallbacks
  53565. var fallbacks = new BABYLON.EffectFallbacks();
  53566. if (this._defines.REFLECTION) {
  53567. fallbacks.addFallback(0, "REFLECTION");
  53568. }
  53569. if (this._defines.REFRACTION) {
  53570. fallbacks.addFallback(0, "REFRACTION");
  53571. }
  53572. if (this._defines.REFLECTIVITY) {
  53573. fallbacks.addFallback(0, "REFLECTIVITY");
  53574. }
  53575. if (this._defines.BUMP) {
  53576. fallbacks.addFallback(0, "BUMP");
  53577. }
  53578. if (this._defines.PARALLAX) {
  53579. fallbacks.addFallback(1, "PARALLAX");
  53580. }
  53581. if (this._defines.PARALLAXOCCLUSION) {
  53582. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  53583. }
  53584. if (this._defines.SPECULAROVERALPHA) {
  53585. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  53586. }
  53587. if (this._defines.FOG) {
  53588. fallbacks.addFallback(1, "FOG");
  53589. }
  53590. if (this._defines.POINTSIZE) {
  53591. fallbacks.addFallback(0, "POINTSIZE");
  53592. }
  53593. if (this._defines.LOGARITHMICDEPTH) {
  53594. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  53595. }
  53596. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  53597. if (this._defines.SPECULARTERM) {
  53598. fallbacks.addFallback(0, "SPECULARTERM");
  53599. }
  53600. if (this._defines.OPACITYFRESNEL) {
  53601. fallbacks.addFallback(1, "OPACITYFRESNEL");
  53602. }
  53603. if (this._defines.EMISSIVEFRESNEL) {
  53604. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  53605. }
  53606. if (this._defines.FRESNEL) {
  53607. fallbacks.addFallback(3, "FRESNEL");
  53608. }
  53609. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  53610. fallbacks.addCPUSkinningFallback(0, mesh);
  53611. }
  53612. //Attributes
  53613. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53614. if (this._defines.NORMAL) {
  53615. attribs.push(BABYLON.VertexBuffer.NormalKind);
  53616. }
  53617. if (this._defines.UV1) {
  53618. attribs.push(BABYLON.VertexBuffer.UVKind);
  53619. }
  53620. if (this._defines.UV2) {
  53621. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53622. }
  53623. if (this._defines.VERTEXCOLOR) {
  53624. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53625. }
  53626. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  53627. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  53628. // Legacy browser patch
  53629. var join = this._defines.toString();
  53630. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  53631. "vFogInfos", "vFogColor", "pointSize",
  53632. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  53633. "mBones",
  53634. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  53635. "depthValues",
  53636. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  53637. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  53638. "logarithmicDepthConstant",
  53639. "vSphericalX", "vSphericalY", "vSphericalZ",
  53640. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  53641. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  53642. "vMicrosurfaceTextureLods",
  53643. "vCameraInfos"
  53644. ];
  53645. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  53646. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  53647. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  53648. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  53649. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  53650. }
  53651. if (!this._effect.isReady()) {
  53652. return false;
  53653. }
  53654. this._renderId = scene.getRenderId();
  53655. this._wasPreviouslyReady = true;
  53656. if (mesh) {
  53657. if (!mesh._materialDefines) {
  53658. mesh._materialDefines = new PBRMaterialDefines();
  53659. }
  53660. this._defines.cloneTo(mesh._materialDefines);
  53661. }
  53662. return true;
  53663. };
  53664. PBRMaterial.prototype.unbind = function () {
  53665. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  53666. this._effect.setTexture("reflection2DSampler", null);
  53667. }
  53668. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  53669. this._effect.setTexture("refraction2DSampler", null);
  53670. }
  53671. _super.prototype.unbind.call(this);
  53672. };
  53673. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53674. this._effect.setMatrix("world", world);
  53675. };
  53676. PBRMaterial.prototype.bind = function (world, mesh) {
  53677. this._myScene = this.getScene();
  53678. // Matrices
  53679. this.bindOnlyWorldMatrix(world);
  53680. // Bones
  53681. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53682. if (this._myScene.getCachedMaterial() !== this) {
  53683. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  53684. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53685. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53686. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  53687. }
  53688. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53689. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  53690. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  53691. }
  53692. }
  53693. // Textures
  53694. if (this._myScene.texturesEnabled) {
  53695. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53696. this._effect.setTexture("albedoSampler", this.albedoTexture);
  53697. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  53698. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  53699. }
  53700. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53701. this._effect.setTexture("ambientSampler", this.ambientTexture);
  53702. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  53703. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  53704. }
  53705. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53706. this._effect.setTexture("opacitySampler", this.opacityTexture);
  53707. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  53708. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  53709. }
  53710. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53711. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  53712. if (this.reflectionTexture.isCube) {
  53713. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  53714. }
  53715. else {
  53716. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  53717. }
  53718. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  53719. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  53720. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  53721. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  53722. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  53723. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  53724. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  53725. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  53726. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  53727. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  53728. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  53729. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  53730. }
  53731. }
  53732. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53733. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  53734. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  53735. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  53736. }
  53737. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53738. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  53739. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  53740. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  53741. }
  53742. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53743. if (this.metallicTexture) {
  53744. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  53745. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  53746. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  53747. }
  53748. else if (this.reflectivityTexture) {
  53749. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  53750. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  53751. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  53752. }
  53753. }
  53754. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53755. this._effect.setTexture("bumpSampler", this.bumpTexture);
  53756. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  53757. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  53758. }
  53759. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53760. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  53761. var depth = 1.0;
  53762. if (this.refractionTexture.isCube) {
  53763. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  53764. }
  53765. else {
  53766. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  53767. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  53768. if (this.refractionTexture.depth) {
  53769. depth = this.refractionTexture.depth;
  53770. }
  53771. }
  53772. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  53773. }
  53774. if ((this.reflectionTexture || this.refractionTexture)) {
  53775. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  53776. }
  53777. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53778. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  53779. }
  53780. }
  53781. // Clip plane
  53782. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  53783. // Point size
  53784. if (this.pointsCloud) {
  53785. this._effect.setFloat("pointSize", this.pointSize);
  53786. }
  53787. // Colors
  53788. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  53789. // GAMMA CORRECTION.
  53790. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  53791. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  53792. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  53793. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  53794. // GAMMA CORRECTION.
  53795. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  53796. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  53797. // GAMMA CORRECTION.
  53798. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  53799. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  53800. }
  53801. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  53802. // GAMMA CORRECTION.
  53803. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  53804. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  53805. // Lights
  53806. if (this._myScene.lightsEnabled && !this.disableLighting) {
  53807. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  53808. }
  53809. // View
  53810. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  53811. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  53812. }
  53813. // Fog
  53814. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  53815. this._lightingInfos.x = this.directIntensity;
  53816. this._lightingInfos.y = this.emissiveIntensity;
  53817. this._lightingInfos.z = this.environmentIntensity;
  53818. this._lightingInfos.w = this.specularIntensity;
  53819. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  53820. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  53821. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  53822. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  53823. this._cameraInfos.x = this.cameraExposure;
  53824. this._cameraInfos.y = this.cameraContrast;
  53825. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  53826. if (this.cameraColorCurves) {
  53827. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  53828. }
  53829. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  53830. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  53831. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  53832. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  53833. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  53834. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  53835. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  53836. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  53837. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  53838. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  53839. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  53840. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  53841. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  53842. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  53843. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  53844. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  53845. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  53846. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  53847. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  53848. // Log. depth
  53849. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  53850. }
  53851. _super.prototype.bind.call(this, world, mesh);
  53852. this._myScene = null;
  53853. };
  53854. PBRMaterial.prototype.getAnimatables = function () {
  53855. var results = [];
  53856. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  53857. results.push(this.albedoTexture);
  53858. }
  53859. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  53860. results.push(this.ambientTexture);
  53861. }
  53862. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  53863. results.push(this.opacityTexture);
  53864. }
  53865. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  53866. results.push(this.reflectionTexture);
  53867. }
  53868. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  53869. results.push(this.emissiveTexture);
  53870. }
  53871. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  53872. results.push(this.metallicTexture);
  53873. }
  53874. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  53875. results.push(this.reflectivityTexture);
  53876. }
  53877. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  53878. results.push(this.bumpTexture);
  53879. }
  53880. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  53881. results.push(this.lightmapTexture);
  53882. }
  53883. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  53884. results.push(this.refractionTexture);
  53885. }
  53886. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  53887. results.push(this.cameraColorGradingTexture);
  53888. }
  53889. return results;
  53890. };
  53891. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53892. if (forceDisposeTextures) {
  53893. if (this.albedoTexture) {
  53894. this.albedoTexture.dispose();
  53895. }
  53896. if (this.ambientTexture) {
  53897. this.ambientTexture.dispose();
  53898. }
  53899. if (this.opacityTexture) {
  53900. this.opacityTexture.dispose();
  53901. }
  53902. if (this.reflectionTexture) {
  53903. this.reflectionTexture.dispose();
  53904. }
  53905. if (this.emissiveTexture) {
  53906. this.emissiveTexture.dispose();
  53907. }
  53908. if (this.metallicTexture) {
  53909. this.metallicTexture.dispose();
  53910. }
  53911. if (this.reflectivityTexture) {
  53912. this.reflectivityTexture.dispose();
  53913. }
  53914. if (this.bumpTexture) {
  53915. this.bumpTexture.dispose();
  53916. }
  53917. if (this.lightmapTexture) {
  53918. this.lightmapTexture.dispose();
  53919. }
  53920. if (this.refractionTexture) {
  53921. this.refractionTexture.dispose();
  53922. }
  53923. if (this.cameraColorGradingTexture) {
  53924. this.cameraColorGradingTexture.dispose();
  53925. }
  53926. }
  53927. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53928. };
  53929. PBRMaterial.prototype.clone = function (name) {
  53930. var _this = this;
  53931. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  53932. };
  53933. PBRMaterial.prototype.serialize = function () {
  53934. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53935. serializationObject.customType = "BABYLON.PBRMaterial";
  53936. return serializationObject;
  53937. };
  53938. // Statics
  53939. PBRMaterial.Parse = function (source, scene, rootUrl) {
  53940. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  53941. };
  53942. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  53943. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  53944. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  53945. PBRMaterial._scaledReflection = new BABYLON.Color3();
  53946. __decorate([
  53947. BABYLON.serialize()
  53948. ], PBRMaterial.prototype, "directIntensity", void 0);
  53949. __decorate([
  53950. BABYLON.serialize()
  53951. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  53952. __decorate([
  53953. BABYLON.serialize()
  53954. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  53955. __decorate([
  53956. BABYLON.serialize()
  53957. ], PBRMaterial.prototype, "specularIntensity", void 0);
  53958. __decorate([
  53959. BABYLON.serialize()
  53960. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  53961. __decorate([
  53962. BABYLON.serialize()
  53963. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  53964. __decorate([
  53965. BABYLON.serialize()
  53966. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  53967. __decorate([
  53968. BABYLON.serialize()
  53969. ], PBRMaterial.prototype, "cameraExposure", void 0);
  53970. __decorate([
  53971. BABYLON.serialize()
  53972. ], PBRMaterial.prototype, "cameraContrast", void 0);
  53973. __decorate([
  53974. BABYLON.serializeAsTexture()
  53975. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  53976. __decorate([
  53977. BABYLON.serializeAsColorCurves()
  53978. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  53979. __decorate([
  53980. BABYLON.serializeAsColor3()
  53981. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  53982. __decorate([
  53983. BABYLON.serialize()
  53984. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  53985. __decorate([
  53986. BABYLON.serializeAsColor3()
  53987. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  53988. __decorate([
  53989. BABYLON.serialize()
  53990. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  53991. __decorate([
  53992. BABYLON.serializeAsColor3()
  53993. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  53994. __decorate([
  53995. BABYLON.serialize()
  53996. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  53997. __decorate([
  53998. BABYLON.serializeAsColor3()
  53999. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  54000. __decorate([
  54001. BABYLON.serialize()
  54002. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  54003. __decorate([
  54004. BABYLON.serializeAsColor3()
  54005. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  54006. __decorate([
  54007. BABYLON.serialize()
  54008. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  54009. __decorate([
  54010. BABYLON.serialize()
  54011. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  54012. __decorate([
  54013. BABYLON.serialize()
  54014. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  54015. __decorate([
  54016. BABYLON.serializeAsTexture()
  54017. ], PBRMaterial.prototype, "albedoTexture", void 0);
  54018. __decorate([
  54019. BABYLON.serializeAsTexture()
  54020. ], PBRMaterial.prototype, "ambientTexture", void 0);
  54021. __decorate([
  54022. BABYLON.serialize()
  54023. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  54024. __decorate([
  54025. BABYLON.serializeAsTexture()
  54026. ], PBRMaterial.prototype, "opacityTexture", void 0);
  54027. __decorate([
  54028. BABYLON.serializeAsTexture()
  54029. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  54030. __decorate([
  54031. BABYLON.serializeAsTexture()
  54032. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  54033. __decorate([
  54034. BABYLON.serializeAsTexture()
  54035. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  54036. __decorate([
  54037. BABYLON.serializeAsTexture()
  54038. ], PBRMaterial.prototype, "metallicTexture", void 0);
  54039. __decorate([
  54040. BABYLON.serializeAsTexture()
  54041. ], PBRMaterial.prototype, "bumpTexture", void 0);
  54042. __decorate([
  54043. BABYLON.serializeAsTexture()
  54044. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  54045. __decorate([
  54046. BABYLON.serializeAsTexture()
  54047. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54048. __decorate([
  54049. BABYLON.serializeAsColor3("ambient")
  54050. ], PBRMaterial.prototype, "ambientColor", void 0);
  54051. __decorate([
  54052. BABYLON.serializeAsColor3("albedo")
  54053. ], PBRMaterial.prototype, "albedoColor", void 0);
  54054. __decorate([
  54055. BABYLON.serializeAsColor3("reflectivity")
  54056. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54057. __decorate([
  54058. BABYLON.serializeAsColor3("reflection")
  54059. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54060. __decorate([
  54061. BABYLON.serializeAsColor3("emissive")
  54062. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54063. __decorate([
  54064. BABYLON.serialize()
  54065. ], PBRMaterial.prototype, "microSurface", void 0);
  54066. __decorate([
  54067. BABYLON.serialize()
  54068. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54069. __decorate([
  54070. BABYLON.serialize()
  54071. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54072. __decorate([
  54073. BABYLON.serializeAsFresnelParameters()
  54074. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54075. __decorate([
  54076. BABYLON.serializeAsFresnelParameters()
  54077. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54078. __decorate([
  54079. BABYLON.serialize()
  54080. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54081. __decorate([
  54082. BABYLON.serialize()
  54083. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54084. __decorate([
  54085. BABYLON.serialize()
  54086. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54087. __decorate([
  54088. BABYLON.serialize()
  54089. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54090. __decorate([
  54091. BABYLON.serialize()
  54092. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54093. __decorate([
  54094. BABYLON.serialize()
  54095. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54096. __decorate([
  54097. BABYLON.serialize()
  54098. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54099. __decorate([
  54100. BABYLON.serialize()
  54101. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  54102. __decorate([
  54103. BABYLON.serialize()
  54104. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  54105. __decorate([
  54106. BABYLON.serialize()
  54107. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54108. __decorate([
  54109. BABYLON.serialize()
  54110. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54111. __decorate([
  54112. BABYLON.serialize()
  54113. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54114. __decorate([
  54115. BABYLON.serialize()
  54116. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54117. __decorate([
  54118. BABYLON.serialize()
  54119. ], PBRMaterial.prototype, "useParallax", void 0);
  54120. __decorate([
  54121. BABYLON.serialize()
  54122. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54123. __decorate([
  54124. BABYLON.serialize()
  54125. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54126. __decorate([
  54127. BABYLON.serialize()
  54128. ], PBRMaterial.prototype, "disableLighting", void 0);
  54129. __decorate([
  54130. BABYLON.serialize()
  54131. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54132. __decorate([
  54133. BABYLON.serialize()
  54134. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54135. __decorate([
  54136. BABYLON.serialize()
  54137. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54138. __decorate([
  54139. BABYLON.serialize()
  54140. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54141. return PBRMaterial;
  54142. }(BABYLON.Material));
  54143. BABYLON.PBRMaterial = PBRMaterial;
  54144. })(BABYLON || (BABYLON = {}));
  54145. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54146. var BABYLON;
  54147. (function (BABYLON) {
  54148. var DebugLayer = (function () {
  54149. function DebugLayer(scene) {
  54150. this._scene = scene;
  54151. }
  54152. /** Creates the inspector window. */
  54153. DebugLayer.prototype._createInspector = function () {
  54154. if (!this._inspector) {
  54155. this._inspector = new INSPECTOR.Inspector(this._scene);
  54156. } // else nothing to do,; instance is already existing
  54157. };
  54158. DebugLayer.prototype.isVisible = function () {
  54159. return false;
  54160. };
  54161. DebugLayer.prototype.hide = function () {
  54162. if (this._inspector) {
  54163. this._inspector.dispose();
  54164. this._inspector = null;
  54165. }
  54166. };
  54167. DebugLayer.prototype.show = function () {
  54168. if (typeof INSPECTOR == 'undefined') {
  54169. // Load inspector and add it to the DOM
  54170. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this));
  54171. }
  54172. else {
  54173. // Otherwise creates the inspector
  54174. this._createInspector();
  54175. }
  54176. };
  54177. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54178. return DebugLayer;
  54179. }());
  54180. BABYLON.DebugLayer = DebugLayer;
  54181. })(BABYLON || (BABYLON = {}));
  54182. //# sourceMappingURL=babylon.debugLayer.js.map
  54183. var BABYLON;
  54184. (function (BABYLON) {
  54185. var StandardRenderingPipeline = (function (_super) {
  54186. __extends(StandardRenderingPipeline, _super);
  54187. /**
  54188. * @constructor
  54189. * @param {string} name - The rendering pipeline name
  54190. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54191. * @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)
  54192. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54193. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54194. */
  54195. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54196. var _this = this;
  54197. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54198. _super.call(this, scene.getEngine(), name);
  54199. this.downSampleX4PostProcess = null;
  54200. this.brightPassPostProcess = null;
  54201. this.gaussianBlurHPostProcesses = [];
  54202. this.gaussianBlurVPostProcesses = [];
  54203. this.textureAdderPostProcess = null;
  54204. this.textureAdderFinalPostProcess = null;
  54205. this.lensFlarePostProcess = null;
  54206. this.lensFlareComposePostProcess = null;
  54207. this.depthOfFieldPostProcess = null;
  54208. // Values
  54209. this.brightThreshold = 1.0;
  54210. this.blurWidth = 2.0;
  54211. this.gaussianCoefficient = 0.25;
  54212. this.gaussianMean = 1.0;
  54213. this.gaussianStandardDeviation = 1.0;
  54214. this.exposure = 1.0;
  54215. this.lensTexture = null;
  54216. this.lensColorTexture = null;
  54217. this.lensFlareStrength = 20.0;
  54218. this.lensFlareGhostDispersal = 1.4;
  54219. this.lensFlareHaloWidth = 0.7;
  54220. this.lensFlareDistortionStrength = 16.0;
  54221. this.lensStarTexture = null;
  54222. this.lensFlareDirtTexture = null;
  54223. this.depthOfFieldDistance = 10.0;
  54224. // IAnimatable
  54225. this.animations = [];
  54226. this._depthRenderer = null;
  54227. // Getters and setters
  54228. this._depthOfFieldEnabled = true;
  54229. this._lensFlareEnabled = true;
  54230. // Initialize
  54231. this._scene = scene;
  54232. // Create pass post-processe
  54233. if (!originalPostProcess) {
  54234. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  54235. }
  54236. else {
  54237. this.originalPostProcess = originalPostProcess;
  54238. }
  54239. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54240. // Create down sample X4 post-process
  54241. this._createDownSampleX4PostProcess(scene, ratio / 2);
  54242. // Create bright pass post-process
  54243. this._createBrightPassPostProcess(scene, ratio / 2);
  54244. // Create gaussian blur post-processes (down sampling blurs)
  54245. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  54246. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  54247. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  54248. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  54249. // Create texture adder post-process
  54250. this._createTextureAdderPostProcess(scene, ratio);
  54251. // Create depth-of-field source post-process
  54252. 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);
  54253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54254. // Create lens flare post-process
  54255. this._createLensFlarePostProcess(scene, ratio);
  54256. // Create gaussian blur used by depth-of-field
  54257. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  54258. // Create depth-of-field post-process
  54259. this._createDepthOfFieldPostProcess(scene, ratio);
  54260. // Finish
  54261. scene.postProcessRenderPipelineManager.addPipeline(this);
  54262. if (cameras !== null) {
  54263. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54264. }
  54265. // Deactivate
  54266. this.LensFlareEnabled = false;
  54267. this.DepthOfFieldEnabled = false;
  54268. }
  54269. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54270. get: function () {
  54271. return this._depthOfFieldEnabled;
  54272. },
  54273. set: function (enabled) {
  54274. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  54275. if (enabled && !this._depthOfFieldEnabled) {
  54276. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54277. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54278. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54279. this._depthRenderer = this._scene.enableDepthRenderer();
  54280. }
  54281. else if (!enabled && this._depthOfFieldEnabled) {
  54282. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54283. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54284. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54285. }
  54286. this._depthOfFieldEnabled = enabled;
  54287. },
  54288. enumerable: true,
  54289. configurable: true
  54290. });
  54291. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54292. get: function () {
  54293. return this._lensFlareEnabled;
  54294. },
  54295. set: function (enabled) {
  54296. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  54297. if (enabled && !this._lensFlareEnabled) {
  54298. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54299. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54300. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54301. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54302. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54303. }
  54304. else if (!enabled && this._lensFlareEnabled) {
  54305. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54306. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54307. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54308. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54309. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54310. }
  54311. this._lensFlareEnabled = enabled;
  54312. },
  54313. enumerable: true,
  54314. configurable: true
  54315. });
  54316. // Down Sample X4 Post-Processs
  54317. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54318. var _this = this;
  54319. var downSampleX4Offsets = new Array(32);
  54320. 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);
  54321. this.downSampleX4PostProcess.onApply = function (effect) {
  54322. var id = 0;
  54323. for (var i = -2; i < 2; i++) {
  54324. for (var j = -2; j < 2; j++) {
  54325. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54326. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54327. id += 2;
  54328. }
  54329. }
  54330. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54331. };
  54332. // Add to pipeline
  54333. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54334. };
  54335. // Brightpass Post-Process
  54336. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54337. var _this = this;
  54338. var brightOffsets = new Array(8);
  54339. 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);
  54340. this.brightPassPostProcess.onApply = function (effect) {
  54341. var sU = (1.0 / _this.brightPassPostProcess.width);
  54342. var sV = (1.0 / _this.brightPassPostProcess.height);
  54343. brightOffsets[0] = -0.5 * sU;
  54344. brightOffsets[1] = 0.5 * sV;
  54345. brightOffsets[2] = 0.5 * sU;
  54346. brightOffsets[3] = 0.5 * sV;
  54347. brightOffsets[4] = -0.5 * sU;
  54348. brightOffsets[5] = -0.5 * sV;
  54349. brightOffsets[6] = 0.5 * sU;
  54350. brightOffsets[7] = -0.5 * sV;
  54351. effect.setArray2("dsOffsets", brightOffsets);
  54352. effect.setFloat("brightThreshold", _this.brightThreshold);
  54353. };
  54354. // Add to pipeline
  54355. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54356. };
  54357. // Create gaussian blur H&V post-processes
  54358. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  54359. var _this = this;
  54360. var blurOffsets = new Array(9);
  54361. var blurWeights = new Array(9);
  54362. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  54363. var callback = function (height) {
  54364. return function (effect) {
  54365. // Weights
  54366. var x = 0.0;
  54367. for (var i = 0; i < 9; i++) {
  54368. x = (i - 4.0) / 4.0;
  54369. blurWeights[i] =
  54370. _this.gaussianCoefficient
  54371. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  54372. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  54373. }
  54374. var lastOutputDimensions = {
  54375. width: scene.getEngine().getRenderWidth(),
  54376. height: scene.getEngine().getRenderHeight()
  54377. };
  54378. for (var i = 0; i < 9; i++) {
  54379. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54380. blurOffsets[i] = value;
  54381. }
  54382. effect.setArray("blurOffsets", blurOffsets);
  54383. effect.setArray("blurWeights", blurWeights);
  54384. effect.setFloat("blurWidth", _this.blurWidth);
  54385. };
  54386. };
  54387. // Create horizontal gaussian blur post-processes
  54388. 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);
  54389. gaussianBlurHPostProcess.onApply = callback(false);
  54390. // Create vertical gaussian blur post-process
  54391. 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);
  54392. gaussianBlurVPostProcess.onApply = callback(true);
  54393. // Add to pipeline
  54394. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  54395. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  54396. // Finish
  54397. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  54398. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  54399. };
  54400. // Create texture adder post-process
  54401. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54402. var _this = this;
  54403. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  54404. 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);
  54405. this.textureAdderPostProcess.onApply = function (effect) {
  54406. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  54407. effect.setTexture("lensSampler", _this.lensTexture);
  54408. effect.setFloat("exposure", _this.exposure);
  54409. };
  54410. // Add to pipeline
  54411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54412. };
  54413. // Create lens flare post-process
  54414. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54415. var _this = this;
  54416. 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);
  54417. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  54418. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  54419. 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);
  54420. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  54421. var resolution = new BABYLON.Vector2(0, 0);
  54422. // Lens flare
  54423. this.lensFlarePostProcess.onApply = function (effect) {
  54424. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  54425. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54426. effect.setFloat("strength", _this.lensFlareStrength);
  54427. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54428. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54429. // Shift
  54430. resolution.x = _this.lensFlarePostProcess.width;
  54431. resolution.y = _this.lensFlarePostProcess.height;
  54432. effect.setVector2("resolution", resolution);
  54433. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54434. };
  54435. // Compose
  54436. 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);
  54437. 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);
  54438. this.lensFlareComposePostProcess.onApply = function (effect) {
  54439. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54440. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54441. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54442. // Lens start rotation matrix
  54443. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54444. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54445. 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));
  54446. camRot *= 4.0;
  54447. 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);
  54448. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54449. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54450. };
  54451. };
  54452. // Create depth-of-field post-process
  54453. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54454. var _this = this;
  54455. 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);
  54456. this.depthOfFieldPostProcess.onApply = function (effect) {
  54457. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54458. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  54459. effect.setFloat("distance", _this.depthOfFieldDistance);
  54460. };
  54461. // Add to pipeline
  54462. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54463. };
  54464. // Dispose
  54465. StandardRenderingPipeline.prototype.dispose = function () {
  54466. for (var i = 0; i < this._scene.cameras.length; i++) {
  54467. var camera = this._scene.cameras[i];
  54468. this.originalPostProcess.dispose(camera);
  54469. this.downSampleX4PostProcess.dispose(camera);
  54470. this.brightPassPostProcess.dispose(camera);
  54471. this.textureAdderPostProcess.dispose(camera);
  54472. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  54473. this.gaussianBlurHPostProcesses[j].dispose(camera);
  54474. }
  54475. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  54476. this.gaussianBlurVPostProcesses[j].dispose(camera);
  54477. }
  54478. this.textureAdderFinalPostProcess.dispose(camera);
  54479. this.lensFlarePostProcess.dispose(camera);
  54480. this.lensFlareComposePostProcess.dispose(camera);
  54481. this.depthOfFieldPostProcess.dispose(camera);
  54482. }
  54483. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54484. _super.prototype.dispose.call(this);
  54485. };
  54486. return StandardRenderingPipeline;
  54487. }(BABYLON.PostProcessRenderPipeline));
  54488. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54489. })(BABYLON || (BABYLON = {}));
  54490. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54491. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nfloat metallic=surfaceMetallicColorMap.r; \n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallic);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallic);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmicroSurface=1.0-surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmicroSurface=1.0-surfaceMetallicColorMap.g;\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) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\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}"};
  54492. 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"};
  54493. 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=new n(0,0,0);return n.LerpToRef(t,i,r,o),o},n.LerpToRef=function(t,i,n,r){r.x=t.x+(i.x-t.x)*n,r.y=t.y+(i.y-t.y)*n,r.z=t.z+(i.z-t.z)*n},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=t.Identity();return t.SlerpToRef(i,n,r,o),o},t.SlerpToRef=function(t,i,n,r){var o,e,s=n,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}r.x=e*t.x+o*i.x,r.y=e*t.y+o*i.y,r.z=e*t.z+o*i.z,r.w=e*t.w+o*i.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,q=s*y-h*m,D=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*q)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*H-n*D+o*N)*b,t.m[15]=(i*q-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){\nfor(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];return 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.prototype.getRotationMatrix=function(){var i=t.Identity();return this.getRotationMatrixToRef(i),i},t.prototype.getRotationMatrixToRef=function(i){var n=this.m,r=n[0]*n[1]*n[2]*n[3]<0?-1:1,o=n[4]*n[5]*n[6]*n[7]<0?-1:1,e=n[8]*n[9]*n[10]*n[11]<0?-1:1,s=r*Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),h=o*Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),a=e*Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]);t.FromValuesToRef(n[0]/s,n[1]/s,n[2]/s,0,n[4]/h,n[5]/h,n[6]/h,0,n[8]/a,n[9]/a,n[10]/a,0,0,0,0,1,i)},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={}));";
  54494. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54495. module.exports = BABYLON;
  54496. };