babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418
  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. return Matrix;
  2577. }());
  2578. Matrix._tempQuaternion = new Quaternion();
  2579. Matrix._xAxis = Vector3.Zero();
  2580. Matrix._yAxis = Vector3.Zero();
  2581. Matrix._zAxis = Vector3.Zero();
  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. var Space;
  2750. (function (Space) {
  2751. Space[Space["LOCAL"] = 0] = "LOCAL";
  2752. Space[Space["WORLD"] = 1] = "WORLD";
  2753. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  2754. var Axis = (function () {
  2755. function Axis() {
  2756. }
  2757. return Axis;
  2758. }());
  2759. Axis.X = new Vector3(1, 0, 0);
  2760. Axis.Y = new Vector3(0, 1, 0);
  2761. Axis.Z = new Vector3(0, 0, 1);
  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. var Orientation;
  2790. (function (Orientation) {
  2791. Orientation[Orientation["CW"] = 0] = "CW";
  2792. Orientation[Orientation["CCW"] = 1] = "CCW";
  2793. })(Orientation = BABYLON.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. return Tmp;
  3319. }());
  3320. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3321. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3322. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3323. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3324. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3325. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3326. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3327. Matrix.Zero(), Matrix.Zero(),
  3328. Matrix.Zero(), Matrix.Zero(),
  3329. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  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. return Database;
  4127. }());
  4128. Database.IsUASupportingBlobStorage = true;
  4129. Database.IDBStorageEnabled = true;
  4130. Database.parseURL = function (url) {
  4131. var a = document.createElement('a');
  4132. a.href = url;
  4133. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4134. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4135. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4136. return absLocation;
  4137. };
  4138. Database.ReturnFullUrlLocation = function (url) {
  4139. if (url.indexOf("http:/") === -1) {
  4140. return (Database.parseURL(window.location.href) + url);
  4141. }
  4142. else {
  4143. return url;
  4144. }
  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. return TGATools;
  4397. }());
  4398. TGATools._TYPE_NO_DATA = 0;
  4399. TGATools._TYPE_INDEXED = 1;
  4400. TGATools._TYPE_RGB = 2;
  4401. TGATools._TYPE_GREY = 3;
  4402. TGATools._TYPE_RLE_INDEXED = 9;
  4403. TGATools._TYPE_RLE_RGB = 10;
  4404. TGATools._TYPE_RLE_GREY = 11;
  4405. TGATools._ORIGIN_MASK = 0x30;
  4406. TGATools._ORIGIN_SHIFT = 0x04;
  4407. TGATools._ORIGIN_BL = 0x00;
  4408. TGATools._ORIGIN_BR = 0x01;
  4409. TGATools._ORIGIN_UL = 0x02;
  4410. TGATools._ORIGIN_UR = 0x03;
  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. return SmartArray;
  4479. }());
  4480. // Statics
  4481. SmartArray._GlobalId = 0;
  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. return Tools;
  5673. }());
  5674. Tools.BaseUrl = "";
  5675. Tools.CorsBehavior = "anonymous";
  5676. Tools.UseFallbackTexture = true;
  5677. // Logs
  5678. Tools._NoneLogLevel = 0;
  5679. Tools._MessageLogLevel = 1;
  5680. Tools._WarningLogLevel = 2;
  5681. Tools._ErrorLogLevel = 4;
  5682. Tools._LogCache = "";
  5683. Tools.errorsCount = 0;
  5684. Tools.Log = Tools._LogEnabled;
  5685. Tools.Warn = Tools._WarnEnabled;
  5686. Tools.Error = Tools._ErrorEnabled;
  5687. // Performances
  5688. Tools._PerformanceNoneLogLevel = 0;
  5689. Tools._PerformanceUserMarkLogLevel = 1;
  5690. Tools._PerformanceConsoleLogLevel = 2;
  5691. Tools._performance = window.performance;
  5692. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5693. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  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. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  6514. var _this = this;
  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 = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6589. if (this._gl) {
  6590. this._webGLVersion = "2.0";
  6591. }
  6592. }
  6593. catch (e) {
  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. this.unbindAllAttributes();
  7542. var offset = 0;
  7543. for (var index = 0; index < attributesCount; index++) {
  7544. if (index < vertexDeclaration.length) {
  7545. var order = effect.getAttributeLocation(index);
  7546. if (order >= 0) {
  7547. this._gl.enableVertexAttribArray(order);
  7548. this._vertexAttribArraysEnabled[order] = true;
  7549. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7550. }
  7551. offset += vertexDeclaration[index] * 4;
  7552. }
  7553. }
  7554. }
  7555. if (this._cachedIndexBuffer !== indexBuffer) {
  7556. this._cachedIndexBuffer = indexBuffer;
  7557. this.bindIndexBuffer(indexBuffer);
  7558. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7559. }
  7560. };
  7561. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7562. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7563. this._cachedVertexBuffers = vertexBuffers;
  7564. this._cachedEffectForVertexBuffers = effect;
  7565. var attributes = effect.getAttributesNames();
  7566. this.unbindAllAttributes();
  7567. for (var index = 0; index < attributes.length; index++) {
  7568. var order = effect.getAttributeLocation(index);
  7569. if (order >= 0) {
  7570. var vertexBuffer = vertexBuffers[attributes[index]];
  7571. if (!vertexBuffer) {
  7572. continue;
  7573. }
  7574. this._gl.enableVertexAttribArray(order);
  7575. this._vertexAttribArraysEnabled[order] = true;
  7576. var buffer = vertexBuffer.getBuffer();
  7577. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7578. if (vertexBuffer.getIsInstanced()) {
  7579. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7580. this._currentInstanceLocations.push(order);
  7581. this._currentInstanceBuffers.push(buffer);
  7582. }
  7583. }
  7584. }
  7585. }
  7586. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7587. this._cachedIndexBuffer = indexBuffer;
  7588. this.bindIndexBuffer(indexBuffer);
  7589. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7590. }
  7591. };
  7592. Engine.prototype.unbindInstanceAttributes = function () {
  7593. var boundBuffer;
  7594. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7595. var instancesBuffer = this._currentInstanceBuffers[i];
  7596. if (boundBuffer != instancesBuffer) {
  7597. boundBuffer = instancesBuffer;
  7598. this.bindArrayBuffer(instancesBuffer);
  7599. }
  7600. var offsetLocation = this._currentInstanceLocations[i];
  7601. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7602. }
  7603. this._currentInstanceBuffers.length = 0;
  7604. this._currentInstanceLocations.length = 0;
  7605. };
  7606. Engine.prototype._releaseBuffer = function (buffer) {
  7607. buffer.references--;
  7608. if (buffer.references === 0) {
  7609. this._gl.deleteBuffer(buffer);
  7610. return true;
  7611. }
  7612. return false;
  7613. };
  7614. Engine.prototype.createInstancesBuffer = function (capacity) {
  7615. var buffer = this._gl.createBuffer();
  7616. buffer.capacity = capacity;
  7617. this.bindArrayBuffer(buffer);
  7618. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7619. return buffer;
  7620. };
  7621. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7622. this._gl.deleteBuffer(buffer);
  7623. };
  7624. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7625. this.bindArrayBuffer(instancesBuffer);
  7626. if (data) {
  7627. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7628. }
  7629. if (offsetLocations[0].index !== undefined) {
  7630. var stride = 0;
  7631. for (var i = 0; i < offsetLocations.length; i++) {
  7632. var ai = offsetLocations[i];
  7633. stride += ai.attributeSize * 4;
  7634. }
  7635. for (var i = 0; i < offsetLocations.length; i++) {
  7636. var ai = offsetLocations[i];
  7637. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7638. this._gl.enableVertexAttribArray(ai.index);
  7639. this._vertexAttribArraysEnabled[ai.index] = true;
  7640. }
  7641. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7642. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7643. this._currentInstanceLocations.push(ai.index);
  7644. this._currentInstanceBuffers.push(instancesBuffer);
  7645. }
  7646. }
  7647. else {
  7648. for (var index = 0; index < 4; index++) {
  7649. var offsetLocation = offsetLocations[index];
  7650. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7651. this._gl.enableVertexAttribArray(offsetLocation);
  7652. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7653. }
  7654. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7655. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7656. this._currentInstanceLocations.push(offsetLocation);
  7657. this._currentInstanceBuffers.push(instancesBuffer);
  7658. }
  7659. }
  7660. };
  7661. Engine.prototype.applyStates = function () {
  7662. this._depthCullingState.apply(this._gl);
  7663. this._stencilState.apply(this._gl);
  7664. this._alphaState.apply(this._gl);
  7665. };
  7666. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7667. // Apply states
  7668. this.applyStates();
  7669. this._drawCalls.addCount(1, false);
  7670. // Render
  7671. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7672. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7673. if (instancesCount) {
  7674. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7675. return;
  7676. }
  7677. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7678. };
  7679. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7680. // Apply states
  7681. this.applyStates();
  7682. this._drawCalls.addCount(1, false);
  7683. if (instancesCount) {
  7684. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7685. return;
  7686. }
  7687. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7688. };
  7689. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7690. // Apply states
  7691. this.applyStates();
  7692. this._drawCalls.addCount(1, false);
  7693. if (instancesCount) {
  7694. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7695. return;
  7696. }
  7697. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7698. };
  7699. // Shaders
  7700. Engine.prototype._releaseEffect = function (effect) {
  7701. if (this._compiledEffects[effect._key]) {
  7702. delete this._compiledEffects[effect._key];
  7703. if (effect.getProgram()) {
  7704. this._gl.deleteProgram(effect.getProgram());
  7705. }
  7706. }
  7707. };
  7708. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7709. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7710. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7711. var name = vertex + "+" + fragment + "@" + defines;
  7712. if (this._compiledEffects[name]) {
  7713. return this._compiledEffects[name];
  7714. }
  7715. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7716. effect._key = name;
  7717. this._compiledEffects[name] = effect;
  7718. return effect;
  7719. };
  7720. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7721. if (uniformsNames === void 0) { uniformsNames = []; }
  7722. if (samplers === void 0) { samplers = []; }
  7723. if (defines === void 0) { defines = ""; }
  7724. return this.createEffect({
  7725. vertex: "particles",
  7726. fragmentElement: fragmentName
  7727. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7728. };
  7729. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7730. context = context || this._gl;
  7731. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7732. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7733. var shaderProgram = context.createProgram();
  7734. context.attachShader(shaderProgram, vertexShader);
  7735. context.attachShader(shaderProgram, fragmentShader);
  7736. context.linkProgram(shaderProgram);
  7737. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7738. if (!linked) {
  7739. var error = context.getProgramInfoLog(shaderProgram);
  7740. if (error) {
  7741. throw new Error(error);
  7742. }
  7743. }
  7744. context.deleteShader(vertexShader);
  7745. context.deleteShader(fragmentShader);
  7746. return shaderProgram;
  7747. };
  7748. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7749. var results = [];
  7750. for (var index = 0; index < uniformsNames.length; index++) {
  7751. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7752. }
  7753. return results;
  7754. };
  7755. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7756. var results = [];
  7757. for (var index = 0; index < attributesNames.length; index++) {
  7758. try {
  7759. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7760. }
  7761. catch (e) {
  7762. results.push(-1);
  7763. }
  7764. }
  7765. return results;
  7766. };
  7767. Engine.prototype.enableEffect = function (effect) {
  7768. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7769. // if (effect && effect.onBind) {
  7770. // effect.onBind(effect);
  7771. // }
  7772. // return;
  7773. //}
  7774. // Use program
  7775. this.setProgram(effect.getProgram());
  7776. this._currentEffect = effect;
  7777. if (effect.onBind) {
  7778. effect.onBind(effect);
  7779. }
  7780. };
  7781. Engine.prototype.setIntArray = function (uniform, array) {
  7782. if (!uniform)
  7783. return;
  7784. this._gl.uniform1iv(uniform, array);
  7785. };
  7786. Engine.prototype.setIntArray2 = function (uniform, array) {
  7787. if (!uniform || array.length % 2 !== 0)
  7788. return;
  7789. this._gl.uniform2iv(uniform, array);
  7790. };
  7791. Engine.prototype.setIntArray3 = function (uniform, array) {
  7792. if (!uniform || array.length % 3 !== 0)
  7793. return;
  7794. this._gl.uniform3iv(uniform, array);
  7795. };
  7796. Engine.prototype.setIntArray4 = function (uniform, array) {
  7797. if (!uniform || array.length % 4 !== 0)
  7798. return;
  7799. this._gl.uniform4iv(uniform, array);
  7800. };
  7801. Engine.prototype.setFloatArray = function (uniform, array) {
  7802. if (!uniform)
  7803. return;
  7804. this._gl.uniform1fv(uniform, array);
  7805. };
  7806. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7807. if (!uniform || array.length % 2 !== 0)
  7808. return;
  7809. this._gl.uniform2fv(uniform, array);
  7810. };
  7811. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7812. if (!uniform || array.length % 3 !== 0)
  7813. return;
  7814. this._gl.uniform3fv(uniform, array);
  7815. };
  7816. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7817. if (!uniform || array.length % 4 !== 0)
  7818. return;
  7819. this._gl.uniform4fv(uniform, array);
  7820. };
  7821. Engine.prototype.setArray = function (uniform, array) {
  7822. if (!uniform)
  7823. return;
  7824. this._gl.uniform1fv(uniform, array);
  7825. };
  7826. Engine.prototype.setArray2 = function (uniform, array) {
  7827. if (!uniform || array.length % 2 !== 0)
  7828. return;
  7829. this._gl.uniform2fv(uniform, array);
  7830. };
  7831. Engine.prototype.setArray3 = function (uniform, array) {
  7832. if (!uniform || array.length % 3 !== 0)
  7833. return;
  7834. this._gl.uniform3fv(uniform, array);
  7835. };
  7836. Engine.prototype.setArray4 = function (uniform, array) {
  7837. if (!uniform || array.length % 4 !== 0)
  7838. return;
  7839. this._gl.uniform4fv(uniform, array);
  7840. };
  7841. Engine.prototype.setMatrices = function (uniform, matrices) {
  7842. if (!uniform)
  7843. return;
  7844. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7845. };
  7846. Engine.prototype.setMatrix = function (uniform, matrix) {
  7847. if (!uniform)
  7848. return;
  7849. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7850. };
  7851. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7852. if (!uniform)
  7853. return;
  7854. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7855. };
  7856. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7857. if (!uniform)
  7858. return;
  7859. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7860. };
  7861. Engine.prototype.setFloat = function (uniform, value) {
  7862. if (!uniform)
  7863. return;
  7864. this._gl.uniform1f(uniform, value);
  7865. };
  7866. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7867. if (!uniform)
  7868. return;
  7869. this._gl.uniform2f(uniform, x, y);
  7870. };
  7871. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7872. if (!uniform)
  7873. return;
  7874. this._gl.uniform3f(uniform, x, y, z);
  7875. };
  7876. Engine.prototype.setBool = function (uniform, bool) {
  7877. if (!uniform)
  7878. return;
  7879. this._gl.uniform1i(uniform, bool);
  7880. };
  7881. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7882. if (!uniform)
  7883. return;
  7884. this._gl.uniform4f(uniform, x, y, z, w);
  7885. };
  7886. Engine.prototype.setColor3 = function (uniform, color3) {
  7887. if (!uniform)
  7888. return;
  7889. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7890. };
  7891. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7892. if (!uniform)
  7893. return;
  7894. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7895. };
  7896. // States
  7897. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7898. if (zOffset === void 0) { zOffset = 0; }
  7899. if (reverseSide === void 0) { reverseSide = false; }
  7900. // Culling
  7901. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7902. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7903. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7904. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7905. if (culling) {
  7906. this._depthCullingState.cullFace = cullFace;
  7907. this._depthCullingState.cull = true;
  7908. }
  7909. else {
  7910. this._depthCullingState.cull = false;
  7911. }
  7912. }
  7913. // Z offset
  7914. this._depthCullingState.zOffset = zOffset;
  7915. };
  7916. Engine.prototype.setDepthBuffer = function (enable) {
  7917. this._depthCullingState.depthTest = enable;
  7918. };
  7919. Engine.prototype.getDepthWrite = function () {
  7920. return this._depthCullingState.depthMask;
  7921. };
  7922. Engine.prototype.setDepthWrite = function (enable) {
  7923. this._depthCullingState.depthMask = enable;
  7924. };
  7925. Engine.prototype.setColorWrite = function (enable) {
  7926. this._gl.colorMask(enable, enable, enable, enable);
  7927. };
  7928. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7929. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7930. if (this._alphaMode === mode) {
  7931. return;
  7932. }
  7933. switch (mode) {
  7934. case Engine.ALPHA_DISABLE:
  7935. this._alphaState.alphaBlend = false;
  7936. break;
  7937. case Engine.ALPHA_COMBINE:
  7938. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7939. this._alphaState.alphaBlend = true;
  7940. break;
  7941. case Engine.ALPHA_ONEONE:
  7942. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7943. this._alphaState.alphaBlend = true;
  7944. break;
  7945. case Engine.ALPHA_ADD:
  7946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7947. this._alphaState.alphaBlend = true;
  7948. break;
  7949. case Engine.ALPHA_SUBTRACT:
  7950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7951. this._alphaState.alphaBlend = true;
  7952. break;
  7953. case Engine.ALPHA_MULTIPLY:
  7954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7955. this._alphaState.alphaBlend = true;
  7956. break;
  7957. case Engine.ALPHA_MAXIMIZED:
  7958. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7959. this._alphaState.alphaBlend = true;
  7960. break;
  7961. }
  7962. if (!noDepthWriteChange) {
  7963. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7964. }
  7965. this._alphaMode = mode;
  7966. };
  7967. Engine.prototype.getAlphaMode = function () {
  7968. return this._alphaMode;
  7969. };
  7970. Engine.prototype.setAlphaTesting = function (enable) {
  7971. this._alphaTest = enable;
  7972. };
  7973. Engine.prototype.getAlphaTesting = function () {
  7974. return this._alphaTest;
  7975. };
  7976. // Textures
  7977. Engine.prototype.wipeCaches = function () {
  7978. this.resetTextureCache();
  7979. this._currentEffect = null;
  7980. this._stencilState.reset();
  7981. this._depthCullingState.reset();
  7982. this.setDepthFunctionToLessOrEqual();
  7983. this._alphaState.reset();
  7984. this._cachedVertexBuffers = null;
  7985. this._cachedIndexBuffer = null;
  7986. this._cachedEffectForVertexBuffers = null;
  7987. };
  7988. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7989. var gl = this._gl;
  7990. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7991. var magFilter = gl.NEAREST;
  7992. var minFilter = gl.NEAREST;
  7993. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7994. magFilter = gl.LINEAR;
  7995. minFilter = gl.LINEAR;
  7996. }
  7997. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7998. magFilter = gl.LINEAR;
  7999. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8000. }
  8001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  8002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  8003. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8004. texture.samplingMode = samplingMode;
  8005. };
  8006. /**
  8007. * Set the compressed texture format to use, based on the formats you have,
  8008. * the formats supported by the hardware / browser, and those currently implemented
  8009. * in BJS.
  8010. *
  8011. * Note: The result of this call is not taken into account texture is base64 or when
  8012. * using a database / manifest.
  8013. *
  8014. * @param {Array<string>} formatsAvailable - Extension names including dot. Case
  8015. * and order do not matter.
  8016. * @returns The extension selected.
  8017. */
  8018. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8019. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8020. // code to allow the formats to be added as they can be developed / hw tested
  8021. if (this._texturesSupported[i] === '.astc')
  8022. continue;
  8023. if (this._texturesSupported[i] === '.pvr')
  8024. continue;
  8025. if (this._texturesSupported[i] === '.etc1')
  8026. continue;
  8027. if (this._texturesSupported[i] === '.etc2')
  8028. continue;
  8029. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8030. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8031. return this._textureFormatInUse = this._texturesSupported[i];
  8032. }
  8033. }
  8034. }
  8035. // actively set format to nothing, to allow this to be called more than once
  8036. // and possibly fail the 2nd time
  8037. return this._textureFormatInUse = null;
  8038. };
  8039. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  8040. var _this = this;
  8041. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8042. if (onLoad === void 0) { onLoad = null; }
  8043. if (onError === void 0) { onError = null; }
  8044. if (buffer === void 0) { buffer = null; }
  8045. var texture = this._gl.createTexture();
  8046. var extension;
  8047. var fromData = false;
  8048. if (url.substr(0, 5) === "data:") {
  8049. fromData = true;
  8050. }
  8051. if (!fromData) {
  8052. var lastDot = url.lastIndexOf('.');
  8053. extension = url.substring(lastDot).toLowerCase();
  8054. if (this._textureFormatInUse && !fromData && !scene.database) {
  8055. extension = this._textureFormatInUse;
  8056. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8057. }
  8058. }
  8059. else {
  8060. var oldUrl = url;
  8061. fromData = oldUrl.split(':');
  8062. url = oldUrl;
  8063. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8064. }
  8065. var isDDS = (extension === ".dds");
  8066. var isTGA = (extension === ".tga");
  8067. scene._addPendingData(texture);
  8068. texture.url = url;
  8069. texture.noMipmap = noMipmap;
  8070. texture.references = 1;
  8071. texture.samplingMode = samplingMode;
  8072. texture.onLoadedCallbacks = [onLoad];
  8073. this._loadedTexturesCache.push(texture);
  8074. var onerror = function () {
  8075. scene._removePendingData(texture);
  8076. if (onError) {
  8077. onError();
  8078. }
  8079. };
  8080. var callback;
  8081. if (isTGA) {
  8082. callback = function (arrayBuffer) {
  8083. var data = new Uint8Array(arrayBuffer);
  8084. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8085. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8086. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8087. }, samplingMode);
  8088. };
  8089. if (!(fromData instanceof Array))
  8090. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  8091. callback(arrayBuffer);
  8092. }, null, scene.database, true, onerror);
  8093. else
  8094. callback(buffer);
  8095. }
  8096. else if (isDDS) {
  8097. callback = function (data) {
  8098. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8099. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8100. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8101. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8102. }, samplingMode);
  8103. };
  8104. if (!(fromData instanceof Array))
  8105. BABYLON.Tools.LoadFile(url, function (data) {
  8106. callback(data);
  8107. }, null, scene.database, true, onerror);
  8108. else
  8109. callback(buffer);
  8110. }
  8111. else {
  8112. var onload = function (img) {
  8113. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8114. var isPot = (img.width === potWidth && img.height === potHeight);
  8115. if (!isPot) {
  8116. _this._prepareWorkingCanvas();
  8117. _this._workingCanvas.width = potWidth;
  8118. _this._workingCanvas.height = potHeight;
  8119. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8120. _this._workingContext.imageSmoothingEnabled = false;
  8121. _this._workingContext.mozImageSmoothingEnabled = false;
  8122. _this._workingContext.oImageSmoothingEnabled = false;
  8123. _this._workingContext.webkitImageSmoothingEnabled = false;
  8124. _this._workingContext.msImageSmoothingEnabled = false;
  8125. }
  8126. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8127. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8128. _this._workingContext.imageSmoothingEnabled = true;
  8129. _this._workingContext.mozImageSmoothingEnabled = true;
  8130. _this._workingContext.oImageSmoothingEnabled = true;
  8131. _this._workingContext.webkitImageSmoothingEnabled = true;
  8132. _this._workingContext.msImageSmoothingEnabled = true;
  8133. }
  8134. }
  8135. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8136. }, samplingMode);
  8137. };
  8138. if (!(fromData instanceof Array))
  8139. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8140. else
  8141. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8142. }
  8143. return texture;
  8144. };
  8145. Engine.prototype._getInternalFormat = function (format) {
  8146. var internalFormat = this._gl.RGBA;
  8147. switch (format) {
  8148. case Engine.TEXTUREFORMAT_ALPHA:
  8149. internalFormat = this._gl.ALPHA;
  8150. break;
  8151. case Engine.TEXTUREFORMAT_LUMINANCE:
  8152. internalFormat = this._gl.LUMINANCE;
  8153. break;
  8154. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8155. internalFormat = this._gl.LUMINANCE_ALPHA;
  8156. break;
  8157. case Engine.TEXTUREFORMAT_RGB:
  8158. internalFormat = this._gl.RGB;
  8159. break;
  8160. case Engine.TEXTUREFORMAT_RGBA:
  8161. internalFormat = this._gl.RGBA;
  8162. break;
  8163. }
  8164. return internalFormat;
  8165. };
  8166. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8167. if (compression === void 0) { compression = null; }
  8168. var internalFormat = this._getInternalFormat(format);
  8169. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8170. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8171. if (texture._width % 4 !== 0) {
  8172. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8173. }
  8174. if (compression) {
  8175. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8176. }
  8177. else {
  8178. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8179. }
  8180. if (texture.generateMipMaps) {
  8181. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8182. }
  8183. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8184. this.resetTextureCache();
  8185. texture.isReady = true;
  8186. };
  8187. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8188. if (compression === void 0) { compression = null; }
  8189. var texture = this._gl.createTexture();
  8190. texture._baseWidth = width;
  8191. texture._baseHeight = height;
  8192. texture._width = width;
  8193. texture._height = height;
  8194. texture.references = 1;
  8195. this.updateRawTexture(texture, data, format, invertY, compression);
  8196. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8197. // Filters
  8198. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8199. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8200. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8201. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8202. texture.samplingMode = samplingMode;
  8203. this._loadedTexturesCache.push(texture);
  8204. return texture;
  8205. };
  8206. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8207. var texture = this._gl.createTexture();
  8208. texture._baseWidth = width;
  8209. texture._baseHeight = height;
  8210. if (generateMipMaps) {
  8211. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8212. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8213. }
  8214. this.resetTextureCache();
  8215. texture._width = width;
  8216. texture._height = height;
  8217. texture.isReady = false;
  8218. texture.generateMipMaps = generateMipMaps;
  8219. texture.references = 1;
  8220. texture.samplingMode = samplingMode;
  8221. this.updateTextureSamplingMode(samplingMode, texture);
  8222. this._loadedTexturesCache.push(texture);
  8223. return texture;
  8224. };
  8225. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8226. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8227. if (texture.isCube) {
  8228. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8229. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8230. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8231. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8232. }
  8233. else {
  8234. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8235. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8236. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8237. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8238. }
  8239. };
  8240. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8241. if (premulAlpha === void 0) { premulAlpha = false; }
  8242. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8243. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8244. if (premulAlpha) {
  8245. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8246. }
  8247. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8248. if (texture.generateMipMaps) {
  8249. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8250. }
  8251. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8252. if (premulAlpha) {
  8253. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8254. }
  8255. this.resetTextureCache();
  8256. texture.isReady = true;
  8257. };
  8258. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8259. if (texture._isDisabled) {
  8260. return;
  8261. }
  8262. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8263. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8264. try {
  8265. // Testing video texture support
  8266. if (this._videoTextureSupported === undefined) {
  8267. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8268. if (this._gl.getError() !== 0) {
  8269. this._videoTextureSupported = false;
  8270. }
  8271. else {
  8272. this._videoTextureSupported = true;
  8273. }
  8274. }
  8275. // Copy video through the current working canvas if video texture is not supported
  8276. if (!this._videoTextureSupported) {
  8277. if (!texture._workingCanvas) {
  8278. texture._workingCanvas = document.createElement("canvas");
  8279. texture._workingContext = texture._workingCanvas.getContext("2d");
  8280. texture._workingCanvas.width = texture._width;
  8281. texture._workingCanvas.height = texture._height;
  8282. }
  8283. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8284. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8285. }
  8286. else {
  8287. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8288. }
  8289. if (texture.generateMipMaps) {
  8290. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8291. }
  8292. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8293. this.resetTextureCache();
  8294. texture.isReady = true;
  8295. }
  8296. catch (ex) {
  8297. // Something unexpected
  8298. // Let's disable the texture
  8299. texture._isDisabled = true;
  8300. }
  8301. };
  8302. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8303. // old version had a "generateMipMaps" arg instead of options.
  8304. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8305. // in the same way, generateDepthBuffer is defaulted to true
  8306. var generateMipMaps = false;
  8307. var generateDepthBuffer = true;
  8308. var generateStencilBuffer = false;
  8309. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8310. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8311. if (options !== undefined) {
  8312. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8313. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8314. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8315. type = options.type === undefined ? type : options.type;
  8316. if (options.samplingMode !== undefined) {
  8317. samplingMode = options.samplingMode;
  8318. }
  8319. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8320. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8321. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8322. }
  8323. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8324. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8325. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8326. }
  8327. }
  8328. var gl = this._gl;
  8329. var texture = gl.createTexture();
  8330. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8331. var width = size.width || size;
  8332. var height = size.height || size;
  8333. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8334. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8335. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8336. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8337. }
  8338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8342. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8343. var depthStencilBuffer;
  8344. // Create the depth/stencil buffer
  8345. if (generateStencilBuffer) {
  8346. depthStencilBuffer = gl.createRenderbuffer();
  8347. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8348. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8349. }
  8350. else if (generateDepthBuffer) {
  8351. depthStencilBuffer = gl.createRenderbuffer();
  8352. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8353. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8354. }
  8355. // Create the framebuffer
  8356. var framebuffer = gl.createFramebuffer();
  8357. this.bindUnboundFramebuffer(framebuffer);
  8358. // Manage attachments
  8359. if (generateStencilBuffer) {
  8360. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8361. }
  8362. else if (generateDepthBuffer) {
  8363. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8364. }
  8365. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8366. if (generateMipMaps) {
  8367. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8368. }
  8369. // Unbind
  8370. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8371. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8372. this.bindUnboundFramebuffer(null);
  8373. texture._framebuffer = framebuffer;
  8374. if (generateDepthBuffer) {
  8375. texture._depthBuffer = depthStencilBuffer;
  8376. }
  8377. texture._baseWidth = width;
  8378. texture._baseHeight = height;
  8379. texture._width = width;
  8380. texture._height = height;
  8381. texture.isReady = true;
  8382. texture.generateMipMaps = generateMipMaps;
  8383. texture.references = 1;
  8384. texture.samplingMode = samplingMode;
  8385. texture.type = type;
  8386. this.resetTextureCache();
  8387. this._loadedTexturesCache.push(texture);
  8388. return texture;
  8389. };
  8390. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8391. var gl = this._gl;
  8392. var texture = gl.createTexture();
  8393. var generateMipMaps = true;
  8394. var generateDepthBuffer = true;
  8395. var generateStencilBuffer = false;
  8396. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8397. if (options !== undefined) {
  8398. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8399. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8400. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8401. if (options.samplingMode !== undefined) {
  8402. samplingMode = options.samplingMode;
  8403. }
  8404. }
  8405. texture.isCube = true;
  8406. texture.references = 1;
  8407. texture.generateMipMaps = generateMipMaps;
  8408. texture.references = 1;
  8409. texture.samplingMode = samplingMode;
  8410. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8411. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8412. for (var face = 0; face < 6; face++) {
  8413. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8414. }
  8415. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8416. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8417. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8419. // Create the depth buffer
  8420. var depthStencilBuffer;
  8421. // Create the depth/stencil buffer
  8422. if (generateStencilBuffer) {
  8423. depthStencilBuffer = gl.createRenderbuffer();
  8424. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8425. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8426. }
  8427. else if (generateDepthBuffer) {
  8428. depthStencilBuffer = gl.createRenderbuffer();
  8429. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8430. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8431. }
  8432. // Create the framebuffer
  8433. var framebuffer = gl.createFramebuffer();
  8434. this.bindUnboundFramebuffer(framebuffer);
  8435. // Manage attachments
  8436. if (generateStencilBuffer) {
  8437. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8438. }
  8439. else if (generateDepthBuffer) {
  8440. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8441. }
  8442. // Mipmaps
  8443. if (texture.generateMipMaps) {
  8444. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8445. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8446. }
  8447. // Unbind
  8448. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8449. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8450. this.bindUnboundFramebuffer(null);
  8451. texture._framebuffer = framebuffer;
  8452. if (generateDepthBuffer) {
  8453. texture._depthBuffer = depthStencilBuffer;
  8454. }
  8455. texture._width = size;
  8456. texture._height = size;
  8457. texture.isReady = true;
  8458. this.resetTextureCache();
  8459. this._loadedTexturesCache.push(texture);
  8460. return texture;
  8461. };
  8462. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8463. var _this = this;
  8464. if (onLoad === void 0) { onLoad = null; }
  8465. if (onError === void 0) { onError = null; }
  8466. var gl = this._gl;
  8467. var texture = gl.createTexture();
  8468. texture.isCube = true;
  8469. texture.url = rootUrl;
  8470. texture.references = 1;
  8471. texture.onLoadedCallbacks = [];
  8472. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8473. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8474. if (isDDS) {
  8475. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8476. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8477. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8478. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8479. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8480. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8481. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8482. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8483. }
  8484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8488. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8489. _this.resetTextureCache();
  8490. texture._width = info.width;
  8491. texture._height = info.height;
  8492. texture.isReady = true;
  8493. }, null, null, true, onError);
  8494. }
  8495. else {
  8496. cascadeLoad(rootUrl, scene, function (imgs) {
  8497. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8498. var height = width;
  8499. _this._prepareWorkingCanvas();
  8500. _this._workingCanvas.width = width;
  8501. _this._workingCanvas.height = height;
  8502. var faces = [
  8503. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8504. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8505. ];
  8506. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8507. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8508. for (var index = 0; index < faces.length; index++) {
  8509. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8510. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8511. }
  8512. if (!noMipmap) {
  8513. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8514. }
  8515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8519. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8520. _this.resetTextureCache();
  8521. texture._width = width;
  8522. texture._height = height;
  8523. texture.isReady = true;
  8524. texture.onLoadedCallbacks.forEach(function (callback) {
  8525. callback();
  8526. });
  8527. if (onLoad) {
  8528. onLoad();
  8529. }
  8530. }, files, onError);
  8531. }
  8532. this._loadedTexturesCache.push(texture);
  8533. return texture;
  8534. };
  8535. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8536. texture._width = width;
  8537. texture._height = height;
  8538. texture._size = width * height;
  8539. texture._baseWidth = width;
  8540. texture._baseHeight = height;
  8541. };
  8542. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8543. var _this = this;
  8544. var gl = this._gl;
  8545. var texture = gl.createTexture();
  8546. scene._addPendingData(texture);
  8547. texture.isCube = true;
  8548. texture.references = 1;
  8549. texture.url = url;
  8550. var internalFormat = this._getInternalFormat(format);
  8551. var textureType = gl.UNSIGNED_BYTE;
  8552. if (type === Engine.TEXTURETYPE_FLOAT) {
  8553. textureType = gl.FLOAT;
  8554. }
  8555. var width = size;
  8556. var height = width;
  8557. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8558. texture._width = width;
  8559. texture._height = height;
  8560. var onerror = function () {
  8561. scene._removePendingData(texture);
  8562. };
  8563. var internalCallback = function (data) {
  8564. var rgbeDataArrays = callback(data);
  8565. var facesIndex = [
  8566. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8567. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8568. ];
  8569. width = texture._width;
  8570. height = texture._height;
  8571. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8572. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8573. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8574. if (!noMipmap && isPot) {
  8575. if (mipmmapGenerator) {
  8576. var arrayTemp = [];
  8577. // Data are known to be in +X +Y +Z -X -Y -Z
  8578. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8579. arrayTemp.push(rgbeDataArrays[0]); // +X
  8580. arrayTemp.push(rgbeDataArrays[3]); // -X
  8581. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8582. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8583. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8584. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8585. var mipData = mipmmapGenerator(arrayTemp);
  8586. for (var level = 0; level < mipData.length; level++) {
  8587. var mipSize = width >> level;
  8588. // mipData is order in +X -X +Y -Y +Z -Z
  8589. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8590. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8591. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8592. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8593. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8594. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8595. }
  8596. }
  8597. else {
  8598. // Data are known to be in +X +Y +Z -X -Y -Z
  8599. for (var index = 0; index < facesIndex.length; index++) {
  8600. var faceData = rgbeDataArrays[index];
  8601. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8602. }
  8603. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8604. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8605. // By following the webgl standard changes from Revision 7, 2014/11/24
  8606. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8607. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8608. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8609. // Data are known to be in +X +Y +Z -X -Y -Z
  8610. for (var index = 0; index < facesIndex.length; index++) {
  8611. var faceData = rgbeDataArrays[index];
  8612. // Create a new RGBA Face.
  8613. var newFaceData = new Float32Array(width * height * 4);
  8614. for (var x = 0; x < width; x++) {
  8615. for (var y = 0; y < height; y++) {
  8616. var index_1 = (y * width + x) * 3;
  8617. var newIndex = (y * width + x) * 4;
  8618. // Map Old Value to new value.
  8619. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8620. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8621. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8622. // Add fully opaque alpha channel.
  8623. newFaceData[newIndex + 3] = 1;
  8624. }
  8625. }
  8626. // Reupload the face.
  8627. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8628. }
  8629. // Try to generate mipmap again.
  8630. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8631. }
  8632. }
  8633. }
  8634. else {
  8635. noMipmap = true;
  8636. }
  8637. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8640. }
  8641. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8643. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8644. }
  8645. else {
  8646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8648. }
  8649. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8650. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8651. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8652. texture.isReady = true;
  8653. _this.resetTextureCache();
  8654. scene._removePendingData(texture);
  8655. };
  8656. BABYLON.Tools.LoadFile(url, function (data) {
  8657. internalCallback(data);
  8658. }, onerror, scene.database, true);
  8659. return texture;
  8660. };
  8661. ;
  8662. Engine.prototype._releaseTexture = function (texture) {
  8663. var gl = this._gl;
  8664. if (texture._framebuffer) {
  8665. gl.deleteFramebuffer(texture._framebuffer);
  8666. }
  8667. if (texture._depthBuffer) {
  8668. gl.deleteRenderbuffer(texture._depthBuffer);
  8669. }
  8670. gl.deleteTexture(texture);
  8671. // Unbind channels
  8672. this.unbindAllTextures();
  8673. var index = this._loadedTexturesCache.indexOf(texture);
  8674. if (index !== -1) {
  8675. this._loadedTexturesCache.splice(index, 1);
  8676. }
  8677. };
  8678. Engine.prototype.setProgram = function (program) {
  8679. if (this._currentProgram !== program) {
  8680. this._gl.useProgram(program);
  8681. this._currentProgram = program;
  8682. }
  8683. };
  8684. Engine.prototype.bindSamplers = function (effect) {
  8685. this.setProgram(effect.getProgram());
  8686. var samplers = effect.getSamplers();
  8687. for (var index = 0; index < samplers.length; index++) {
  8688. var uniform = effect.getUniform(samplers[index]);
  8689. this._gl.uniform1i(uniform, index);
  8690. }
  8691. this._currentEffect = null;
  8692. };
  8693. Engine.prototype.activateTexture = function (texture) {
  8694. if (this._activeTexture !== texture) {
  8695. this._gl.activeTexture(texture);
  8696. this._activeTexture = texture;
  8697. }
  8698. };
  8699. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8700. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8701. this._gl.bindTexture(target, texture);
  8702. this._activeTexturesCache[this._activeTexture] = texture;
  8703. }
  8704. };
  8705. Engine.prototype._bindTexture = function (channel, texture) {
  8706. if (channel < 0) {
  8707. return;
  8708. }
  8709. this.activateTexture(this._gl["TEXTURE" + channel]);
  8710. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8711. };
  8712. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8713. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8714. };
  8715. Engine.prototype.unbindAllTextures = function () {
  8716. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8717. this.activateTexture(this._gl["TEXTURE" + channel]);
  8718. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8719. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8720. }
  8721. };
  8722. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8723. if (channel < 0) {
  8724. return;
  8725. }
  8726. this._gl.uniform1i(uniform, channel);
  8727. this._setTexture(channel, texture);
  8728. };
  8729. Engine.prototype._setTexture = function (channel, texture) {
  8730. // Not ready?
  8731. if (!texture || !texture.isReady()) {
  8732. if (this._activeTexturesCache[channel] != null) {
  8733. this.activateTexture(this._gl["TEXTURE" + channel]);
  8734. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8735. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8736. }
  8737. return;
  8738. }
  8739. // Video
  8740. var alreadyActivated = false;
  8741. if (texture instanceof BABYLON.VideoTexture) {
  8742. this.activateTexture(this._gl["TEXTURE" + channel]);
  8743. alreadyActivated = true;
  8744. texture.update();
  8745. }
  8746. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8747. texture.delayLoad();
  8748. return;
  8749. }
  8750. var internalTexture = texture.getInternalTexture();
  8751. if (this._activeTexturesCache[channel] === internalTexture) {
  8752. return;
  8753. }
  8754. if (!alreadyActivated) {
  8755. this.activateTexture(this._gl["TEXTURE" + channel]);
  8756. }
  8757. if (internalTexture.isCube) {
  8758. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8759. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8760. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8761. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8762. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8763. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8764. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8765. }
  8766. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8767. }
  8768. else {
  8769. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8770. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8771. internalTexture._cachedWrapU = texture.wrapU;
  8772. switch (texture.wrapU) {
  8773. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8774. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8775. break;
  8776. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8777. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8778. break;
  8779. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8780. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8781. break;
  8782. }
  8783. }
  8784. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8785. internalTexture._cachedWrapV = texture.wrapV;
  8786. switch (texture.wrapV) {
  8787. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8788. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8789. break;
  8790. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8791. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, 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_T, this._gl.MIRRORED_REPEAT);
  8795. break;
  8796. }
  8797. }
  8798. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8799. }
  8800. };
  8801. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8802. if (channel < 0) {
  8803. return;
  8804. }
  8805. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8806. this._textureUnits = new Int32Array(textures.length);
  8807. }
  8808. for (var i = 0; i < textures.length; i++) {
  8809. this._textureUnits[i] = channel + i;
  8810. }
  8811. this._gl.uniform1iv(uniform, this._textureUnits);
  8812. for (var index = 0; index < textures.length; index++) {
  8813. this._setTexture(channel + index, textures[index]);
  8814. }
  8815. };
  8816. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8817. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8818. var value = texture.anisotropicFilteringLevel;
  8819. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8820. value = 1;
  8821. }
  8822. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8823. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8824. texture._cachedAnisotropicFilteringLevel = value;
  8825. }
  8826. };
  8827. Engine.prototype.readPixels = function (x, y, width, height) {
  8828. var data = new Uint8Array(height * width * 4);
  8829. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8830. return data;
  8831. };
  8832. /**
  8833. * Add an externaly attached data from its key.
  8834. * This method call will fail and return false, if such key already exists.
  8835. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8836. * @param key the unique key that identifies the data
  8837. * @param data the data object to associate to the key for this Engine instance
  8838. * @return true if no such key were already present and the data was added successfully, false otherwise
  8839. */
  8840. Engine.prototype.addExternalData = function (key, data) {
  8841. return this._externalData.add(key, data);
  8842. };
  8843. /**
  8844. * Get an externaly attached data from its key
  8845. * @param key the unique key that identifies the data
  8846. * @return the associated data, if present (can be null), or undefined if not present
  8847. */
  8848. Engine.prototype.getExternalData = function (key) {
  8849. return this._externalData.get(key);
  8850. };
  8851. /**
  8852. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8853. * @param key the unique key that identifies the data
  8854. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8855. * @return the associated data, can be null if the factory returned null.
  8856. */
  8857. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8858. return this._externalData.getOrAddWithFactory(key, factory);
  8859. };
  8860. /**
  8861. * Remove an externaly attached data from the Engine instance
  8862. * @param key the unique key that identifies the data
  8863. * @return true if the data was successfully removed, false if it doesn't exist
  8864. */
  8865. Engine.prototype.removeExternalData = function (key) {
  8866. return this._externalData.remove(key);
  8867. };
  8868. Engine.prototype.releaseInternalTexture = function (texture) {
  8869. if (!texture) {
  8870. return;
  8871. }
  8872. texture.references--;
  8873. // Final reference ?
  8874. if (texture.references === 0) {
  8875. var texturesCache = this.getLoadedTexturesCache();
  8876. var index = texturesCache.indexOf(texture);
  8877. if (index > -1) {
  8878. texturesCache.splice(index, 1);
  8879. }
  8880. this._releaseTexture(texture);
  8881. }
  8882. };
  8883. Engine.prototype.unbindAllAttributes = function () {
  8884. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8885. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8886. continue;
  8887. }
  8888. if (this._vertexAttribArraysEnabled[i]) {
  8889. this._gl.disableVertexAttribArray(i);
  8890. this._vertexAttribArraysEnabled[i] = false;
  8891. }
  8892. }
  8893. };
  8894. // Dispose
  8895. Engine.prototype.dispose = function () {
  8896. this.hideLoadingUI();
  8897. this.stopRenderLoop();
  8898. // Release scenes
  8899. while (this.scenes.length) {
  8900. this.scenes[0].dispose();
  8901. }
  8902. // Release audio engine
  8903. Engine.audioEngine.dispose();
  8904. // Release effects
  8905. for (var name in this._compiledEffects) {
  8906. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8907. }
  8908. // Unbind
  8909. this.unbindAllAttributes();
  8910. this._gl = null;
  8911. //WebVR
  8912. this.disableVR();
  8913. // Events
  8914. window.removeEventListener("blur", this._onBlur);
  8915. window.removeEventListener("focus", this._onFocus);
  8916. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8917. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8918. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8919. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8920. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8921. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8922. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8923. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8924. };
  8925. // Loading screen
  8926. Engine.prototype.displayLoadingUI = function () {
  8927. this._loadingScreen.displayLoadingUI();
  8928. };
  8929. Engine.prototype.hideLoadingUI = function () {
  8930. this._loadingScreen.hideLoadingUI();
  8931. };
  8932. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8933. get: function () {
  8934. return this._loadingScreen;
  8935. },
  8936. set: function (loadingScreen) {
  8937. this._loadingScreen = loadingScreen;
  8938. },
  8939. enumerable: true,
  8940. configurable: true
  8941. });
  8942. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8943. set: function (text) {
  8944. this._loadingScreen.loadingUIText = text;
  8945. },
  8946. enumerable: true,
  8947. configurable: true
  8948. });
  8949. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8950. set: function (color) {
  8951. this._loadingScreen.loadingUIBackgroundColor = color;
  8952. },
  8953. enumerable: true,
  8954. configurable: true
  8955. });
  8956. Engine.prototype.attachContextLostEvent = function (callback) {
  8957. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8958. };
  8959. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8960. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8961. };
  8962. Engine.prototype.getVertexShaderSource = function (program) {
  8963. var shaders = this._gl.getAttachedShaders(program);
  8964. return this._gl.getShaderSource(shaders[0]);
  8965. };
  8966. Engine.prototype.getFragmentShaderSource = function (program) {
  8967. var shaders = this._gl.getAttachedShaders(program);
  8968. return this._gl.getShaderSource(shaders[1]);
  8969. };
  8970. // FPS
  8971. Engine.prototype.getFps = function () {
  8972. return this.fps;
  8973. };
  8974. Engine.prototype.getDeltaTime = function () {
  8975. return this.deltaTime;
  8976. };
  8977. Engine.prototype._measureFps = function () {
  8978. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8979. var length = this.previousFramesDuration.length;
  8980. if (length >= 2) {
  8981. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8982. }
  8983. if (length >= this.fpsRange) {
  8984. if (length > this.fpsRange) {
  8985. this.previousFramesDuration.splice(0, 1);
  8986. length = this.previousFramesDuration.length;
  8987. }
  8988. var sum = 0;
  8989. for (var id = 0; id < length - 1; id++) {
  8990. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8991. }
  8992. this.fps = 1000.0 / (sum / (length - 1));
  8993. }
  8994. };
  8995. Engine.prototype._canRenderToFloatTexture = function () {
  8996. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8997. };
  8998. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8999. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  9000. };
  9001. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9002. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  9003. var tempcanvas = document.createElement("canvas");
  9004. tempcanvas.height = 16;
  9005. tempcanvas.width = 16;
  9006. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  9007. // extension.
  9008. var ext = gl.getExtension(extension);
  9009. if (!ext) {
  9010. return false;
  9011. }
  9012. // setup GLSL program
  9013. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  9014. 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 }";
  9015. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  9016. gl.useProgram(program);
  9017. // look up where the vertex data needs to go.
  9018. var positionLocation = gl.getAttribLocation(program, "a_position");
  9019. var colorLoc = gl.getUniformLocation(program, "u_color");
  9020. // provide texture coordinates for the rectangle.
  9021. var positionBuffer = gl.createBuffer();
  9022. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  9023. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  9024. -1.0, -1.0,
  9025. 1.0, -1.0,
  9026. -1.0, 1.0,
  9027. -1.0, 1.0,
  9028. 1.0, -1.0,
  9029. 1.0, 1.0
  9030. ]), gl.STATIC_DRAW);
  9031. gl.enableVertexAttribArray(positionLocation);
  9032. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  9033. var whiteTex = gl.createTexture();
  9034. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9035. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  9036. var tex = gl.createTexture();
  9037. gl.bindTexture(gl.TEXTURE_2D, tex);
  9038. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  9039. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9040. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9041. var fb = gl.createFramebuffer();
  9042. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9043. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  9044. var cleanup = function () {
  9045. gl.deleteProgram(program);
  9046. gl.disableVertexAttribArray(positionLocation);
  9047. gl.deleteBuffer(positionBuffer);
  9048. gl.deleteFramebuffer(fb);
  9049. gl.deleteTexture(whiteTex);
  9050. gl.deleteTexture(tex);
  9051. };
  9052. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9053. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  9054. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  9055. cleanup();
  9056. return false;
  9057. }
  9058. // Draw the rectangle.
  9059. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9060. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  9061. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9062. gl.bindTexture(gl.TEXTURE_2D, tex);
  9063. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9064. gl.clearColor(1, 0, 0, 1);
  9065. gl.clear(gl.COLOR_BUFFER_BIT);
  9066. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  9067. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9068. var pixel = new Uint8Array(4);
  9069. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  9070. if (pixel[0] !== 0 ||
  9071. pixel[1] < 248 ||
  9072. pixel[2] < 248 ||
  9073. pixel[3] < 254) {
  9074. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  9075. cleanup();
  9076. return false;
  9077. }
  9078. // Succesfully rendered to "format" texture.
  9079. cleanup();
  9080. return true;
  9081. };
  9082. // Statics
  9083. Engine.isSupported = function () {
  9084. try {
  9085. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9086. if (navigator.isCocoonJS) {
  9087. return true;
  9088. }
  9089. var tempcanvas = document.createElement("canvas");
  9090. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9091. return gl != null && !!window.WebGLRenderingContext;
  9092. }
  9093. catch (e) {
  9094. return false;
  9095. }
  9096. };
  9097. return Engine;
  9098. }());
  9099. // Const statics
  9100. Engine._ALPHA_DISABLE = 0;
  9101. Engine._ALPHA_ADD = 1;
  9102. Engine._ALPHA_COMBINE = 2;
  9103. Engine._ALPHA_SUBTRACT = 3;
  9104. Engine._ALPHA_MULTIPLY = 4;
  9105. Engine._ALPHA_MAXIMIZED = 5;
  9106. Engine._ALPHA_ONEONE = 6;
  9107. Engine._DELAYLOADSTATE_NONE = 0;
  9108. Engine._DELAYLOADSTATE_LOADED = 1;
  9109. Engine._DELAYLOADSTATE_LOADING = 2;
  9110. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9111. Engine._TEXTUREFORMAT_ALPHA = 0;
  9112. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9113. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9114. Engine._TEXTUREFORMAT_RGB = 4;
  9115. Engine._TEXTUREFORMAT_RGBA = 5;
  9116. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9117. Engine._TEXTURETYPE_FLOAT = 1;
  9118. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9119. // Depht or Stencil test Constants.
  9120. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9121. 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.
  9122. 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.
  9123. 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.
  9124. 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.
  9125. 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.
  9126. 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.
  9127. 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.
  9128. // Stencil Actions Constants.
  9129. Engine._KEEP = 0x1E00;
  9130. Engine._REPLACE = 0x1E01;
  9131. Engine._INCR = 0x1E02;
  9132. Engine._DECR = 0x1E03;
  9133. Engine._INVERT = 0x150A;
  9134. Engine._INCR_WRAP = 0x8507;
  9135. Engine._DECR_WRAP = 0x8508;
  9136. // Updatable statics so stick with vars here
  9137. Engine.CollisionsEpsilon = 0.001;
  9138. Engine.CodeRepository = "src/";
  9139. Engine.ShadersRepository = "src/Shaders/";
  9140. BABYLON.Engine = Engine;
  9141. })(BABYLON || (BABYLON = {}));
  9142. //# sourceMappingURL=babylon.engine.js.map
  9143. var BABYLON;
  9144. (function (BABYLON) {
  9145. /**
  9146. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9147. */
  9148. var Node = (function () {
  9149. /**
  9150. * @constructor
  9151. * @param {string} name - the name and id to be given to this node
  9152. * @param {BABYLON.Scene} the scene this node will be added to
  9153. */
  9154. function Node(name, scene) {
  9155. this.state = "";
  9156. this.metadata = null;
  9157. this.doNotSerialize = false;
  9158. this.animations = new Array();
  9159. this._ranges = {};
  9160. this._childrenFlag = -1;
  9161. this._isEnabled = true;
  9162. this._isReady = true;
  9163. this._currentRenderId = -1;
  9164. this._parentRenderId = -1;
  9165. /**
  9166. * An event triggered when the mesh is disposed.
  9167. * @type {BABYLON.Observable}
  9168. */
  9169. this.onDisposeObservable = new BABYLON.Observable();
  9170. this.name = name;
  9171. this.id = name;
  9172. this._scene = scene;
  9173. this._initCache();
  9174. }
  9175. Object.defineProperty(Node.prototype, "parent", {
  9176. get: function () {
  9177. return this._parentNode;
  9178. },
  9179. set: function (parent) {
  9180. if (this._parentNode === parent) {
  9181. return;
  9182. }
  9183. if (this._parentNode) {
  9184. var index = this._parentNode._children.indexOf(this);
  9185. if (index !== -1) {
  9186. this._parentNode._children.splice(index, 1);
  9187. }
  9188. }
  9189. this._parentNode = parent;
  9190. if (this._parentNode) {
  9191. if (!this._parentNode._children) {
  9192. this._parentNode._children = new Array();
  9193. }
  9194. this._parentNode._children.push(this);
  9195. }
  9196. },
  9197. enumerable: true,
  9198. configurable: true
  9199. });
  9200. Node.prototype.getClassName = function () {
  9201. return "Node";
  9202. };
  9203. Object.defineProperty(Node.prototype, "onDispose", {
  9204. set: function (callback) {
  9205. if (this._onDisposeObserver) {
  9206. this.onDisposeObservable.remove(this._onDisposeObserver);
  9207. }
  9208. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9209. },
  9210. enumerable: true,
  9211. configurable: true
  9212. });
  9213. Node.prototype.getScene = function () {
  9214. return this._scene;
  9215. };
  9216. Node.prototype.getEngine = function () {
  9217. return this._scene.getEngine();
  9218. };
  9219. // override it in derived class
  9220. Node.prototype.getWorldMatrix = function () {
  9221. return BABYLON.Matrix.Identity();
  9222. };
  9223. // override it in derived class if you add new variables to the cache
  9224. // and call the parent class method
  9225. Node.prototype._initCache = function () {
  9226. this._cache = {};
  9227. this._cache.parent = undefined;
  9228. };
  9229. Node.prototype.updateCache = function (force) {
  9230. if (!force && this.isSynchronized())
  9231. return;
  9232. this._cache.parent = this.parent;
  9233. this._updateCache();
  9234. };
  9235. // override it in derived class if you add new variables to the cache
  9236. // and call the parent class method if !ignoreParentClass
  9237. Node.prototype._updateCache = function (ignoreParentClass) {
  9238. };
  9239. // override it in derived class if you add new variables to the cache
  9240. Node.prototype._isSynchronized = function () {
  9241. return true;
  9242. };
  9243. Node.prototype._markSyncedWithParent = function () {
  9244. this._parentRenderId = this.parent._currentRenderId;
  9245. };
  9246. Node.prototype.isSynchronizedWithParent = function () {
  9247. if (!this.parent) {
  9248. return true;
  9249. }
  9250. if (this._parentRenderId !== this.parent._currentRenderId) {
  9251. return false;
  9252. }
  9253. return this.parent.isSynchronized();
  9254. };
  9255. Node.prototype.isSynchronized = function (updateCache) {
  9256. var check = this.hasNewParent();
  9257. check = check || !this.isSynchronizedWithParent();
  9258. check = check || !this._isSynchronized();
  9259. if (updateCache)
  9260. this.updateCache(true);
  9261. return !check;
  9262. };
  9263. Node.prototype.hasNewParent = function (update) {
  9264. if (this._cache.parent === this.parent)
  9265. return false;
  9266. if (update)
  9267. this._cache.parent = this.parent;
  9268. return true;
  9269. };
  9270. /**
  9271. * Is this node ready to be used/rendered
  9272. * @return {boolean} is it ready
  9273. */
  9274. Node.prototype.isReady = function () {
  9275. return this._isReady;
  9276. };
  9277. /**
  9278. * Is this node enabled.
  9279. * If the node has a parent and is enabled, the parent will be inspected as well.
  9280. * @return {boolean} whether this node (and its parent) is enabled.
  9281. * @see setEnabled
  9282. */
  9283. Node.prototype.isEnabled = function () {
  9284. if (!this._isEnabled) {
  9285. return false;
  9286. }
  9287. if (this.parent) {
  9288. return this.parent.isEnabled();
  9289. }
  9290. return true;
  9291. };
  9292. /**
  9293. * Set the enabled state of this node.
  9294. * @param {boolean} value - the new enabled state
  9295. * @see isEnabled
  9296. */
  9297. Node.prototype.setEnabled = function (value) {
  9298. this._isEnabled = value;
  9299. };
  9300. /**
  9301. * Is this node a descendant of the given node.
  9302. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9303. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9304. * @see parent
  9305. */
  9306. Node.prototype.isDescendantOf = function (ancestor) {
  9307. if (this.parent) {
  9308. if (this.parent === ancestor) {
  9309. return true;
  9310. }
  9311. return this.parent.isDescendantOf(ancestor);
  9312. }
  9313. return false;
  9314. };
  9315. /**
  9316. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9317. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9318. * @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.
  9319. * @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.
  9320. */
  9321. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9322. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9323. if (!this._children) {
  9324. return;
  9325. }
  9326. for (var index = 0; index < this._children.length; index++) {
  9327. var item = this._children[index];
  9328. if (!predicate || predicate(item)) {
  9329. results.push(item);
  9330. }
  9331. if (!directDescendantsOnly) {
  9332. item._getDescendants(results, false, predicate);
  9333. }
  9334. }
  9335. };
  9336. /**
  9337. * Will return all nodes that have this node as ascendant.
  9338. * @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.
  9339. * @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.
  9340. * @return {BABYLON.Node[]} all children nodes of all types.
  9341. */
  9342. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9343. var results = [];
  9344. this._getDescendants(results, directDescendantsOnly, predicate);
  9345. return results;
  9346. };
  9347. /**
  9348. * @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.
  9349. * @Deprecated, legacy support.
  9350. * use getDecendants instead.
  9351. */
  9352. Node.prototype.getChildren = function (predicate) {
  9353. return this.getDescendants(true, predicate);
  9354. };
  9355. /**
  9356. * Get all child-meshes of this node.
  9357. */
  9358. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9359. var results = [];
  9360. this._getDescendants(results, directDecendantsOnly, function (node) {
  9361. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9362. });
  9363. return results;
  9364. };
  9365. Node.prototype._setReady = function (state) {
  9366. if (state === this._isReady) {
  9367. return;
  9368. }
  9369. if (!state) {
  9370. this._isReady = false;
  9371. return;
  9372. }
  9373. this._isReady = true;
  9374. if (this.onReady) {
  9375. this.onReady(this);
  9376. }
  9377. };
  9378. Node.prototype.getAnimationByName = function (name) {
  9379. for (var i = 0; i < this.animations.length; i++) {
  9380. var animation = this.animations[i];
  9381. if (animation.name === name) {
  9382. return animation;
  9383. }
  9384. }
  9385. return null;
  9386. };
  9387. Node.prototype.createAnimationRange = function (name, from, to) {
  9388. // check name not already in use
  9389. if (!this._ranges[name]) {
  9390. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9391. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9392. if (this.animations[i]) {
  9393. this.animations[i].createRange(name, from, to);
  9394. }
  9395. }
  9396. }
  9397. };
  9398. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9399. if (deleteFrames === void 0) { deleteFrames = true; }
  9400. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9401. if (this.animations[i]) {
  9402. this.animations[i].deleteRange(name, deleteFrames);
  9403. }
  9404. }
  9405. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9406. };
  9407. Node.prototype.getAnimationRange = function (name) {
  9408. return this._ranges[name];
  9409. };
  9410. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9411. var range = this.getAnimationRange(name);
  9412. if (!range) {
  9413. return null;
  9414. }
  9415. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9416. };
  9417. Node.prototype.serializeAnimationRanges = function () {
  9418. var serializationRanges = [];
  9419. for (var name in this._ranges) {
  9420. var range = {};
  9421. range.name = name;
  9422. range.from = this._ranges[name].from;
  9423. range.to = this._ranges[name].to;
  9424. serializationRanges.push(range);
  9425. }
  9426. return serializationRanges;
  9427. };
  9428. Node.prototype.dispose = function () {
  9429. this.parent = null;
  9430. // Callback
  9431. this.onDisposeObservable.notifyObservers(this);
  9432. this.onDisposeObservable.clear();
  9433. };
  9434. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9435. if (parsedNode.ranges) {
  9436. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9437. var data = parsedNode.ranges[index];
  9438. node.createAnimationRange(data.name, data.from, data.to);
  9439. }
  9440. }
  9441. };
  9442. return Node;
  9443. }());
  9444. __decorate([
  9445. BABYLON.serialize()
  9446. ], Node.prototype, "name", void 0);
  9447. __decorate([
  9448. BABYLON.serialize()
  9449. ], Node.prototype, "id", void 0);
  9450. __decorate([
  9451. BABYLON.serialize()
  9452. ], Node.prototype, "uniqueId", void 0);
  9453. __decorate([
  9454. BABYLON.serialize()
  9455. ], Node.prototype, "state", void 0);
  9456. __decorate([
  9457. BABYLON.serialize()
  9458. ], Node.prototype, "metadata", void 0);
  9459. BABYLON.Node = Node;
  9460. })(BABYLON || (BABYLON = {}));
  9461. //# sourceMappingURL=babylon.node.js.map
  9462. var BABYLON;
  9463. (function (BABYLON) {
  9464. var FilesInput = (function () {
  9465. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9466. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9467. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9468. this._engine = p_engine;
  9469. this._canvas = p_canvas;
  9470. this._currentScene = p_scene;
  9471. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9472. this._progressCallback = p_progressCallback;
  9473. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9474. this._textureLoadingCallback = p_textureLoadingCallback;
  9475. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9476. }
  9477. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9478. var _this = this;
  9479. if (p_elementToMonitor) {
  9480. this._elementToMonitor = p_elementToMonitor;
  9481. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9482. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9483. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9484. }
  9485. };
  9486. FilesInput.prototype.renderFunction = function () {
  9487. if (this._additionnalRenderLoopLogicCallback) {
  9488. this._additionnalRenderLoopLogicCallback();
  9489. }
  9490. if (this._currentScene) {
  9491. if (this._textureLoadingCallback) {
  9492. var remaining = this._currentScene.getWaitingItemsCount();
  9493. if (remaining > 0) {
  9494. this._textureLoadingCallback(remaining);
  9495. }
  9496. }
  9497. this._currentScene.render();
  9498. }
  9499. };
  9500. FilesInput.prototype.drag = function (e) {
  9501. e.stopPropagation();
  9502. e.preventDefault();
  9503. };
  9504. FilesInput.prototype.drop = function (eventDrop) {
  9505. eventDrop.stopPropagation();
  9506. eventDrop.preventDefault();
  9507. this.loadFiles(eventDrop);
  9508. };
  9509. FilesInput.prototype.loadFiles = function (event) {
  9510. if (this._startingProcessingFilesCallback)
  9511. this._startingProcessingFilesCallback();
  9512. // Handling data transfer via drag'n'drop
  9513. if (event && event.dataTransfer && event.dataTransfer.files) {
  9514. this._filesToLoad = event.dataTransfer.files;
  9515. }
  9516. // Handling files from input files
  9517. if (event && event.target && event.target.files) {
  9518. this._filesToLoad = event.target.files;
  9519. }
  9520. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9521. for (var i = 0; i < this._filesToLoad.length; i++) {
  9522. switch (this._filesToLoad[i].type) {
  9523. case "image/jpeg":
  9524. case "image/png":
  9525. case "image/bmp":
  9526. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9527. break;
  9528. case "image/targa":
  9529. case "image/vnd.ms-dds":
  9530. case "audio/wav":
  9531. case "audio/x-wav":
  9532. case "audio/mp3":
  9533. case "audio/mpeg":
  9534. case "audio/mpeg3":
  9535. case "audio/x-mpeg-3":
  9536. case "audio/ogg":
  9537. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9538. break;
  9539. default:
  9540. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9541. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9542. }
  9543. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9544. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9545. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9546. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9547. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9548. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9549. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9550. this._sceneFileToLoad = this._filesToLoad[i];
  9551. }
  9552. break;
  9553. }
  9554. }
  9555. this.reload();
  9556. }
  9557. };
  9558. FilesInput.prototype.reload = function () {
  9559. var _this = this;
  9560. var that = this;
  9561. // If a ".babylon" file has been provided
  9562. if (this._sceneFileToLoad) {
  9563. if (this._currentScene) {
  9564. if (BABYLON.Tools.errorsCount > 0) {
  9565. BABYLON.Tools.ClearLogCache();
  9566. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9567. }
  9568. this._engine.stopRenderLoop();
  9569. this._currentScene.dispose();
  9570. }
  9571. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9572. that._currentScene = newScene;
  9573. // Wait for textures and shaders to be ready
  9574. that._currentScene.executeWhenReady(function () {
  9575. // Attach camera to canvas inputs
  9576. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9577. that._currentScene.createDefaultCameraOrLight();
  9578. }
  9579. that._currentScene.activeCamera.attachControl(that._canvas);
  9580. if (that._sceneLoadedCallback) {
  9581. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9582. }
  9583. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9584. });
  9585. }, function (progress) {
  9586. if (_this._progressCallback) {
  9587. _this._progressCallback(progress);
  9588. }
  9589. });
  9590. }
  9591. else {
  9592. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9593. }
  9594. };
  9595. return FilesInput;
  9596. }());
  9597. FilesInput.FilesTextures = new Array();
  9598. FilesInput.FilesToLoad = new Array();
  9599. BABYLON.FilesInput = FilesInput;
  9600. })(BABYLON || (BABYLON = {}));
  9601. //# sourceMappingURL=babylon.filesInput.js.map
  9602. var BABYLON;
  9603. (function (BABYLON) {
  9604. var IntersectionInfo = (function () {
  9605. function IntersectionInfo(bu, bv, distance) {
  9606. this.bu = bu;
  9607. this.bv = bv;
  9608. this.distance = distance;
  9609. this.faceId = 0;
  9610. this.subMeshId = 0;
  9611. }
  9612. return IntersectionInfo;
  9613. }());
  9614. BABYLON.IntersectionInfo = IntersectionInfo;
  9615. var PickingInfo = (function () {
  9616. function PickingInfo() {
  9617. this.hit = false;
  9618. this.distance = 0;
  9619. this.pickedPoint = null;
  9620. this.pickedMesh = null;
  9621. this.bu = 0;
  9622. this.bv = 0;
  9623. this.faceId = -1;
  9624. this.subMeshId = 0;
  9625. this.pickedSprite = null;
  9626. }
  9627. // Methods
  9628. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9629. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9630. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9631. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9632. return null;
  9633. }
  9634. var indices = this.pickedMesh.getIndices();
  9635. var result;
  9636. if (useVerticesNormals) {
  9637. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9638. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9639. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9640. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9641. normal0 = normal0.scale(this.bu);
  9642. normal1 = normal1.scale(this.bv);
  9643. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9644. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9645. }
  9646. else {
  9647. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9648. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9649. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9650. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9651. var p1p2 = vertex1.subtract(vertex2);
  9652. var p3p2 = vertex3.subtract(vertex2);
  9653. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9654. }
  9655. if (useWorldCoordinates) {
  9656. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9657. }
  9658. return BABYLON.Vector3.Normalize(result);
  9659. };
  9660. PickingInfo.prototype.getTextureCoordinates = function () {
  9661. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9662. return null;
  9663. }
  9664. var indices = this.pickedMesh.getIndices();
  9665. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9666. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9667. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9668. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9669. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9670. uv1 = uv1.scale(this.bu);
  9671. uv2 = uv2.scale(this.bv);
  9672. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9673. };
  9674. return PickingInfo;
  9675. }());
  9676. BABYLON.PickingInfo = PickingInfo;
  9677. })(BABYLON || (BABYLON = {}));
  9678. //# sourceMappingURL=babylon.pickingInfo.js.map
  9679. var BABYLON;
  9680. (function (BABYLON) {
  9681. var BoundingSphere = (function () {
  9682. function BoundingSphere(minimum, maximum) {
  9683. this.minimum = minimum;
  9684. this.maximum = maximum;
  9685. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9686. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9687. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9688. this.radius = distance * 0.5;
  9689. this.centerWorld = BABYLON.Vector3.Zero();
  9690. this._update(BABYLON.Matrix.Identity());
  9691. }
  9692. // Methods
  9693. BoundingSphere.prototype._update = function (world) {
  9694. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9695. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9696. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9697. };
  9698. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9699. for (var i = 0; i < 6; i++) {
  9700. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9701. return false;
  9702. }
  9703. return true;
  9704. };
  9705. BoundingSphere.prototype.intersectsPoint = function (point) {
  9706. var x = this.centerWorld.x - point.x;
  9707. var y = this.centerWorld.y - point.y;
  9708. var z = this.centerWorld.z - point.z;
  9709. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9710. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9711. return false;
  9712. return true;
  9713. };
  9714. // Statics
  9715. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9716. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9717. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9718. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9719. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9720. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9721. return false;
  9722. return true;
  9723. };
  9724. return BoundingSphere;
  9725. }());
  9726. BABYLON.BoundingSphere = BoundingSphere;
  9727. })(BABYLON || (BABYLON = {}));
  9728. //# sourceMappingURL=babylon.boundingSphere.js.map
  9729. var BABYLON;
  9730. (function (BABYLON) {
  9731. var BoundingBox = (function () {
  9732. function BoundingBox(minimum, maximum) {
  9733. this.minimum = minimum;
  9734. this.maximum = maximum;
  9735. this.vectors = new Array();
  9736. this.vectorsWorld = new Array();
  9737. // Bounding vectors
  9738. this.vectors.push(this.minimum.clone());
  9739. this.vectors.push(this.maximum.clone());
  9740. this.vectors.push(this.minimum.clone());
  9741. this.vectors[2].x = this.maximum.x;
  9742. this.vectors.push(this.minimum.clone());
  9743. this.vectors[3].y = this.maximum.y;
  9744. this.vectors.push(this.minimum.clone());
  9745. this.vectors[4].z = this.maximum.z;
  9746. this.vectors.push(this.maximum.clone());
  9747. this.vectors[5].z = this.minimum.z;
  9748. this.vectors.push(this.maximum.clone());
  9749. this.vectors[6].x = this.minimum.x;
  9750. this.vectors.push(this.maximum.clone());
  9751. this.vectors[7].y = this.minimum.y;
  9752. // OBB
  9753. this.center = this.maximum.add(this.minimum).scale(0.5);
  9754. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9755. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9756. // World
  9757. for (var index = 0; index < this.vectors.length; index++) {
  9758. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9759. }
  9760. this.minimumWorld = BABYLON.Vector3.Zero();
  9761. this.maximumWorld = BABYLON.Vector3.Zero();
  9762. this._update(BABYLON.Matrix.Identity());
  9763. }
  9764. // Methods
  9765. BoundingBox.prototype.getWorldMatrix = function () {
  9766. return this._worldMatrix;
  9767. };
  9768. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9769. this._worldMatrix.copyFrom(matrix);
  9770. return this;
  9771. };
  9772. BoundingBox.prototype._update = function (world) {
  9773. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9774. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9775. for (var index = 0; index < this.vectors.length; index++) {
  9776. var v = this.vectorsWorld[index];
  9777. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9778. if (v.x < this.minimumWorld.x)
  9779. this.minimumWorld.x = v.x;
  9780. if (v.y < this.minimumWorld.y)
  9781. this.minimumWorld.y = v.y;
  9782. if (v.z < this.minimumWorld.z)
  9783. this.minimumWorld.z = v.z;
  9784. if (v.x > this.maximumWorld.x)
  9785. this.maximumWorld.x = v.x;
  9786. if (v.y > this.maximumWorld.y)
  9787. this.maximumWorld.y = v.y;
  9788. if (v.z > this.maximumWorld.z)
  9789. this.maximumWorld.z = v.z;
  9790. }
  9791. // OBB
  9792. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9793. this.center.scaleInPlace(0.5);
  9794. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9795. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9796. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9797. this._worldMatrix = world;
  9798. };
  9799. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9800. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9801. };
  9802. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9803. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9804. };
  9805. BoundingBox.prototype.intersectsPoint = function (point) {
  9806. var delta = -BABYLON.Epsilon;
  9807. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9808. return false;
  9809. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9810. return false;
  9811. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9812. return false;
  9813. return true;
  9814. };
  9815. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9816. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9817. };
  9818. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9819. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9820. return false;
  9821. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9822. return false;
  9823. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9824. return false;
  9825. return true;
  9826. };
  9827. // Statics
  9828. BoundingBox.Intersects = function (box0, box1) {
  9829. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9830. return false;
  9831. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9832. return false;
  9833. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9834. return false;
  9835. return true;
  9836. };
  9837. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9838. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9839. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9840. return (num <= (sphereRadius * sphereRadius));
  9841. };
  9842. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9843. for (var p = 0; p < 6; p++) {
  9844. for (var i = 0; i < 8; i++) {
  9845. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9846. return false;
  9847. }
  9848. }
  9849. }
  9850. return true;
  9851. };
  9852. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9853. for (var p = 0; p < 6; p++) {
  9854. var inCount = 8;
  9855. for (var i = 0; i < 8; i++) {
  9856. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9857. --inCount;
  9858. }
  9859. else {
  9860. break;
  9861. }
  9862. }
  9863. if (inCount === 0)
  9864. return false;
  9865. }
  9866. return true;
  9867. };
  9868. return BoundingBox;
  9869. }());
  9870. BABYLON.BoundingBox = BoundingBox;
  9871. })(BABYLON || (BABYLON = {}));
  9872. //# sourceMappingURL=babylon.boundingBox.js.map
  9873. var BABYLON;
  9874. (function (BABYLON) {
  9875. var computeBoxExtents = function (axis, box) {
  9876. var p = BABYLON.Vector3.Dot(box.center, axis);
  9877. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9878. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9879. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9880. var r = r0 + r1 + r2;
  9881. return {
  9882. min: p - r,
  9883. max: p + r
  9884. };
  9885. };
  9886. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9887. var axisOverlap = function (axis, box0, box1) {
  9888. var result0 = computeBoxExtents(axis, box0);
  9889. var result1 = computeBoxExtents(axis, box1);
  9890. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9891. };
  9892. var BoundingInfo = (function () {
  9893. function BoundingInfo(minimum, maximum) {
  9894. this.minimum = minimum;
  9895. this.maximum = maximum;
  9896. this._isLocked = false;
  9897. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9898. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9899. }
  9900. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9901. get: function () {
  9902. return this._isLocked;
  9903. },
  9904. set: function (value) {
  9905. this._isLocked = value;
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. // Methods
  9911. BoundingInfo.prototype.update = function (world) {
  9912. if (this._isLocked) {
  9913. return;
  9914. }
  9915. this.boundingBox._update(world);
  9916. this.boundingSphere._update(world);
  9917. };
  9918. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9919. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9920. return false;
  9921. return this.boundingBox.isInFrustum(frustumPlanes);
  9922. };
  9923. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9924. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9925. };
  9926. BoundingInfo.prototype._checkCollision = function (collider) {
  9927. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9928. };
  9929. BoundingInfo.prototype.intersectsPoint = function (point) {
  9930. if (!this.boundingSphere.centerWorld) {
  9931. return false;
  9932. }
  9933. if (!this.boundingSphere.intersectsPoint(point)) {
  9934. return false;
  9935. }
  9936. if (!this.boundingBox.intersectsPoint(point)) {
  9937. return false;
  9938. }
  9939. return true;
  9940. };
  9941. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9942. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9943. return false;
  9944. }
  9945. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9946. return false;
  9947. }
  9948. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9949. return false;
  9950. }
  9951. if (!precise) {
  9952. return true;
  9953. }
  9954. var box0 = this.boundingBox;
  9955. var box1 = boundingInfo.boundingBox;
  9956. if (!axisOverlap(box0.directions[0], box0, box1))
  9957. return false;
  9958. if (!axisOverlap(box0.directions[1], box0, box1))
  9959. return false;
  9960. if (!axisOverlap(box0.directions[2], box0, box1))
  9961. return false;
  9962. if (!axisOverlap(box1.directions[0], box0, box1))
  9963. return false;
  9964. if (!axisOverlap(box1.directions[1], box0, box1))
  9965. return false;
  9966. if (!axisOverlap(box1.directions[2], box0, box1))
  9967. return false;
  9968. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9969. return false;
  9970. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9971. return false;
  9972. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9973. return false;
  9974. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9975. return false;
  9976. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9977. return false;
  9978. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9979. return false;
  9980. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9981. return false;
  9982. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9983. return false;
  9984. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9985. return false;
  9986. return true;
  9987. };
  9988. return BoundingInfo;
  9989. }());
  9990. BABYLON.BoundingInfo = BoundingInfo;
  9991. })(BABYLON || (BABYLON = {}));
  9992. //# sourceMappingURL=babylon.boundingInfo.js.map
  9993. var BABYLON;
  9994. (function (BABYLON) {
  9995. var Ray = (function () {
  9996. function Ray(origin, direction, length) {
  9997. if (length === void 0) { length = Number.MAX_VALUE; }
  9998. this.origin = origin;
  9999. this.direction = direction;
  10000. this.length = length;
  10001. this._show = false;
  10002. }
  10003. // Methods
  10004. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10005. var d = 0.0;
  10006. var maxValue = Number.MAX_VALUE;
  10007. var inv;
  10008. var min;
  10009. var max;
  10010. var temp;
  10011. if (Math.abs(this.direction.x) < 0.0000001) {
  10012. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10013. return false;
  10014. }
  10015. }
  10016. else {
  10017. inv = 1.0 / this.direction.x;
  10018. min = (minimum.x - this.origin.x) * inv;
  10019. max = (maximum.x - this.origin.x) * inv;
  10020. if (max === -Infinity) {
  10021. max = Infinity;
  10022. }
  10023. if (min > max) {
  10024. temp = min;
  10025. min = max;
  10026. max = temp;
  10027. }
  10028. d = Math.max(min, d);
  10029. maxValue = Math.min(max, maxValue);
  10030. if (d > maxValue) {
  10031. return false;
  10032. }
  10033. }
  10034. if (Math.abs(this.direction.y) < 0.0000001) {
  10035. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10036. return false;
  10037. }
  10038. }
  10039. else {
  10040. inv = 1.0 / this.direction.y;
  10041. min = (minimum.y - this.origin.y) * inv;
  10042. max = (maximum.y - this.origin.y) * inv;
  10043. if (max === -Infinity) {
  10044. max = Infinity;
  10045. }
  10046. if (min > max) {
  10047. temp = min;
  10048. min = max;
  10049. max = temp;
  10050. }
  10051. d = Math.max(min, d);
  10052. maxValue = Math.min(max, maxValue);
  10053. if (d > maxValue) {
  10054. return false;
  10055. }
  10056. }
  10057. if (Math.abs(this.direction.z) < 0.0000001) {
  10058. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10059. return false;
  10060. }
  10061. }
  10062. else {
  10063. inv = 1.0 / this.direction.z;
  10064. min = (minimum.z - this.origin.z) * inv;
  10065. max = (maximum.z - this.origin.z) * inv;
  10066. if (max === -Infinity) {
  10067. max = Infinity;
  10068. }
  10069. if (min > max) {
  10070. temp = min;
  10071. min = max;
  10072. max = temp;
  10073. }
  10074. d = Math.max(min, d);
  10075. maxValue = Math.min(max, maxValue);
  10076. if (d > maxValue) {
  10077. return false;
  10078. }
  10079. }
  10080. return true;
  10081. };
  10082. Ray.prototype.intersectsBox = function (box) {
  10083. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10084. };
  10085. Ray.prototype.intersectsSphere = function (sphere) {
  10086. var x = sphere.center.x - this.origin.x;
  10087. var y = sphere.center.y - this.origin.y;
  10088. var z = sphere.center.z - this.origin.z;
  10089. var pyth = (x * x) + (y * y) + (z * z);
  10090. var rr = sphere.radius * sphere.radius;
  10091. if (pyth <= rr) {
  10092. return true;
  10093. }
  10094. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10095. if (dot < 0.0) {
  10096. return false;
  10097. }
  10098. var temp = pyth - (dot * dot);
  10099. return temp <= rr;
  10100. };
  10101. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10102. if (!this._edge1) {
  10103. this._edge1 = BABYLON.Vector3.Zero();
  10104. this._edge2 = BABYLON.Vector3.Zero();
  10105. this._pvec = BABYLON.Vector3.Zero();
  10106. this._tvec = BABYLON.Vector3.Zero();
  10107. this._qvec = BABYLON.Vector3.Zero();
  10108. }
  10109. vertex1.subtractToRef(vertex0, this._edge1);
  10110. vertex2.subtractToRef(vertex0, this._edge2);
  10111. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10112. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10113. if (det === 0) {
  10114. return null;
  10115. }
  10116. var invdet = 1 / det;
  10117. this.origin.subtractToRef(vertex0, this._tvec);
  10118. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10119. if (bu < 0 || bu > 1.0) {
  10120. return null;
  10121. }
  10122. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10123. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10124. if (bv < 0 || bu + bv > 1.0) {
  10125. return null;
  10126. }
  10127. //check if the distance is longer than the predefined length.
  10128. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10129. if (distance > this.length) {
  10130. return null;
  10131. }
  10132. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10133. };
  10134. Ray.prototype.intersectsPlane = function (plane) {
  10135. var distance;
  10136. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10137. if (Math.abs(result1) < 9.99999997475243E-07) {
  10138. return null;
  10139. }
  10140. else {
  10141. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10142. distance = (-plane.d - result2) / result1;
  10143. if (distance < 0.0) {
  10144. if (distance < -9.99999997475243E-07) {
  10145. return null;
  10146. }
  10147. else {
  10148. return 0;
  10149. }
  10150. }
  10151. return distance;
  10152. }
  10153. };
  10154. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10155. var tm = BABYLON.Tmp.Matrix[0];
  10156. mesh.getWorldMatrix().invertToRef(tm);
  10157. if (this._tmpRay) {
  10158. Ray.TransformToRef(this, tm, this._tmpRay);
  10159. }
  10160. else {
  10161. this._tmpRay = Ray.Transform(this, tm);
  10162. }
  10163. return mesh.intersects(this._tmpRay, fastCheck);
  10164. };
  10165. Ray.prototype.show = function (scene, color) {
  10166. if (!this._show) {
  10167. this._renderFunction = this._render.bind(this);
  10168. this._show = true;
  10169. this._scene = scene;
  10170. this._renderPoints = [this.origin, this.origin.add(this.direction.scale(this.length))];
  10171. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10172. this._scene.registerBeforeRender(this._renderFunction);
  10173. }
  10174. if (color) {
  10175. this._renderLine.color.copyFrom(color);
  10176. }
  10177. };
  10178. Ray.prototype.hide = function () {
  10179. if (this._show) {
  10180. this._show = false;
  10181. this._scene.unregisterBeforeRender(this._renderFunction);
  10182. }
  10183. if (this._renderLine) {
  10184. this._renderLine.dispose();
  10185. this._renderLine = null;
  10186. this._renderPoints = null;
  10187. }
  10188. };
  10189. Ray.prototype._render = function () {
  10190. var point = this._renderPoints[1];
  10191. point.copyFrom(this.direction);
  10192. point.scaleInPlace(this.length);
  10193. point.addInPlace(this.origin);
  10194. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10195. };
  10196. /**
  10197. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10198. * @param sega the first point of the segment to test the intersection against
  10199. * @param segb the second point of the segment to test the intersection against
  10200. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10201. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10202. */
  10203. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10204. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10205. var u = segb.subtract(sega);
  10206. var v = rsegb.subtract(this.origin);
  10207. var w = sega.subtract(this.origin);
  10208. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10209. var b = BABYLON.Vector3.Dot(u, v);
  10210. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10211. var d = BABYLON.Vector3.Dot(u, w);
  10212. var e = BABYLON.Vector3.Dot(v, w);
  10213. var D = a * c - b * b; // always >= 0
  10214. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10215. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10216. // compute the line parameters of the two closest points
  10217. if (D < Ray.smallnum) {
  10218. sN = 0.0; // force using point P0 on segment S1
  10219. sD = 1.0; // to prevent possible division by 0.0 later
  10220. tN = e;
  10221. tD = c;
  10222. }
  10223. else {
  10224. sN = (b * e - c * d);
  10225. tN = (a * e - b * d);
  10226. if (sN < 0.0) {
  10227. sN = 0.0;
  10228. tN = e;
  10229. tD = c;
  10230. }
  10231. else if (sN > sD) {
  10232. sN = sD;
  10233. tN = e + b;
  10234. tD = c;
  10235. }
  10236. }
  10237. if (tN < 0.0) {
  10238. tN = 0.0;
  10239. // recompute sc for this edge
  10240. if (-d < 0.0) {
  10241. sN = 0.0;
  10242. }
  10243. else if (-d > a)
  10244. sN = sD;
  10245. else {
  10246. sN = -d;
  10247. sD = a;
  10248. }
  10249. }
  10250. else if (tN > tD) {
  10251. tN = tD;
  10252. // recompute sc for this edge
  10253. if ((-d + b) < 0.0) {
  10254. sN = 0;
  10255. }
  10256. else if ((-d + b) > a) {
  10257. sN = sD;
  10258. }
  10259. else {
  10260. sN = (-d + b);
  10261. sD = a;
  10262. }
  10263. }
  10264. // finally do the division to get sc and tc
  10265. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10266. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10267. // get the difference of the two closest points
  10268. var qtc = v.multiplyByFloats(tc, tc, tc);
  10269. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10270. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10271. if (isIntersected) {
  10272. return qtc.length();
  10273. }
  10274. return -1;
  10275. };
  10276. // Statics
  10277. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10278. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10279. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10280. var direction = end.subtract(start);
  10281. direction.normalize();
  10282. return new Ray(start, direction);
  10283. };
  10284. /**
  10285. * 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
  10286. * transformed to the given world matrix.
  10287. * @param origin The origin point
  10288. * @param end The end point
  10289. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10290. */
  10291. Ray.CreateNewFromTo = function (origin, end, world) {
  10292. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10293. var direction = end.subtract(origin);
  10294. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10295. direction.normalize();
  10296. return Ray.Transform(new Ray(origin, direction, length), world);
  10297. };
  10298. Ray.Transform = function (ray, matrix) {
  10299. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10300. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10301. newDirection.normalize();
  10302. return new Ray(newOrigin, newDirection, ray.length);
  10303. };
  10304. Ray.TransformToRef = function (ray, matrix, result) {
  10305. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10306. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10307. ray.direction.normalize();
  10308. };
  10309. return Ray;
  10310. }());
  10311. Ray.smallnum = 0.00000001;
  10312. Ray.rayl = 10e8;
  10313. BABYLON.Ray = Ray;
  10314. })(BABYLON || (BABYLON = {}));
  10315. //# sourceMappingURL=babylon.ray.js.map
  10316. var BABYLON;
  10317. (function (BABYLON) {
  10318. var AbstractMesh = (function (_super) {
  10319. __extends(AbstractMesh, _super);
  10320. // Constructor
  10321. function AbstractMesh(name, scene) {
  10322. var _this = _super.call(this, name, scene) || this;
  10323. // Events
  10324. /**
  10325. * An event triggered when this mesh collides with another one
  10326. * @type {BABYLON.Observable}
  10327. */
  10328. _this.onCollideObservable = new BABYLON.Observable();
  10329. /**
  10330. * An event triggered when the collision's position changes
  10331. * @type {BABYLON.Observable}
  10332. */
  10333. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10334. /**
  10335. * An event triggered after the world matrix is updated
  10336. * @type {BABYLON.Observable}
  10337. */
  10338. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10339. // Properties
  10340. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10341. _this.position = new BABYLON.Vector3(0, 0, 0);
  10342. _this._rotation = new BABYLON.Vector3(0, 0, 0);
  10343. _this._scaling = new BABYLON.Vector3(1, 1, 1);
  10344. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10345. _this.visibility = 1.0;
  10346. _this.alphaIndex = Number.MAX_VALUE;
  10347. _this.infiniteDistance = false;
  10348. _this.isVisible = true;
  10349. _this.isPickable = true;
  10350. _this.showBoundingBox = false;
  10351. _this.showSubMeshesBoundingBox = false;
  10352. _this.isBlocker = false;
  10353. _this.renderingGroupId = 0;
  10354. _this.receiveShadows = false;
  10355. _this.renderOutline = false;
  10356. _this.outlineColor = BABYLON.Color3.Red();
  10357. _this.outlineWidth = 0.02;
  10358. _this.renderOverlay = false;
  10359. _this.overlayColor = BABYLON.Color3.Red();
  10360. _this.overlayAlpha = 0.5;
  10361. _this.hasVertexAlpha = false;
  10362. _this.useVertexColors = true;
  10363. _this.applyFog = true;
  10364. _this.computeBonesUsingShaders = true;
  10365. _this.scalingDeterminant = 1;
  10366. _this.numBoneInfluencers = 4;
  10367. _this.useOctreeForRenderingSelection = true;
  10368. _this.useOctreeForPicking = true;
  10369. _this.useOctreeForCollisions = true;
  10370. _this.layerMask = 0x0FFFFFFF;
  10371. _this.alwaysSelectAsActiveMesh = false;
  10372. // Collisions
  10373. _this._checkCollisions = false;
  10374. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10375. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10376. _this._collider = new BABYLON.Collider();
  10377. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10378. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10379. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10380. // Edges
  10381. _this.edgesWidth = 1;
  10382. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10383. // Cache
  10384. _this._localWorld = BABYLON.Matrix.Zero();
  10385. _this._worldMatrix = BABYLON.Matrix.Zero();
  10386. _this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10387. _this._absolutePosition = BABYLON.Vector3.Zero();
  10388. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10389. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10390. _this._isDirty = false;
  10391. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10392. _this._isDisposed = false;
  10393. _this._renderId = 0;
  10394. _this._intersectionsInProgress = new Array();
  10395. _this._isWorldMatrixFrozen = false;
  10396. _this._unIndexed = false;
  10397. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10398. if (collidedMesh === void 0) { collidedMesh = null; }
  10399. //TODO move this to the collision coordinator!
  10400. if (_this.getScene().workerCollisions)
  10401. newPosition.multiplyInPlace(_this._collider.radius);
  10402. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10403. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10404. _this.position.addInPlace(_this._diffPositionForCollisions);
  10405. }
  10406. if (collidedMesh) {
  10407. _this.onCollideObservable.notifyObservers(collidedMesh);
  10408. }
  10409. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10410. };
  10411. scene.addMesh(_this);
  10412. return _this;
  10413. }
  10414. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10415. get: function () {
  10416. return AbstractMesh._BILLBOARDMODE_NONE;
  10417. },
  10418. enumerable: true,
  10419. configurable: true
  10420. });
  10421. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10422. get: function () {
  10423. return AbstractMesh._BILLBOARDMODE_X;
  10424. },
  10425. enumerable: true,
  10426. configurable: true
  10427. });
  10428. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10429. get: function () {
  10430. return AbstractMesh._BILLBOARDMODE_Y;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10436. get: function () {
  10437. return AbstractMesh._BILLBOARDMODE_Z;
  10438. },
  10439. enumerable: true,
  10440. configurable: true
  10441. });
  10442. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10443. get: function () {
  10444. return AbstractMesh._BILLBOARDMODE_ALL;
  10445. },
  10446. enumerable: true,
  10447. configurable: true
  10448. });
  10449. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10450. set: function (callback) {
  10451. if (this._onCollideObserver) {
  10452. this.onCollideObservable.remove(this._onCollideObserver);
  10453. }
  10454. this._onCollideObserver = this.onCollideObservable.add(callback);
  10455. },
  10456. enumerable: true,
  10457. configurable: true
  10458. });
  10459. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10460. set: function (callback) {
  10461. if (this._onCollisionPositionChangeObserver) {
  10462. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10463. }
  10464. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10465. },
  10466. enumerable: true,
  10467. configurable: true
  10468. });
  10469. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10470. get: function () {
  10471. return this._skeleton;
  10472. },
  10473. set: function (value) {
  10474. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10475. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10476. }
  10477. if (value && value.needInitialSkinMatrix) {
  10478. value._registerMeshWithPoseMatrix(this);
  10479. }
  10480. this._skeleton = value;
  10481. if (!this._skeleton) {
  10482. this._bonesTransformMatrices = null;
  10483. }
  10484. },
  10485. enumerable: true,
  10486. configurable: true
  10487. });
  10488. AbstractMesh.prototype.getClassName = function () {
  10489. return "AbstractMesh";
  10490. };
  10491. /**
  10492. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10493. */
  10494. AbstractMesh.prototype.toString = function (fullDetails) {
  10495. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10496. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10497. if (this._skeleton) {
  10498. ret += ", skeleton: " + this._skeleton.name;
  10499. }
  10500. if (fullDetails) {
  10501. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10502. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10503. }
  10504. return ret;
  10505. };
  10506. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10507. /**
  10508. * Getting the rotation object.
  10509. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10510. */
  10511. get: function () {
  10512. return this._rotation;
  10513. },
  10514. set: function (newRotation) {
  10515. this._rotation = newRotation;
  10516. },
  10517. enumerable: true,
  10518. configurable: true
  10519. });
  10520. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10521. get: function () {
  10522. return this._scaling;
  10523. },
  10524. set: function (newScaling) {
  10525. this._scaling = newScaling;
  10526. if (this.physicsImpostor) {
  10527. this.physicsImpostor.forceUpdate();
  10528. }
  10529. },
  10530. enumerable: true,
  10531. configurable: true
  10532. });
  10533. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10534. get: function () {
  10535. return this._rotationQuaternion;
  10536. },
  10537. set: function (quaternion) {
  10538. this._rotationQuaternion = quaternion;
  10539. //reset the rotation vector.
  10540. if (quaternion && this.rotation.length()) {
  10541. this.rotation.copyFromFloats(0, 0, 0);
  10542. }
  10543. },
  10544. enumerable: true,
  10545. configurable: true
  10546. });
  10547. // Methods
  10548. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10549. this._poseMatrix.copyFrom(matrix);
  10550. };
  10551. AbstractMesh.prototype.getPoseMatrix = function () {
  10552. return this._poseMatrix;
  10553. };
  10554. AbstractMesh.prototype.disableEdgesRendering = function () {
  10555. if (this._edgesRenderer !== undefined) {
  10556. this._edgesRenderer.dispose();
  10557. this._edgesRenderer = undefined;
  10558. }
  10559. };
  10560. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10561. if (epsilon === void 0) { epsilon = 0.95; }
  10562. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10563. this.disableEdgesRendering();
  10564. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10565. };
  10566. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10567. get: function () {
  10568. return false;
  10569. },
  10570. enumerable: true,
  10571. configurable: true
  10572. });
  10573. AbstractMesh.prototype.getLOD = function (camera) {
  10574. return this;
  10575. };
  10576. AbstractMesh.prototype.getTotalVertices = function () {
  10577. return 0;
  10578. };
  10579. AbstractMesh.prototype.getIndices = function () {
  10580. return null;
  10581. };
  10582. AbstractMesh.prototype.getVerticesData = function (kind) {
  10583. return null;
  10584. };
  10585. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10586. return false;
  10587. };
  10588. AbstractMesh.prototype.getBoundingInfo = function () {
  10589. if (this._masterMesh) {
  10590. return this._masterMesh.getBoundingInfo();
  10591. }
  10592. if (!this._boundingInfo) {
  10593. this._updateBoundingInfo();
  10594. }
  10595. return this._boundingInfo;
  10596. };
  10597. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10598. this._boundingInfo = boundingInfo;
  10599. };
  10600. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10601. get: function () {
  10602. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10603. },
  10604. enumerable: true,
  10605. configurable: true
  10606. });
  10607. AbstractMesh.prototype._preActivate = function () {
  10608. };
  10609. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10610. };
  10611. AbstractMesh.prototype._activate = function (renderId) {
  10612. this._renderId = renderId;
  10613. };
  10614. AbstractMesh.prototype.getWorldMatrix = function () {
  10615. if (this._masterMesh) {
  10616. return this._masterMesh.getWorldMatrix();
  10617. }
  10618. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10619. this.computeWorldMatrix();
  10620. }
  10621. return this._worldMatrix;
  10622. };
  10623. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10624. get: function () {
  10625. return this._worldMatrix;
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10631. get: function () {
  10632. return this._absolutePosition;
  10633. },
  10634. enumerable: true,
  10635. configurable: true
  10636. });
  10637. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10638. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10639. this.computeWorldMatrix(true);
  10640. this._isWorldMatrixFrozen = true;
  10641. };
  10642. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10643. this._isWorldMatrixFrozen = false;
  10644. this.computeWorldMatrix(true);
  10645. };
  10646. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10647. get: function () {
  10648. return this._isWorldMatrixFrozen;
  10649. },
  10650. enumerable: true,
  10651. configurable: true
  10652. });
  10653. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10654. axis.normalize();
  10655. if (!this.rotationQuaternion) {
  10656. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10657. this.rotation = BABYLON.Vector3.Zero();
  10658. }
  10659. var rotationQuaternion;
  10660. if (!space || space === BABYLON.Space.LOCAL) {
  10661. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10662. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10663. }
  10664. else {
  10665. if (this.parent) {
  10666. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10667. invertParentWorldMatrix.invert();
  10668. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10669. }
  10670. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10671. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10672. }
  10673. };
  10674. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10675. var displacementVector = axis.scale(distance);
  10676. if (!space || space === BABYLON.Space.LOCAL) {
  10677. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10678. this.setPositionWithLocalVector(tempV3);
  10679. }
  10680. else {
  10681. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10682. }
  10683. };
  10684. AbstractMesh.prototype.getAbsolutePosition = function () {
  10685. this.computeWorldMatrix();
  10686. return this._absolutePosition;
  10687. };
  10688. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10689. if (!absolutePosition) {
  10690. return;
  10691. }
  10692. var absolutePositionX;
  10693. var absolutePositionY;
  10694. var absolutePositionZ;
  10695. if (absolutePosition.x === undefined) {
  10696. if (arguments.length < 3) {
  10697. return;
  10698. }
  10699. absolutePositionX = arguments[0];
  10700. absolutePositionY = arguments[1];
  10701. absolutePositionZ = arguments[2];
  10702. }
  10703. else {
  10704. absolutePositionX = absolutePosition.x;
  10705. absolutePositionY = absolutePosition.y;
  10706. absolutePositionZ = absolutePosition.z;
  10707. }
  10708. if (this.parent) {
  10709. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10710. invertParentWorldMatrix.invert();
  10711. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10712. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10713. }
  10714. else {
  10715. this.position.x = absolutePositionX;
  10716. this.position.y = absolutePositionY;
  10717. this.position.z = absolutePositionZ;
  10718. }
  10719. };
  10720. // ================================== Point of View Movement =================================
  10721. /**
  10722. * Perform relative position change from the point of view of behind the front of the mesh.
  10723. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10724. * Supports definition of mesh facing forward or backward.
  10725. * @param {number} amountRight
  10726. * @param {number} amountUp
  10727. * @param {number} amountForward
  10728. */
  10729. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10730. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10731. };
  10732. /**
  10733. * Calculate 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.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10741. var rotMatrix = new BABYLON.Matrix();
  10742. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10743. rotQuaternion.toRotationMatrix(rotMatrix);
  10744. var translationDelta = BABYLON.Vector3.Zero();
  10745. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10746. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10747. return translationDelta;
  10748. };
  10749. // ================================== Point of View Rotation =================================
  10750. /**
  10751. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10752. * Supports definition of mesh facing forward or backward.
  10753. * @param {number} flipBack
  10754. * @param {number} twirlClockwise
  10755. * @param {number} tiltRight
  10756. */
  10757. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10758. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10759. };
  10760. /**
  10761. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10762. * Supports definition of mesh facing forward or backward.
  10763. * @param {number} flipBack
  10764. * @param {number} twirlClockwise
  10765. * @param {number} tiltRight
  10766. */
  10767. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10768. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10769. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10770. };
  10771. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10772. this._pivotMatrix = matrix;
  10773. this._cache.pivotMatrixUpdated = true;
  10774. };
  10775. AbstractMesh.prototype.getPivotMatrix = function () {
  10776. return this._pivotMatrix;
  10777. };
  10778. AbstractMesh.prototype._isSynchronized = function () {
  10779. if (this._isDirty) {
  10780. return false;
  10781. }
  10782. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10783. return false;
  10784. if (this._cache.pivotMatrixUpdated) {
  10785. return false;
  10786. }
  10787. if (this.infiniteDistance) {
  10788. return false;
  10789. }
  10790. if (!this._cache.position.equals(this.position))
  10791. return false;
  10792. if (this.rotationQuaternion) {
  10793. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10794. return false;
  10795. }
  10796. if (!this._cache.rotation.equals(this.rotation))
  10797. return false;
  10798. if (!this._cache.scaling.equals(this.scaling))
  10799. return false;
  10800. return true;
  10801. };
  10802. AbstractMesh.prototype._initCache = function () {
  10803. _super.prototype._initCache.call(this);
  10804. this._cache.localMatrixUpdated = false;
  10805. this._cache.position = BABYLON.Vector3.Zero();
  10806. this._cache.scaling = BABYLON.Vector3.Zero();
  10807. this._cache.rotation = BABYLON.Vector3.Zero();
  10808. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10809. this._cache.billboardMode = -1;
  10810. };
  10811. AbstractMesh.prototype.markAsDirty = function (property) {
  10812. if (property === "rotation") {
  10813. this.rotationQuaternion = null;
  10814. }
  10815. this._currentRenderId = Number.MAX_VALUE;
  10816. this._isDirty = true;
  10817. };
  10818. AbstractMesh.prototype._updateBoundingInfo = function () {
  10819. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10820. this._boundingInfo.update(this.worldMatrixFromCache);
  10821. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10822. };
  10823. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10824. if (!this.subMeshes) {
  10825. return;
  10826. }
  10827. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10828. var subMesh = this.subMeshes[subIndex];
  10829. if (!subMesh.IsGlobal) {
  10830. subMesh.updateBoundingInfo(matrix);
  10831. }
  10832. }
  10833. };
  10834. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10835. if (this._isWorldMatrixFrozen) {
  10836. return this._worldMatrix;
  10837. }
  10838. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10839. this._currentRenderId = this.getScene().getRenderId();
  10840. return this._worldMatrix;
  10841. }
  10842. this._cache.position.copyFrom(this.position);
  10843. this._cache.scaling.copyFrom(this.scaling);
  10844. this._cache.pivotMatrixUpdated = false;
  10845. this._cache.billboardMode = this.billboardMode;
  10846. this._currentRenderId = this.getScene().getRenderId();
  10847. this._isDirty = false;
  10848. // Scaling
  10849. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10850. // Rotation
  10851. //rotate, if quaternion is set and rotation was used
  10852. if (this.rotationQuaternion) {
  10853. var len = this.rotation.length();
  10854. if (len) {
  10855. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10856. this.rotation.copyFromFloats(0, 0, 0);
  10857. }
  10858. }
  10859. if (this.rotationQuaternion) {
  10860. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10861. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10862. }
  10863. else {
  10864. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10865. this._cache.rotation.copyFrom(this.rotation);
  10866. }
  10867. // Translation
  10868. if (this.infiniteDistance && !this.parent) {
  10869. var camera = this.getScene().activeCamera;
  10870. if (camera) {
  10871. var cameraWorldMatrix = camera.getWorldMatrix();
  10872. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10873. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10874. }
  10875. }
  10876. else {
  10877. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10878. }
  10879. // Composing transformations
  10880. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10881. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10882. // Billboarding
  10883. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10884. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10885. var localPosition = BABYLON.Tmp.Vector3[0];
  10886. if (this.parent && this.parent.getWorldMatrix) {
  10887. this._markSyncedWithParent();
  10888. var parentMatrix;
  10889. if (this._meshToBoneReferal) {
  10890. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10891. parentMatrix = BABYLON.Tmp.Matrix[6];
  10892. }
  10893. else {
  10894. parentMatrix = this.parent.getWorldMatrix();
  10895. }
  10896. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10897. localPosition = BABYLON.Tmp.Vector3[1];
  10898. }
  10899. var zero = this.getScene().activeCamera.globalPosition.clone();
  10900. if (this.parent && this.parent.position) {
  10901. localPosition.addInPlace(this.parent.position);
  10902. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10903. }
  10904. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10905. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10906. zero.x = localPosition.x + BABYLON.Epsilon;
  10907. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10908. zero.y = localPosition.y + BABYLON.Epsilon;
  10909. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10910. zero.z = localPosition.z + BABYLON.Epsilon;
  10911. }
  10912. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10913. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10914. BABYLON.Tmp.Matrix[3].invert();
  10915. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10916. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10917. }
  10918. // Local world
  10919. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10920. // Parent
  10921. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10922. this._markSyncedWithParent();
  10923. if (this._meshToBoneReferal) {
  10924. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10925. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10926. }
  10927. else {
  10928. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10929. }
  10930. }
  10931. else {
  10932. this._worldMatrix.copyFrom(this._localWorld);
  10933. }
  10934. // Bounding info
  10935. this._updateBoundingInfo();
  10936. // Absolute position
  10937. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10938. // Callbacks
  10939. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10940. if (!this._poseMatrix) {
  10941. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10942. }
  10943. return this._worldMatrix;
  10944. };
  10945. /**
  10946. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10947. * @param func: callback function to add
  10948. */
  10949. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10950. this.onAfterWorldMatrixUpdateObservable.add(func);
  10951. };
  10952. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10953. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10954. };
  10955. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10956. this.computeWorldMatrix();
  10957. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10958. };
  10959. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10960. this.computeWorldMatrix();
  10961. var invLocalWorldMatrix = this._localWorld.clone();
  10962. invLocalWorldMatrix.invert();
  10963. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10964. };
  10965. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10966. this.computeWorldMatrix(true);
  10967. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10968. };
  10969. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10970. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10971. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10972. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10973. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10974. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10975. /// <returns>Mesh oriented towards targetMesh</returns>
  10976. if (yawCor === void 0) { yawCor = 0; }
  10977. if (pitchCor === void 0) { pitchCor = 0; }
  10978. if (rollCor === void 0) { rollCor = 0; }
  10979. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10980. var dv = AbstractMesh._lookAtVectorCache;
  10981. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10982. targetPoint.subtractToRef(pos, dv);
  10983. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10984. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10985. var pitch = Math.atan2(dv.y, len);
  10986. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10987. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10988. };
  10989. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10990. this._meshToBoneReferal = affectedMesh;
  10991. this.parent = bone;
  10992. if (bone.getWorldMatrix().determinant() < 0) {
  10993. this.scalingDeterminant *= -1;
  10994. }
  10995. };
  10996. AbstractMesh.prototype.detachFromBone = function () {
  10997. if (this.parent.getWorldMatrix().determinant() < 0) {
  10998. this.scalingDeterminant *= -1;
  10999. }
  11000. this._meshToBoneReferal = null;
  11001. this.parent = null;
  11002. };
  11003. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11004. return this._boundingInfo.isInFrustum(frustumPlanes);
  11005. };
  11006. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11007. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11008. ;
  11009. };
  11010. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11011. if (!this._boundingInfo || !mesh._boundingInfo) {
  11012. return false;
  11013. }
  11014. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11015. };
  11016. AbstractMesh.prototype.intersectsPoint = function (point) {
  11017. if (!this._boundingInfo) {
  11018. return false;
  11019. }
  11020. return this._boundingInfo.intersectsPoint(point);
  11021. };
  11022. // Physics
  11023. /**
  11024. * @Deprecated. Use new PhysicsImpostor instead.
  11025. * */
  11026. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11027. //legacy support
  11028. if (impostor.impostor) {
  11029. options = impostor;
  11030. impostor = impostor.impostor;
  11031. }
  11032. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11033. return this.physicsImpostor.physicsBody;
  11034. };
  11035. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11036. return this.physicsImpostor;
  11037. };
  11038. /**
  11039. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11040. */
  11041. AbstractMesh.prototype.getPhysicsMass = function () {
  11042. return this.physicsImpostor.getParam("mass");
  11043. };
  11044. /**
  11045. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11046. */
  11047. AbstractMesh.prototype.getPhysicsFriction = function () {
  11048. return this.physicsImpostor.getParam("friction");
  11049. };
  11050. /**
  11051. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11052. */
  11053. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11054. return this.physicsImpostor.getParam("restitution");
  11055. };
  11056. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11057. if (!camera) {
  11058. camera = this.getScene().activeCamera;
  11059. }
  11060. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11061. };
  11062. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11063. if (!camera) {
  11064. camera = this.getScene().activeCamera;
  11065. }
  11066. return this.absolutePosition.subtract(camera.position).length();
  11067. };
  11068. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11069. if (!this.physicsImpostor) {
  11070. return;
  11071. }
  11072. this.physicsImpostor.applyImpulse(force, contactPoint);
  11073. };
  11074. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11075. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11076. return;
  11077. }
  11078. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11079. mainPivot: pivot1,
  11080. connectedPivot: pivot2,
  11081. nativeParams: options
  11082. });
  11083. };
  11084. /**
  11085. * @Deprecated
  11086. */
  11087. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11088. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11089. this.updatePhysicsBody();
  11090. };
  11091. /**
  11092. * @Deprecated
  11093. * Calling this function is not needed anymore.
  11094. * The physics engine takes care of transofmration automatically.
  11095. */
  11096. AbstractMesh.prototype.updatePhysicsBody = function () {
  11097. //Unneeded
  11098. };
  11099. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11100. // Collisions
  11101. get: function () {
  11102. return this._checkCollisions;
  11103. },
  11104. set: function (collisionEnabled) {
  11105. this._checkCollisions = collisionEnabled;
  11106. if (this.getScene().workerCollisions) {
  11107. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11108. }
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11114. var globalPosition = this.getAbsolutePosition();
  11115. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11116. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11117. this._collider.radius = this.ellipsoid;
  11118. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11119. };
  11120. // Submeshes octree
  11121. /**
  11122. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11123. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11124. */
  11125. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11126. if (maxCapacity === void 0) { maxCapacity = 64; }
  11127. if (maxDepth === void 0) { maxDepth = 2; }
  11128. if (!this._submeshesOctree) {
  11129. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11130. }
  11131. this.computeWorldMatrix(true);
  11132. // Update octree
  11133. var bbox = this.getBoundingInfo().boundingBox;
  11134. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11135. return this._submeshesOctree;
  11136. };
  11137. // Collisions
  11138. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11139. this._generatePointsArray();
  11140. // Transformation
  11141. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11142. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11143. subMesh._lastColliderWorldVertices = [];
  11144. subMesh._trianglePlanes = [];
  11145. var start = subMesh.verticesStart;
  11146. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11147. for (var i = start; i < end; i++) {
  11148. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11149. }
  11150. }
  11151. // Collide
  11152. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11153. if (collider.collisionFound) {
  11154. collider.collidedMesh = this;
  11155. }
  11156. };
  11157. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11158. var subMeshes;
  11159. var len;
  11160. // Octrees
  11161. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11162. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11163. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11164. len = intersections.length;
  11165. subMeshes = intersections.data;
  11166. }
  11167. else {
  11168. subMeshes = this.subMeshes;
  11169. len = subMeshes.length;
  11170. }
  11171. for (var index = 0; index < len; index++) {
  11172. var subMesh = subMeshes[index];
  11173. // Bounding test
  11174. if (len > 1 && !subMesh._checkCollision(collider))
  11175. continue;
  11176. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11177. }
  11178. };
  11179. AbstractMesh.prototype._checkCollision = function (collider) {
  11180. // Bounding box test
  11181. if (!this._boundingInfo._checkCollision(collider))
  11182. return;
  11183. // Transformation matrix
  11184. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11185. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11186. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11187. };
  11188. // Picking
  11189. AbstractMesh.prototype._generatePointsArray = function () {
  11190. return false;
  11191. };
  11192. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11193. var pickingInfo = new BABYLON.PickingInfo();
  11194. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11195. return pickingInfo;
  11196. }
  11197. if (!this._generatePointsArray()) {
  11198. return pickingInfo;
  11199. }
  11200. var intersectInfo = null;
  11201. // Octrees
  11202. var subMeshes;
  11203. var len;
  11204. if (this._submeshesOctree && this.useOctreeForPicking) {
  11205. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11206. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11207. len = intersections.length;
  11208. subMeshes = intersections.data;
  11209. }
  11210. else {
  11211. subMeshes = this.subMeshes;
  11212. len = subMeshes.length;
  11213. }
  11214. for (var index = 0; index < len; index++) {
  11215. var subMesh = subMeshes[index];
  11216. // Bounding test
  11217. if (len > 1 && !subMesh.canIntersects(ray))
  11218. continue;
  11219. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11220. if (currentIntersectInfo) {
  11221. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11222. intersectInfo = currentIntersectInfo;
  11223. intersectInfo.subMeshId = index;
  11224. if (fastCheck) {
  11225. break;
  11226. }
  11227. }
  11228. }
  11229. }
  11230. if (intersectInfo) {
  11231. // Get picked point
  11232. var world = this.getWorldMatrix();
  11233. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11234. var direction = ray.direction.clone();
  11235. direction = direction.scale(intersectInfo.distance);
  11236. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11237. var pickedPoint = worldOrigin.add(worldDirection);
  11238. // Return result
  11239. pickingInfo.hit = true;
  11240. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11241. pickingInfo.pickedPoint = pickedPoint;
  11242. pickingInfo.pickedMesh = this;
  11243. pickingInfo.bu = intersectInfo.bu;
  11244. pickingInfo.bv = intersectInfo.bv;
  11245. pickingInfo.faceId = intersectInfo.faceId;
  11246. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11247. return pickingInfo;
  11248. }
  11249. return pickingInfo;
  11250. };
  11251. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11252. return null;
  11253. };
  11254. AbstractMesh.prototype.releaseSubMeshes = function () {
  11255. if (this.subMeshes) {
  11256. while (this.subMeshes.length) {
  11257. this.subMeshes[0].dispose();
  11258. }
  11259. }
  11260. else {
  11261. this.subMeshes = new Array();
  11262. }
  11263. };
  11264. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11265. var _this = this;
  11266. var index;
  11267. // Action manager
  11268. if (this.actionManager) {
  11269. this.actionManager.dispose();
  11270. this.actionManager = null;
  11271. }
  11272. // Skeleton
  11273. this.skeleton = null;
  11274. // Animations
  11275. this.getScene().stopAnimation(this);
  11276. // Physics
  11277. if (this.physicsImpostor) {
  11278. this.physicsImpostor.dispose();
  11279. }
  11280. // Intersections in progress
  11281. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11282. var other = this._intersectionsInProgress[index];
  11283. var pos = other._intersectionsInProgress.indexOf(this);
  11284. other._intersectionsInProgress.splice(pos, 1);
  11285. }
  11286. this._intersectionsInProgress = [];
  11287. // Lights
  11288. var lights = this.getScene().lights;
  11289. lights.forEach(function (light) {
  11290. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11291. if (meshIndex !== -1) {
  11292. light.includedOnlyMeshes.splice(meshIndex, 1);
  11293. }
  11294. meshIndex = light.excludedMeshes.indexOf(_this);
  11295. if (meshIndex !== -1) {
  11296. light.excludedMeshes.splice(meshIndex, 1);
  11297. }
  11298. // Shadow generators
  11299. var generator = light.getShadowGenerator();
  11300. if (generator) {
  11301. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11302. if (meshIndex !== -1) {
  11303. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11304. }
  11305. }
  11306. });
  11307. // Edges
  11308. if (this._edgesRenderer) {
  11309. this._edgesRenderer.dispose();
  11310. this._edgesRenderer = null;
  11311. }
  11312. // SubMeshes
  11313. this.releaseSubMeshes();
  11314. // Engine
  11315. this.getScene().getEngine().unbindAllAttributes();
  11316. // Remove from scene
  11317. this.getScene().removeMesh(this);
  11318. if (!doNotRecurse) {
  11319. // Particles
  11320. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11321. if (this.getScene().particleSystems[index].emitter === this) {
  11322. this.getScene().particleSystems[index].dispose();
  11323. index--;
  11324. }
  11325. }
  11326. // Children
  11327. var objects = this.getDescendants(true);
  11328. for (index = 0; index < objects.length; index++) {
  11329. objects[index].dispose();
  11330. }
  11331. }
  11332. else {
  11333. var childMeshes = this.getChildMeshes(true);
  11334. for (index = 0; index < childMeshes.length; index++) {
  11335. var child = childMeshes[index];
  11336. child.parent = null;
  11337. child.computeWorldMatrix(true);
  11338. }
  11339. }
  11340. this.onAfterWorldMatrixUpdateObservable.clear();
  11341. this.onCollideObservable.clear();
  11342. this.onCollisionPositionChangeObservable.clear();
  11343. this._isDisposed = true;
  11344. _super.prototype.dispose.call(this);
  11345. };
  11346. AbstractMesh.prototype.getDirection = function (localAxis) {
  11347. var result = BABYLON.Vector3.Zero();
  11348. this.getDirectionToRef(localAxis, result);
  11349. return result;
  11350. };
  11351. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11352. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11353. };
  11354. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11355. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11356. if (this.getScene().getRenderId() == 0) {
  11357. this.computeWorldMatrix(true);
  11358. }
  11359. var wm = this.getWorldMatrix();
  11360. if (space == BABYLON.Space.WORLD) {
  11361. var tmat = BABYLON.Tmp.Matrix[0];
  11362. wm.invertToRef(tmat);
  11363. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11364. }
  11365. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11366. this._pivotMatrix.m[12] = -point.x;
  11367. this._pivotMatrix.m[13] = -point.y;
  11368. this._pivotMatrix.m[14] = -point.z;
  11369. this._cache.pivotMatrixUpdated = true;
  11370. };
  11371. AbstractMesh.prototype.getPivotPoint = function () {
  11372. var point = BABYLON.Vector3.Zero();
  11373. this.getPivotPointToRef(point);
  11374. return point;
  11375. };
  11376. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11377. result.x = -this._pivotMatrix.m[12];
  11378. result.y = -this._pivotMatrix.m[13];
  11379. result.z = -this._pivotMatrix.m[14];
  11380. };
  11381. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11382. var point = BABYLON.Vector3.Zero();
  11383. this.getAbsolutePivotPointToRef(point);
  11384. return point;
  11385. };
  11386. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11387. result.x = this._pivotMatrix.m[12];
  11388. result.y = this._pivotMatrix.m[13];
  11389. result.z = this._pivotMatrix.m[14];
  11390. this.getPivotPointToRef(result);
  11391. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11392. };
  11393. return AbstractMesh;
  11394. }(BABYLON.Node));
  11395. // Statics
  11396. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11397. AbstractMesh._BILLBOARDMODE_X = 1;
  11398. AbstractMesh._BILLBOARDMODE_Y = 2;
  11399. AbstractMesh._BILLBOARDMODE_Z = 4;
  11400. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11401. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11402. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11403. BABYLON.AbstractMesh = AbstractMesh;
  11404. })(BABYLON || (BABYLON = {}));
  11405. //# sourceMappingURL=babylon.abstractMesh.js.map
  11406. var BABYLON;
  11407. (function (BABYLON) {
  11408. var Light = (function (_super) {
  11409. __extends(Light, _super);
  11410. function Light(name, scene) {
  11411. var _this = _super.call(this, name, scene) || this;
  11412. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11413. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11414. _this.intensity = 1.0;
  11415. _this.range = Number.MAX_VALUE;
  11416. _this.includeOnlyWithLayerMask = 0;
  11417. _this.includedOnlyMeshes = new Array();
  11418. _this.excludedMeshes = new Array();
  11419. _this.excludeWithLayerMask = 0;
  11420. _this.lightmapMode = 0;
  11421. // PBR Properties.
  11422. _this.radius = 0.00001;
  11423. _this._excludedMeshesIds = new Array();
  11424. _this._includedOnlyMeshesIds = new Array();
  11425. scene.addLight(_this);
  11426. return _this;
  11427. }
  11428. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11429. /**
  11430. * If every light affecting the material is in this lightmapMode,
  11431. * material.lightmapTexture adds or multiplies
  11432. * (depends on material.useLightmapAsShadowmap)
  11433. * after every other light calculations.
  11434. */
  11435. get: function () {
  11436. return Light._LIGHTMAP_DEFAULT;
  11437. },
  11438. enumerable: true,
  11439. configurable: true
  11440. });
  11441. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11442. /**
  11443. * material.lightmapTexture as only diffuse lighting from this light
  11444. * adds pnly specular lighting from this light
  11445. * adds dynamic shadows
  11446. */
  11447. get: function () {
  11448. return Light._LIGHTMAP_SPECULAR;
  11449. },
  11450. enumerable: true,
  11451. configurable: true
  11452. });
  11453. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11454. /**
  11455. * material.lightmapTexture as only lighting
  11456. * no light calculation from this light
  11457. * only adds dynamic shadows from this light
  11458. */
  11459. get: function () {
  11460. return Light._LIGHTMAP_SHADOWSONLY;
  11461. },
  11462. enumerable: true,
  11463. configurable: true
  11464. });
  11465. Light.prototype.getClassName = function () {
  11466. return "Light";
  11467. };
  11468. /**
  11469. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11470. */
  11471. Light.prototype.toString = function (fullDetails) {
  11472. var ret = "Name: " + this.name;
  11473. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11474. if (this.animations) {
  11475. for (var i = 0; i < this.animations.length; i++) {
  11476. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11477. }
  11478. }
  11479. if (fullDetails) {
  11480. }
  11481. return ret;
  11482. };
  11483. Light.prototype.getShadowGenerator = function () {
  11484. return this._shadowGenerator;
  11485. };
  11486. Light.prototype.getAbsolutePosition = function () {
  11487. return BABYLON.Vector3.Zero();
  11488. };
  11489. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11490. };
  11491. Light.prototype._getWorldMatrix = function () {
  11492. return BABYLON.Matrix.Identity();
  11493. };
  11494. Light.prototype.canAffectMesh = function (mesh) {
  11495. if (!mesh) {
  11496. return true;
  11497. }
  11498. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11499. return false;
  11500. }
  11501. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11502. return false;
  11503. }
  11504. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11505. return false;
  11506. }
  11507. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11508. return false;
  11509. }
  11510. return true;
  11511. };
  11512. Light.prototype.getWorldMatrix = function () {
  11513. this._currentRenderId = this.getScene().getRenderId();
  11514. var worldMatrix = this._getWorldMatrix();
  11515. if (this.parent && this.parent.getWorldMatrix) {
  11516. if (!this._parentedWorldMatrix) {
  11517. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11518. }
  11519. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11520. this._markSyncedWithParent();
  11521. return this._parentedWorldMatrix;
  11522. }
  11523. return worldMatrix;
  11524. };
  11525. Light.prototype.dispose = function () {
  11526. if (this._shadowGenerator) {
  11527. this._shadowGenerator.dispose();
  11528. this._shadowGenerator = null;
  11529. }
  11530. // Animations
  11531. this.getScene().stopAnimation(this);
  11532. // Remove from scene
  11533. this.getScene().removeLight(this);
  11534. _super.prototype.dispose.call(this);
  11535. };
  11536. Light.prototype.getTypeID = function () {
  11537. return 0;
  11538. };
  11539. Light.prototype.clone = function (name) {
  11540. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11541. };
  11542. Light.prototype.serialize = function () {
  11543. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11544. // Type
  11545. serializationObject.type = this.getTypeID();
  11546. // Parent
  11547. if (this.parent) {
  11548. serializationObject.parentId = this.parent.id;
  11549. }
  11550. // Inclusion / exclusions
  11551. if (this.excludedMeshes.length > 0) {
  11552. serializationObject.excludedMeshesIds = [];
  11553. this.excludedMeshes.forEach(function (mesh) {
  11554. serializationObject.excludedMeshesIds.push(mesh.id);
  11555. });
  11556. }
  11557. if (this.includedOnlyMeshes.length > 0) {
  11558. serializationObject.includedOnlyMeshesIds = [];
  11559. this.includedOnlyMeshes.forEach(function (mesh) {
  11560. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11561. });
  11562. }
  11563. // Animations
  11564. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11565. serializationObject.ranges = this.serializeAnimationRanges();
  11566. return serializationObject;
  11567. };
  11568. Light.GetConstructorFromName = function (type, name, scene) {
  11569. switch (type) {
  11570. case 0:
  11571. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11572. case 1:
  11573. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11574. case 2:
  11575. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11576. case 3:
  11577. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11578. }
  11579. };
  11580. Light.Parse = function (parsedLight, scene) {
  11581. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11582. // Inclusion / exclusions
  11583. if (parsedLight.excludedMeshesIds) {
  11584. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11585. }
  11586. if (parsedLight.includedOnlyMeshesIds) {
  11587. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11588. }
  11589. // Parent
  11590. if (parsedLight.parentId) {
  11591. light._waitingParentId = parsedLight.parentId;
  11592. }
  11593. // Animations
  11594. if (parsedLight.animations) {
  11595. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11596. var parsedAnimation = parsedLight.animations[animationIndex];
  11597. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11598. }
  11599. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11600. }
  11601. if (parsedLight.autoAnimate) {
  11602. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11603. }
  11604. return light;
  11605. };
  11606. return Light;
  11607. }(BABYLON.Node));
  11608. //lightmapMode Consts
  11609. Light._LIGHTMAP_DEFAULT = 0;
  11610. Light._LIGHTMAP_SPECULAR = 1;
  11611. Light._LIGHTMAP_SHADOWSONLY = 2;
  11612. __decorate([
  11613. BABYLON.serializeAsColor3()
  11614. ], Light.prototype, "diffuse", void 0);
  11615. __decorate([
  11616. BABYLON.serializeAsColor3()
  11617. ], Light.prototype, "specular", void 0);
  11618. __decorate([
  11619. BABYLON.serialize()
  11620. ], Light.prototype, "intensity", void 0);
  11621. __decorate([
  11622. BABYLON.serialize()
  11623. ], Light.prototype, "range", void 0);
  11624. __decorate([
  11625. BABYLON.serialize()
  11626. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11627. __decorate([
  11628. BABYLON.serialize()
  11629. ], Light.prototype, "excludeWithLayerMask", void 0);
  11630. __decorate([
  11631. BABYLON.serialize()
  11632. ], Light.prototype, "lightmapMode", void 0);
  11633. __decorate([
  11634. BABYLON.serialize()
  11635. ], Light.prototype, "radius", void 0);
  11636. BABYLON.Light = Light;
  11637. })(BABYLON || (BABYLON = {}));
  11638. //# sourceMappingURL=babylon.light.js.map
  11639. var BABYLON;
  11640. (function (BABYLON) {
  11641. var PointLight = (function (_super) {
  11642. __extends(PointLight, _super);
  11643. function PointLight(name, position, scene) {
  11644. var _this = _super.call(this, name, scene) || this;
  11645. _this.position = position;
  11646. return _this;
  11647. }
  11648. PointLight.prototype.getClassName = function () {
  11649. return "PointLight";
  11650. };
  11651. PointLight.prototype.getAbsolutePosition = function () {
  11652. return this.transformedPosition ? this.transformedPosition : this.position;
  11653. };
  11654. PointLight.prototype.computeTransformedPosition = function () {
  11655. if (this.parent && this.parent.getWorldMatrix) {
  11656. if (!this.transformedPosition) {
  11657. this.transformedPosition = BABYLON.Vector3.Zero();
  11658. }
  11659. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11660. return true;
  11661. }
  11662. return false;
  11663. };
  11664. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11665. if (this.parent && this.parent.getWorldMatrix) {
  11666. this.computeTransformedPosition();
  11667. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11668. return;
  11669. }
  11670. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11671. };
  11672. PointLight.prototype.needCube = function () {
  11673. return true;
  11674. };
  11675. PointLight.prototype.supportsVSM = function () {
  11676. return false;
  11677. };
  11678. PointLight.prototype.needRefreshPerFrame = function () {
  11679. return false;
  11680. };
  11681. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11682. switch (faceIndex) {
  11683. case 0:
  11684. return new BABYLON.Vector3(1, 0, 0);
  11685. case 1:
  11686. return new BABYLON.Vector3(-1, 0, 0);
  11687. case 2:
  11688. return new BABYLON.Vector3(0, -1, 0);
  11689. case 3:
  11690. return new BABYLON.Vector3(0, 1, 0);
  11691. case 4:
  11692. return new BABYLON.Vector3(0, 0, 1);
  11693. case 5:
  11694. return new BABYLON.Vector3(0, 0, -1);
  11695. }
  11696. return BABYLON.Vector3.Zero();
  11697. };
  11698. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11699. var activeCamera = this.getScene().activeCamera;
  11700. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11701. };
  11702. PointLight.prototype._getWorldMatrix = function () {
  11703. if (!this._worldMatrix) {
  11704. this._worldMatrix = BABYLON.Matrix.Identity();
  11705. }
  11706. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11707. return this._worldMatrix;
  11708. };
  11709. PointLight.prototype.getTypeID = function () {
  11710. return 0;
  11711. };
  11712. return PointLight;
  11713. }(BABYLON.Light));
  11714. __decorate([
  11715. BABYLON.serializeAsVector3()
  11716. ], PointLight.prototype, "position", void 0);
  11717. BABYLON.PointLight = PointLight;
  11718. })(BABYLON || (BABYLON = {}));
  11719. //# sourceMappingURL=babylon.pointLight.js.map
  11720. var BABYLON;
  11721. (function (BABYLON) {
  11722. var SpotLight = (function (_super) {
  11723. __extends(SpotLight, _super);
  11724. function SpotLight(name, position, direction, angle, exponent, scene) {
  11725. var _this = _super.call(this, name, scene) || this;
  11726. _this.position = position;
  11727. _this.direction = direction;
  11728. _this.angle = angle;
  11729. _this.exponent = exponent;
  11730. return _this;
  11731. }
  11732. SpotLight.prototype.getClassName = function () {
  11733. return "SpotLight";
  11734. };
  11735. SpotLight.prototype.getAbsolutePosition = function () {
  11736. return this.transformedPosition ? this.transformedPosition : this.position;
  11737. };
  11738. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11739. var activeCamera = this.getScene().activeCamera;
  11740. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11741. };
  11742. SpotLight.prototype.needCube = function () {
  11743. return false;
  11744. };
  11745. SpotLight.prototype.supportsVSM = function () {
  11746. return true;
  11747. };
  11748. SpotLight.prototype.needRefreshPerFrame = function () {
  11749. return false;
  11750. };
  11751. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11752. return this.direction;
  11753. };
  11754. SpotLight.prototype.setDirectionToTarget = function (target) {
  11755. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11756. return this.direction;
  11757. };
  11758. SpotLight.prototype.computeTransformedPosition = function () {
  11759. if (this.parent && this.parent.getWorldMatrix) {
  11760. if (!this.transformedPosition) {
  11761. this.transformedPosition = BABYLON.Vector3.Zero();
  11762. }
  11763. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11764. return true;
  11765. }
  11766. return false;
  11767. };
  11768. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11769. var normalizeDirection;
  11770. if (this.parent && this.parent.getWorldMatrix) {
  11771. if (!this._transformedDirection) {
  11772. this._transformedDirection = BABYLON.Vector3.Zero();
  11773. }
  11774. this.computeTransformedPosition();
  11775. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11776. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11777. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11778. }
  11779. else {
  11780. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11781. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11782. }
  11783. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11784. };
  11785. SpotLight.prototype._getWorldMatrix = function () {
  11786. if (!this._worldMatrix) {
  11787. this._worldMatrix = BABYLON.Matrix.Identity();
  11788. }
  11789. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11790. return this._worldMatrix;
  11791. };
  11792. SpotLight.prototype.getTypeID = function () {
  11793. return 2;
  11794. };
  11795. SpotLight.prototype.getRotation = function () {
  11796. this.direction.normalize();
  11797. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  11798. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  11799. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  11800. };
  11801. return SpotLight;
  11802. }(BABYLON.Light));
  11803. __decorate([
  11804. BABYLON.serializeAsVector3()
  11805. ], SpotLight.prototype, "position", void 0);
  11806. __decorate([
  11807. BABYLON.serializeAsVector3()
  11808. ], SpotLight.prototype, "direction", void 0);
  11809. __decorate([
  11810. BABYLON.serialize()
  11811. ], SpotLight.prototype, "angle", void 0);
  11812. __decorate([
  11813. BABYLON.serialize()
  11814. ], SpotLight.prototype, "exponent", void 0);
  11815. BABYLON.SpotLight = SpotLight;
  11816. })(BABYLON || (BABYLON = {}));
  11817. //# sourceMappingURL=babylon.spotLight.js.map
  11818. var BABYLON;
  11819. (function (BABYLON) {
  11820. var HemisphericLight = (function (_super) {
  11821. __extends(HemisphericLight, _super);
  11822. function HemisphericLight(name, direction, scene) {
  11823. var _this = _super.call(this, name, scene) || this;
  11824. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11825. _this.direction = direction;
  11826. return _this;
  11827. }
  11828. HemisphericLight.prototype.getClassName = function () {
  11829. return "HemisphericLight";
  11830. };
  11831. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11832. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11833. return this.direction;
  11834. };
  11835. HemisphericLight.prototype.getShadowGenerator = function () {
  11836. return null;
  11837. };
  11838. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11839. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11840. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11841. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11842. };
  11843. HemisphericLight.prototype._getWorldMatrix = function () {
  11844. if (!this._worldMatrix) {
  11845. this._worldMatrix = BABYLON.Matrix.Identity();
  11846. }
  11847. return this._worldMatrix;
  11848. };
  11849. HemisphericLight.prototype.getTypeID = function () {
  11850. return 3;
  11851. };
  11852. return HemisphericLight;
  11853. }(BABYLON.Light));
  11854. __decorate([
  11855. BABYLON.serializeAsColor3()
  11856. ], HemisphericLight.prototype, "groundColor", void 0);
  11857. __decorate([
  11858. BABYLON.serializeAsVector3()
  11859. ], HemisphericLight.prototype, "direction", void 0);
  11860. BABYLON.HemisphericLight = HemisphericLight;
  11861. })(BABYLON || (BABYLON = {}));
  11862. //# sourceMappingURL=babylon.hemisphericLight.js.map
  11863. var BABYLON;
  11864. (function (BABYLON) {
  11865. var DirectionalLight = (function (_super) {
  11866. __extends(DirectionalLight, _super);
  11867. function DirectionalLight(name, direction, scene) {
  11868. var _this = _super.call(this, name, scene) || this;
  11869. _this.shadowOrthoScale = 0.5;
  11870. _this.autoUpdateExtends = true;
  11871. // Cache
  11872. _this._orthoLeft = Number.MAX_VALUE;
  11873. _this._orthoRight = Number.MIN_VALUE;
  11874. _this._orthoTop = Number.MIN_VALUE;
  11875. _this._orthoBottom = Number.MAX_VALUE;
  11876. _this.position = direction.scale(-1);
  11877. _this.direction = direction;
  11878. return _this;
  11879. }
  11880. DirectionalLight.prototype.getClassName = function () {
  11881. return "DirectionalLight";
  11882. };
  11883. DirectionalLight.prototype.getAbsolutePosition = function () {
  11884. return this.transformedPosition ? this.transformedPosition : this.position;
  11885. };
  11886. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11887. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11888. return this.direction;
  11889. };
  11890. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11891. var activeCamera = this.getScene().activeCamera;
  11892. // Check extends
  11893. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11894. var tempVector3 = BABYLON.Vector3.Zero();
  11895. this._orthoLeft = Number.MAX_VALUE;
  11896. this._orthoRight = Number.MIN_VALUE;
  11897. this._orthoTop = Number.MIN_VALUE;
  11898. this._orthoBottom = Number.MAX_VALUE;
  11899. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11900. var mesh = renderList[meshIndex];
  11901. if (!mesh) {
  11902. continue;
  11903. }
  11904. var boundingInfo = mesh.getBoundingInfo();
  11905. if (!boundingInfo) {
  11906. continue;
  11907. }
  11908. var boundingBox = boundingInfo.boundingBox;
  11909. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11910. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11911. if (tempVector3.x < this._orthoLeft)
  11912. this._orthoLeft = tempVector3.x;
  11913. if (tempVector3.y < this._orthoBottom)
  11914. this._orthoBottom = tempVector3.y;
  11915. if (tempVector3.x > this._orthoRight)
  11916. this._orthoRight = tempVector3.x;
  11917. if (tempVector3.y > this._orthoTop)
  11918. this._orthoTop = tempVector3.y;
  11919. }
  11920. }
  11921. }
  11922. var xOffset = this._orthoRight - this._orthoLeft;
  11923. var yOffset = this._orthoTop - this._orthoBottom;
  11924. 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);
  11925. };
  11926. DirectionalLight.prototype.supportsVSM = function () {
  11927. return true;
  11928. };
  11929. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11930. return true;
  11931. };
  11932. DirectionalLight.prototype.needCube = function () {
  11933. return false;
  11934. };
  11935. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11936. return this.direction;
  11937. };
  11938. DirectionalLight.prototype.computeTransformedPosition = function () {
  11939. if (this.parent && this.parent.getWorldMatrix) {
  11940. if (!this.transformedPosition) {
  11941. this.transformedPosition = BABYLON.Vector3.Zero();
  11942. }
  11943. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11944. return true;
  11945. }
  11946. return false;
  11947. };
  11948. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11949. if (this.parent && this.parent.getWorldMatrix) {
  11950. if (!this._transformedDirection) {
  11951. this._transformedDirection = BABYLON.Vector3.Zero();
  11952. }
  11953. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11954. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11955. return;
  11956. }
  11957. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11958. };
  11959. DirectionalLight.prototype._getWorldMatrix = function () {
  11960. if (!this._worldMatrix) {
  11961. this._worldMatrix = BABYLON.Matrix.Identity();
  11962. }
  11963. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11964. return this._worldMatrix;
  11965. };
  11966. DirectionalLight.prototype.getTypeID = function () {
  11967. return 1;
  11968. };
  11969. return DirectionalLight;
  11970. }(BABYLON.Light));
  11971. __decorate([
  11972. BABYLON.serializeAsVector3()
  11973. ], DirectionalLight.prototype, "position", void 0);
  11974. __decorate([
  11975. BABYLON.serializeAsVector3()
  11976. ], DirectionalLight.prototype, "direction", void 0);
  11977. __decorate([
  11978. BABYLON.serialize()
  11979. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11980. __decorate([
  11981. BABYLON.serialize()
  11982. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11983. BABYLON.DirectionalLight = DirectionalLight;
  11984. })(BABYLON || (BABYLON = {}));
  11985. //# sourceMappingURL=babylon.directionalLight.js.map
  11986. var BABYLON;
  11987. (function (BABYLON) {
  11988. var ShadowGenerator = (function () {
  11989. function ShadowGenerator(mapSize, light) {
  11990. var _this = this;
  11991. // Members
  11992. this._filter = ShadowGenerator.FILTER_NONE;
  11993. this.blurScale = 2;
  11994. this._blurBoxOffset = 0;
  11995. this._bias = 0.00005;
  11996. this._lightDirection = BABYLON.Vector3.Zero();
  11997. this.forceBackFacesOnly = false;
  11998. this._darkness = 0;
  11999. this._transparencyShadow = false;
  12000. this._viewMatrix = BABYLON.Matrix.Zero();
  12001. this._projectionMatrix = BABYLON.Matrix.Zero();
  12002. this._transformMatrix = BABYLON.Matrix.Zero();
  12003. this._worldViewProjection = BABYLON.Matrix.Zero();
  12004. this._currentFaceIndex = 0;
  12005. this._currentFaceIndexCache = 0;
  12006. this._useFullFloat = true;
  12007. this._light = light;
  12008. this._scene = light.getScene();
  12009. this._mapSize = mapSize;
  12010. light._shadowGenerator = this;
  12011. // Texture type fallback from float to int if not supported.
  12012. var textureType;
  12013. var caps = this._scene.getEngine().getCaps();
  12014. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12015. this._useFullFloat = true;
  12016. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12017. }
  12018. else {
  12019. this._useFullFloat = false;
  12020. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12021. }
  12022. // Render target
  12023. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12024. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12025. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12026. this._shadowMap.anisotropicFilteringLevel = 1;
  12027. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12028. this._shadowMap.renderParticles = false;
  12029. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12030. _this._currentFaceIndex = faceIndex;
  12031. });
  12032. this._shadowMap.onAfterUnbindObservable.add(function () {
  12033. if (!_this.useBlurVarianceShadowMap) {
  12034. return;
  12035. }
  12036. if (!_this._shadowMap2) {
  12037. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12038. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12039. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12040. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12041. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12042. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12043. effect.setTexture("textureSampler", _this._shadowMap);
  12044. });
  12045. _this.blurBoxOffset = 1;
  12046. }
  12047. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12048. });
  12049. // Custom render function
  12050. var renderSubMesh = function (subMesh) {
  12051. var mesh = subMesh.getRenderingMesh();
  12052. var scene = _this._scene;
  12053. var engine = scene.getEngine();
  12054. // Culling
  12055. engine.setState(subMesh.getMaterial().backFaceCulling);
  12056. // Managing instances
  12057. var batch = mesh._getInstancesRenderList(subMesh._id);
  12058. if (batch.mustReturn) {
  12059. return;
  12060. }
  12061. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12062. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12063. engine.enableEffect(_this._effect);
  12064. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12065. var material = subMesh.getMaterial();
  12066. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12067. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12068. if (_this.getLight().needCube()) {
  12069. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12070. }
  12071. // Alpha test
  12072. if (material && material.needAlphaTesting()) {
  12073. var alphaTexture = material.getAlphaTestTexture();
  12074. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12075. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12076. }
  12077. // Bones
  12078. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12079. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12080. }
  12081. if (_this.forceBackFacesOnly) {
  12082. engine.setState(true, 0, false, true);
  12083. }
  12084. // Draw
  12085. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12086. if (_this.forceBackFacesOnly) {
  12087. engine.setState(true, 0, false, false);
  12088. }
  12089. }
  12090. else {
  12091. // Need to reset refresh rate of the shadowMap
  12092. _this._shadowMap.resetRefreshCounter();
  12093. }
  12094. };
  12095. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12096. var index;
  12097. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12098. renderSubMesh(opaqueSubMeshes.data[index]);
  12099. }
  12100. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12101. renderSubMesh(alphaTestSubMeshes.data[index]);
  12102. }
  12103. if (_this._transparencyShadow) {
  12104. for (index = 0; index < transparentSubMeshes.length; index++) {
  12105. renderSubMesh(transparentSubMeshes.data[index]);
  12106. }
  12107. }
  12108. };
  12109. this._shadowMap.onClearObservable.add(function (engine) {
  12110. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12111. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12112. }
  12113. else {
  12114. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12115. }
  12116. });
  12117. }
  12118. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12119. // Static
  12120. get: function () {
  12121. return ShadowGenerator._FILTER_NONE;
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12127. get: function () {
  12128. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12134. get: function () {
  12135. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12141. get: function () {
  12142. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12143. },
  12144. enumerable: true,
  12145. configurable: true
  12146. });
  12147. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12148. get: function () {
  12149. return this._bias;
  12150. },
  12151. set: function (bias) {
  12152. this._bias = bias;
  12153. },
  12154. enumerable: true,
  12155. configurable: true
  12156. });
  12157. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12158. get: function () {
  12159. return this._blurBoxOffset;
  12160. },
  12161. set: function (value) {
  12162. var _this = this;
  12163. if (this._blurBoxOffset === value) {
  12164. return;
  12165. }
  12166. this._blurBoxOffset = value;
  12167. if (this._boxBlurPostprocess) {
  12168. this._boxBlurPostprocess.dispose();
  12169. }
  12170. 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);
  12171. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12172. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12173. });
  12174. },
  12175. enumerable: true,
  12176. configurable: true
  12177. });
  12178. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12179. get: function () {
  12180. return this._filter;
  12181. },
  12182. set: function (value) {
  12183. if (this._filter === value) {
  12184. return;
  12185. }
  12186. this._filter = value;
  12187. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12188. this._shadowMap.anisotropicFilteringLevel = 16;
  12189. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12190. }
  12191. else {
  12192. this._shadowMap.anisotropicFilteringLevel = 1;
  12193. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12194. }
  12195. },
  12196. enumerable: true,
  12197. configurable: true
  12198. });
  12199. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12200. get: function () {
  12201. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12202. },
  12203. set: function (value) {
  12204. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12210. get: function () {
  12211. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12212. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12213. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12214. },
  12215. set: function (value) {
  12216. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12217. },
  12218. enumerable: true,
  12219. configurable: true
  12220. });
  12221. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12222. get: function () {
  12223. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12224. },
  12225. set: function (value) {
  12226. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12227. },
  12228. enumerable: true,
  12229. configurable: true
  12230. });
  12231. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12232. var defines = [];
  12233. if (this._useFullFloat) {
  12234. defines.push("#define FULLFLOAT");
  12235. }
  12236. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12237. defines.push("#define VSM");
  12238. }
  12239. if (this.getLight().needCube()) {
  12240. defines.push("#define CUBEMAP");
  12241. }
  12242. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12243. var mesh = subMesh.getMesh();
  12244. var material = subMesh.getMaterial();
  12245. // Alpha test
  12246. if (material && material.needAlphaTesting()) {
  12247. defines.push("#define ALPHATEST");
  12248. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12249. attribs.push(BABYLON.VertexBuffer.UVKind);
  12250. defines.push("#define UV1");
  12251. }
  12252. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12253. var alphaTexture = material.getAlphaTestTexture();
  12254. if (alphaTexture.coordinatesIndex === 1) {
  12255. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12256. defines.push("#define UV2");
  12257. }
  12258. }
  12259. }
  12260. // Bones
  12261. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12262. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12263. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12264. if (mesh.numBoneInfluencers > 4) {
  12265. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12266. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12267. }
  12268. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12269. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12270. }
  12271. else {
  12272. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12273. }
  12274. // Instances
  12275. if (useInstances) {
  12276. defines.push("#define INSTANCES");
  12277. attribs.push("world0");
  12278. attribs.push("world1");
  12279. attribs.push("world2");
  12280. attribs.push("world3");
  12281. }
  12282. // Get correct effect
  12283. var join = defines.join("\n");
  12284. if (this._cachedDefines !== join) {
  12285. this._cachedDefines = join;
  12286. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12287. }
  12288. return this._effect.isReady();
  12289. };
  12290. ShadowGenerator.prototype.getShadowMap = function () {
  12291. return this._shadowMap;
  12292. };
  12293. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12294. if (this._shadowMap2) {
  12295. return this._shadowMap2;
  12296. }
  12297. return this._shadowMap;
  12298. };
  12299. ShadowGenerator.prototype.getLight = function () {
  12300. return this._light;
  12301. };
  12302. // Methods
  12303. ShadowGenerator.prototype.getTransformMatrix = function () {
  12304. var scene = this._scene;
  12305. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12306. return this._transformMatrix;
  12307. }
  12308. this._currentRenderID = scene.getRenderId();
  12309. this._currentFaceIndexCache = this._currentFaceIndex;
  12310. var lightPosition = this._light.position;
  12311. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12312. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12313. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12314. }
  12315. if (this._light.computeTransformedPosition()) {
  12316. lightPosition = this._light.transformedPosition;
  12317. }
  12318. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12319. this._cachedPosition = lightPosition.clone();
  12320. this._cachedDirection = this._lightDirection.clone();
  12321. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12322. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12323. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12324. }
  12325. return this._transformMatrix;
  12326. };
  12327. ShadowGenerator.prototype.getDarkness = function () {
  12328. return this._darkness;
  12329. };
  12330. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12331. if (darkness >= 1.0)
  12332. this._darkness = 1.0;
  12333. else if (darkness <= 0.0)
  12334. this._darkness = 0.0;
  12335. else
  12336. this._darkness = darkness;
  12337. };
  12338. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12339. this._transparencyShadow = hasShadow;
  12340. };
  12341. ShadowGenerator.prototype._packHalf = function (depth) {
  12342. var scale = depth * 255.0;
  12343. var fract = scale - Math.floor(scale);
  12344. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12345. };
  12346. ShadowGenerator.prototype.dispose = function () {
  12347. this._shadowMap.dispose();
  12348. if (this._shadowMap2) {
  12349. this._shadowMap2.dispose();
  12350. }
  12351. if (this._downSamplePostprocess) {
  12352. this._downSamplePostprocess.dispose();
  12353. }
  12354. if (this._boxBlurPostprocess) {
  12355. this._boxBlurPostprocess.dispose();
  12356. }
  12357. };
  12358. ShadowGenerator.prototype.serialize = function () {
  12359. var serializationObject = {};
  12360. serializationObject.lightId = this._light.id;
  12361. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12362. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12363. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12364. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12365. serializationObject.renderList = [];
  12366. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12367. var mesh = this.getShadowMap().renderList[meshIndex];
  12368. serializationObject.renderList.push(mesh.id);
  12369. }
  12370. return serializationObject;
  12371. };
  12372. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12373. //casting to point light, as light is missing the position attr and typescript complains.
  12374. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12375. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12376. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12377. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12378. meshes.forEach(function (mesh) {
  12379. shadowGenerator.getShadowMap().renderList.push(mesh);
  12380. });
  12381. }
  12382. if (parsedShadowGenerator.usePoissonSampling) {
  12383. shadowGenerator.usePoissonSampling = true;
  12384. }
  12385. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12386. shadowGenerator.useVarianceShadowMap = true;
  12387. }
  12388. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12389. shadowGenerator.useBlurVarianceShadowMap = true;
  12390. if (parsedShadowGenerator.blurScale) {
  12391. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12392. }
  12393. if (parsedShadowGenerator.blurBoxOffset) {
  12394. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12395. }
  12396. }
  12397. if (parsedShadowGenerator.bias !== undefined) {
  12398. shadowGenerator.bias = parsedShadowGenerator.bias;
  12399. }
  12400. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12401. return shadowGenerator;
  12402. };
  12403. return ShadowGenerator;
  12404. }());
  12405. ShadowGenerator._FILTER_NONE = 0;
  12406. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12407. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12408. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12409. BABYLON.ShadowGenerator = ShadowGenerator;
  12410. })(BABYLON || (BABYLON = {}));
  12411. //# sourceMappingURL=babylon.shadowGenerator.js.map
  12412. var BABYLON;
  12413. (function (BABYLON) {
  12414. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12415. if (boxMin.x > sphereCenter.x + sphereRadius)
  12416. return false;
  12417. if (sphereCenter.x - sphereRadius > boxMax.x)
  12418. return false;
  12419. if (boxMin.y > sphereCenter.y + sphereRadius)
  12420. return false;
  12421. if (sphereCenter.y - sphereRadius > boxMax.y)
  12422. return false;
  12423. if (boxMin.z > sphereCenter.z + sphereRadius)
  12424. return false;
  12425. if (sphereCenter.z - sphereRadius > boxMax.z)
  12426. return false;
  12427. return true;
  12428. };
  12429. var getLowestRoot = (function () {
  12430. var result = { root: 0, found: false };
  12431. return function (a, b, c, maxR) {
  12432. result.root = 0;
  12433. result.found = false;
  12434. var determinant = b * b - 4.0 * a * c;
  12435. if (determinant < 0)
  12436. return result;
  12437. var sqrtD = Math.sqrt(determinant);
  12438. var r1 = (-b - sqrtD) / (2.0 * a);
  12439. var r2 = (-b + sqrtD) / (2.0 * a);
  12440. if (r1 > r2) {
  12441. var temp = r2;
  12442. r2 = r1;
  12443. r1 = temp;
  12444. }
  12445. if (r1 > 0 && r1 < maxR) {
  12446. result.root = r1;
  12447. result.found = true;
  12448. return result;
  12449. }
  12450. if (r2 > 0 && r2 < maxR) {
  12451. result.root = r2;
  12452. result.found = true;
  12453. return result;
  12454. }
  12455. return result;
  12456. };
  12457. })();
  12458. var Collider = (function () {
  12459. function Collider() {
  12460. this.radius = new BABYLON.Vector3(1, 1, 1);
  12461. this.retry = 0;
  12462. this.basePointWorld = BABYLON.Vector3.Zero();
  12463. this.velocityWorld = BABYLON.Vector3.Zero();
  12464. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12465. this._collisionPoint = BABYLON.Vector3.Zero();
  12466. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12467. this._tempVector = BABYLON.Vector3.Zero();
  12468. this._tempVector2 = BABYLON.Vector3.Zero();
  12469. this._tempVector3 = BABYLON.Vector3.Zero();
  12470. this._tempVector4 = BABYLON.Vector3.Zero();
  12471. this._edge = BABYLON.Vector3.Zero();
  12472. this._baseToVertex = BABYLON.Vector3.Zero();
  12473. this._destinationPoint = BABYLON.Vector3.Zero();
  12474. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12475. this._displacementVector = BABYLON.Vector3.Zero();
  12476. }
  12477. // Methods
  12478. Collider.prototype._initialize = function (source, dir, e) {
  12479. this.velocity = dir;
  12480. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12481. this.basePoint = source;
  12482. source.multiplyToRef(this.radius, this.basePointWorld);
  12483. dir.multiplyToRef(this.radius, this.velocityWorld);
  12484. this.velocityWorldLength = this.velocityWorld.length();
  12485. this.epsilon = e;
  12486. this.collisionFound = false;
  12487. };
  12488. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12489. pa.subtractToRef(point, this._tempVector);
  12490. pb.subtractToRef(point, this._tempVector2);
  12491. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12492. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12493. if (d < 0)
  12494. return false;
  12495. pc.subtractToRef(point, this._tempVector3);
  12496. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12497. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12498. if (d < 0)
  12499. return false;
  12500. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12501. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12502. return d >= 0;
  12503. };
  12504. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12505. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12506. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12507. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12508. return false;
  12509. }
  12510. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12511. return false;
  12512. return true;
  12513. };
  12514. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12515. var t0;
  12516. var embeddedInPlane = false;
  12517. //defensive programming, actually not needed.
  12518. if (!trianglePlaneArray) {
  12519. trianglePlaneArray = [];
  12520. }
  12521. if (!trianglePlaneArray[faceIndex]) {
  12522. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12523. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12524. }
  12525. var trianglePlane = trianglePlaneArray[faceIndex];
  12526. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12527. return;
  12528. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12529. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12530. if (normalDotVelocity == 0) {
  12531. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12532. return;
  12533. embeddedInPlane = true;
  12534. t0 = 0;
  12535. }
  12536. else {
  12537. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12538. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12539. if (t0 > t1) {
  12540. var temp = t1;
  12541. t1 = t0;
  12542. t0 = temp;
  12543. }
  12544. if (t0 > 1.0 || t1 < 0.0)
  12545. return;
  12546. if (t0 < 0)
  12547. t0 = 0;
  12548. if (t0 > 1.0)
  12549. t0 = 1.0;
  12550. }
  12551. this._collisionPoint.copyFromFloats(0, 0, 0);
  12552. var found = false;
  12553. var t = 1.0;
  12554. if (!embeddedInPlane) {
  12555. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12556. this.velocity.scaleToRef(t0, this._tempVector);
  12557. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12558. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12559. found = true;
  12560. t = t0;
  12561. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12562. }
  12563. }
  12564. if (!found) {
  12565. var velocitySquaredLength = this.velocity.lengthSquared();
  12566. var a = velocitySquaredLength;
  12567. this.basePoint.subtractToRef(p1, this._tempVector);
  12568. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12569. var c = this._tempVector.lengthSquared() - 1.0;
  12570. var lowestRoot = getLowestRoot(a, b, c, t);
  12571. if (lowestRoot.found) {
  12572. t = lowestRoot.root;
  12573. found = true;
  12574. this._collisionPoint.copyFrom(p1);
  12575. }
  12576. this.basePoint.subtractToRef(p2, this._tempVector);
  12577. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12578. c = this._tempVector.lengthSquared() - 1.0;
  12579. lowestRoot = getLowestRoot(a, b, c, t);
  12580. if (lowestRoot.found) {
  12581. t = lowestRoot.root;
  12582. found = true;
  12583. this._collisionPoint.copyFrom(p2);
  12584. }
  12585. this.basePoint.subtractToRef(p3, this._tempVector);
  12586. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12587. c = this._tempVector.lengthSquared() - 1.0;
  12588. lowestRoot = getLowestRoot(a, b, c, t);
  12589. if (lowestRoot.found) {
  12590. t = lowestRoot.root;
  12591. found = true;
  12592. this._collisionPoint.copyFrom(p3);
  12593. }
  12594. p2.subtractToRef(p1, this._edge);
  12595. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12596. var edgeSquaredLength = this._edge.lengthSquared();
  12597. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12598. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12599. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12600. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12601. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12602. lowestRoot = getLowestRoot(a, b, c, t);
  12603. if (lowestRoot.found) {
  12604. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12605. if (f >= 0.0 && f <= 1.0) {
  12606. t = lowestRoot.root;
  12607. found = true;
  12608. this._edge.scaleInPlace(f);
  12609. p1.addToRef(this._edge, this._collisionPoint);
  12610. }
  12611. }
  12612. p3.subtractToRef(p2, this._edge);
  12613. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12614. edgeSquaredLength = this._edge.lengthSquared();
  12615. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12616. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12617. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12618. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12619. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12620. lowestRoot = getLowestRoot(a, b, c, t);
  12621. if (lowestRoot.found) {
  12622. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12623. if (f >= 0.0 && f <= 1.0) {
  12624. t = lowestRoot.root;
  12625. found = true;
  12626. this._edge.scaleInPlace(f);
  12627. p2.addToRef(this._edge, this._collisionPoint);
  12628. }
  12629. }
  12630. p1.subtractToRef(p3, this._edge);
  12631. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12632. edgeSquaredLength = this._edge.lengthSquared();
  12633. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12634. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12635. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12636. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12637. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12638. lowestRoot = getLowestRoot(a, b, c, t);
  12639. if (lowestRoot.found) {
  12640. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12641. if (f >= 0.0 && f <= 1.0) {
  12642. t = lowestRoot.root;
  12643. found = true;
  12644. this._edge.scaleInPlace(f);
  12645. p3.addToRef(this._edge, this._collisionPoint);
  12646. }
  12647. }
  12648. }
  12649. if (found) {
  12650. var distToCollision = t * this.velocity.length();
  12651. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12652. if (!this.intersectionPoint) {
  12653. this.intersectionPoint = this._collisionPoint.clone();
  12654. }
  12655. else {
  12656. this.intersectionPoint.copyFrom(this._collisionPoint);
  12657. }
  12658. this.nearestDistance = distToCollision;
  12659. this.collisionFound = true;
  12660. }
  12661. }
  12662. };
  12663. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12664. for (var i = indexStart; i < indexEnd; i += 3) {
  12665. var p1 = pts[indices[i] - decal];
  12666. var p2 = pts[indices[i + 1] - decal];
  12667. var p3 = pts[indices[i + 2] - decal];
  12668. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12669. }
  12670. };
  12671. Collider.prototype._getResponse = function (pos, vel) {
  12672. pos.addToRef(vel, this._destinationPoint);
  12673. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12674. this.basePoint.addToRef(vel, pos);
  12675. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12676. this._slidePlaneNormal.normalize();
  12677. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12678. pos.addInPlace(this._displacementVector);
  12679. this.intersectionPoint.addInPlace(this._displacementVector);
  12680. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12681. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12682. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12683. };
  12684. return Collider;
  12685. }());
  12686. BABYLON.Collider = Collider;
  12687. })(BABYLON || (BABYLON = {}));
  12688. //# sourceMappingURL=babylon.collider.js.map
  12689. var BABYLON;
  12690. (function (BABYLON) {
  12691. //WebWorker code will be inserted to this variable.
  12692. BABYLON.CollisionWorker = "";
  12693. var WorkerTaskType;
  12694. (function (WorkerTaskType) {
  12695. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12696. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12697. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12698. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12699. var WorkerReplyType;
  12700. (function (WorkerReplyType) {
  12701. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12702. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12703. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12704. var CollisionCoordinatorWorker = (function () {
  12705. function CollisionCoordinatorWorker() {
  12706. var _this = this;
  12707. this._scaledPosition = BABYLON.Vector3.Zero();
  12708. this._scaledVelocity = BABYLON.Vector3.Zero();
  12709. this.onMeshUpdated = function (mesh) {
  12710. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12711. };
  12712. this.onGeometryUpdated = function (geometry) {
  12713. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12714. };
  12715. this._afterRender = function () {
  12716. if (!_this._init)
  12717. return;
  12718. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12719. return;
  12720. }
  12721. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12722. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12723. if (_this._runningUpdated > 4) {
  12724. return;
  12725. }
  12726. ++_this._runningUpdated;
  12727. var payload = {
  12728. updatedMeshes: _this._addUpdateMeshesList,
  12729. updatedGeometries: _this._addUpdateGeometriesList,
  12730. removedGeometries: _this._toRemoveGeometryArray,
  12731. removedMeshes: _this._toRemoveMeshesArray
  12732. };
  12733. var message = {
  12734. payload: payload,
  12735. taskType: WorkerTaskType.UPDATE
  12736. };
  12737. var serializable = [];
  12738. for (var id in payload.updatedGeometries) {
  12739. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12740. //prepare transferables
  12741. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12742. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12743. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12744. }
  12745. }
  12746. _this._worker.postMessage(message, serializable);
  12747. _this._addUpdateMeshesList = {};
  12748. _this._addUpdateGeometriesList = {};
  12749. _this._toRemoveGeometryArray = [];
  12750. _this._toRemoveMeshesArray = [];
  12751. };
  12752. this._onMessageFromWorker = function (e) {
  12753. var returnData = e.data;
  12754. if (returnData.error != WorkerReplyType.SUCCESS) {
  12755. //TODO what errors can be returned from the worker?
  12756. BABYLON.Tools.Warn("error returned from worker!");
  12757. return;
  12758. }
  12759. switch (returnData.taskType) {
  12760. case WorkerTaskType.INIT:
  12761. _this._init = true;
  12762. //Update the worked with ALL of the scene's current state
  12763. _this._scene.meshes.forEach(function (mesh) {
  12764. _this.onMeshAdded(mesh);
  12765. });
  12766. _this._scene.getGeometries().forEach(function (geometry) {
  12767. _this.onGeometryAdded(geometry);
  12768. });
  12769. break;
  12770. case WorkerTaskType.UPDATE:
  12771. _this._runningUpdated--;
  12772. break;
  12773. case WorkerTaskType.COLLIDE:
  12774. _this._runningCollisionTask = false;
  12775. var returnPayload = returnData.payload;
  12776. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12777. return;
  12778. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12779. //cleanup
  12780. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12781. break;
  12782. }
  12783. };
  12784. this._collisionsCallbackArray = [];
  12785. this._init = false;
  12786. this._runningUpdated = 0;
  12787. this._runningCollisionTask = false;
  12788. this._addUpdateMeshesList = {};
  12789. this._addUpdateGeometriesList = {};
  12790. this._toRemoveGeometryArray = [];
  12791. this._toRemoveMeshesArray = [];
  12792. }
  12793. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12794. if (!this._init)
  12795. return;
  12796. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12797. return;
  12798. position.divideToRef(collider.radius, this._scaledPosition);
  12799. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12800. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12801. var payload = {
  12802. collider: {
  12803. position: this._scaledPosition.asArray(),
  12804. velocity: this._scaledVelocity.asArray(),
  12805. radius: collider.radius.asArray()
  12806. },
  12807. collisionId: collisionIndex,
  12808. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12809. maximumRetry: maximumRetry
  12810. };
  12811. var message = {
  12812. payload: payload,
  12813. taskType: WorkerTaskType.COLLIDE
  12814. };
  12815. this._worker.postMessage(message);
  12816. };
  12817. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12818. this._scene = scene;
  12819. this._scene.registerAfterRender(this._afterRender);
  12820. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12821. this._worker = new Worker(workerUrl);
  12822. this._worker.onmessage = this._onMessageFromWorker;
  12823. var message = {
  12824. payload: {},
  12825. taskType: WorkerTaskType.INIT
  12826. };
  12827. this._worker.postMessage(message);
  12828. };
  12829. CollisionCoordinatorWorker.prototype.destroy = function () {
  12830. this._scene.unregisterAfterRender(this._afterRender);
  12831. this._worker.terminate();
  12832. };
  12833. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12834. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12835. this.onMeshUpdated(mesh);
  12836. };
  12837. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12838. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12839. };
  12840. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12841. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12842. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12843. this.onGeometryUpdated(geometry);
  12844. };
  12845. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12846. this._toRemoveGeometryArray.push(geometry.id);
  12847. };
  12848. return CollisionCoordinatorWorker;
  12849. }());
  12850. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12851. var submeshes = [];
  12852. if (mesh.subMeshes) {
  12853. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12854. return {
  12855. position: idx,
  12856. verticesStart: sm.verticesStart,
  12857. verticesCount: sm.verticesCount,
  12858. indexStart: sm.indexStart,
  12859. indexCount: sm.indexCount,
  12860. hasMaterial: !!sm.getMaterial(),
  12861. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12862. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12863. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12864. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12865. };
  12866. });
  12867. }
  12868. var geometryId = null;
  12869. if (mesh instanceof BABYLON.Mesh) {
  12870. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12871. }
  12872. else if (mesh instanceof BABYLON.InstancedMesh) {
  12873. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12874. }
  12875. return {
  12876. uniqueId: mesh.uniqueId,
  12877. id: mesh.id,
  12878. name: mesh.name,
  12879. geometryId: geometryId,
  12880. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12881. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12882. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12883. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12884. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12885. subMeshes: submeshes,
  12886. checkCollisions: mesh.checkCollisions
  12887. };
  12888. };
  12889. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12890. return {
  12891. id: geometry.id,
  12892. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12893. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12894. indices: new Int32Array(geometry.getIndices() || []),
  12895. };
  12896. };
  12897. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12898. var CollisionCoordinatorLegacy = (function () {
  12899. function CollisionCoordinatorLegacy() {
  12900. this._scaledPosition = BABYLON.Vector3.Zero();
  12901. this._scaledVelocity = BABYLON.Vector3.Zero();
  12902. this._finalPosition = BABYLON.Vector3.Zero();
  12903. }
  12904. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12905. position.divideToRef(collider.radius, this._scaledPosition);
  12906. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12907. collider.collidedMesh = null;
  12908. collider.retry = 0;
  12909. collider.initialVelocity = this._scaledVelocity;
  12910. collider.initialPosition = this._scaledPosition;
  12911. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12912. this._finalPosition.multiplyInPlace(collider.radius);
  12913. //run the callback
  12914. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12915. };
  12916. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12917. this._scene = scene;
  12918. };
  12919. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12920. //Legacy need no destruction method.
  12921. };
  12922. //No update in legacy mode
  12923. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12924. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12925. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12926. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12927. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12928. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12929. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12930. if (excludedMesh === void 0) { excludedMesh = null; }
  12931. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12932. if (collider.retry >= maximumRetry) {
  12933. finalPosition.copyFrom(position);
  12934. return;
  12935. }
  12936. collider._initialize(position, velocity, closeDistance);
  12937. // Check all meshes
  12938. for (var index = 0; index < this._scene.meshes.length; index++) {
  12939. var mesh = this._scene.meshes[index];
  12940. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12941. mesh._checkCollision(collider);
  12942. }
  12943. }
  12944. if (!collider.collisionFound) {
  12945. position.addToRef(velocity, finalPosition);
  12946. return;
  12947. }
  12948. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12949. collider._getResponse(position, velocity);
  12950. }
  12951. if (velocity.length() <= closeDistance) {
  12952. finalPosition.copyFrom(position);
  12953. return;
  12954. }
  12955. collider.retry++;
  12956. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12957. };
  12958. return CollisionCoordinatorLegacy;
  12959. }());
  12960. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12961. })(BABYLON || (BABYLON = {}));
  12962. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  12963. var BABYLON;
  12964. (function (BABYLON) {
  12965. var Camera = (function (_super) {
  12966. __extends(Camera, _super);
  12967. function Camera(name, position, scene) {
  12968. var _this = _super.call(this, name, scene) || this;
  12969. _this.upVector = BABYLON.Vector3.Up();
  12970. _this.orthoLeft = null;
  12971. _this.orthoRight = null;
  12972. _this.orthoBottom = null;
  12973. _this.orthoTop = null;
  12974. _this.fov = 0.8;
  12975. _this.minZ = 1.0;
  12976. _this.maxZ = 10000.0;
  12977. _this.inertia = 0.9;
  12978. _this.mode = Camera.PERSPECTIVE_CAMERA;
  12979. _this.isIntermediate = false;
  12980. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12981. _this.layerMask = 0x0FFFFFFF;
  12982. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12983. // Camera rig members
  12984. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  12985. _this._rigCameras = new Array();
  12986. // Cache
  12987. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  12988. _this._projectionMatrix = new BABYLON.Matrix();
  12989. _this._doNotComputeProjectionMatrix = false;
  12990. _this._postProcesses = new Array();
  12991. _this._transformMatrix = BABYLON.Matrix.Zero();
  12992. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  12993. _this._activeMeshes = new BABYLON.SmartArray(256);
  12994. _this._globalPosition = BABYLON.Vector3.Zero();
  12995. _this._refreshFrustumPlanes = true;
  12996. scene.addCamera(_this);
  12997. if (!scene.activeCamera) {
  12998. scene.activeCamera = _this;
  12999. }
  13000. _this.position = position;
  13001. return _this;
  13002. }
  13003. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13004. get: function () {
  13005. return Camera._PERSPECTIVE_CAMERA;
  13006. },
  13007. enumerable: true,
  13008. configurable: true
  13009. });
  13010. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13011. get: function () {
  13012. return Camera._ORTHOGRAPHIC_CAMERA;
  13013. },
  13014. enumerable: true,
  13015. configurable: true
  13016. });
  13017. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13018. get: function () {
  13019. return Camera._FOVMODE_VERTICAL_FIXED;
  13020. },
  13021. enumerable: true,
  13022. configurable: true
  13023. });
  13024. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13025. get: function () {
  13026. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13027. },
  13028. enumerable: true,
  13029. configurable: true
  13030. });
  13031. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13032. get: function () {
  13033. return Camera._RIG_MODE_NONE;
  13034. },
  13035. enumerable: true,
  13036. configurable: true
  13037. });
  13038. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13039. get: function () {
  13040. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13041. },
  13042. enumerable: true,
  13043. configurable: true
  13044. });
  13045. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13046. get: function () {
  13047. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13048. },
  13049. enumerable: true,
  13050. configurable: true
  13051. });
  13052. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13053. get: function () {
  13054. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13055. },
  13056. enumerable: true,
  13057. configurable: true
  13058. });
  13059. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13060. get: function () {
  13061. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13062. },
  13063. enumerable: true,
  13064. configurable: true
  13065. });
  13066. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13067. get: function () {
  13068. return Camera._RIG_MODE_VR;
  13069. },
  13070. enumerable: true,
  13071. configurable: true
  13072. });
  13073. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13074. get: function () {
  13075. return Camera._RIG_MODE_WEBVR;
  13076. },
  13077. enumerable: true,
  13078. configurable: true
  13079. });
  13080. Camera.prototype.getClassName = function () {
  13081. return "Camera";
  13082. };
  13083. /**
  13084. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13085. */
  13086. Camera.prototype.toString = function (fullDetails) {
  13087. var ret = "Name: " + this.name;
  13088. ret += ", type: " + this.getClassName();
  13089. if (this.animations) {
  13090. for (var i = 0; i < this.animations.length; i++) {
  13091. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13092. }
  13093. }
  13094. if (fullDetails) {
  13095. }
  13096. return ret;
  13097. };
  13098. Object.defineProperty(Camera.prototype, "globalPosition", {
  13099. get: function () {
  13100. return this._globalPosition;
  13101. },
  13102. enumerable: true,
  13103. configurable: true
  13104. });
  13105. Camera.prototype.getActiveMeshes = function () {
  13106. return this._activeMeshes;
  13107. };
  13108. Camera.prototype.isActiveMesh = function (mesh) {
  13109. return (this._activeMeshes.indexOf(mesh) !== -1);
  13110. };
  13111. //Cache
  13112. Camera.prototype._initCache = function () {
  13113. _super.prototype._initCache.call(this);
  13114. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13115. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13116. this._cache.mode = undefined;
  13117. this._cache.minZ = undefined;
  13118. this._cache.maxZ = undefined;
  13119. this._cache.fov = undefined;
  13120. this._cache.fovMode = undefined;
  13121. this._cache.aspectRatio = undefined;
  13122. this._cache.orthoLeft = undefined;
  13123. this._cache.orthoRight = undefined;
  13124. this._cache.orthoBottom = undefined;
  13125. this._cache.orthoTop = undefined;
  13126. this._cache.renderWidth = undefined;
  13127. this._cache.renderHeight = undefined;
  13128. };
  13129. Camera.prototype._updateCache = function (ignoreParentClass) {
  13130. if (!ignoreParentClass) {
  13131. _super.prototype._updateCache.call(this);
  13132. }
  13133. var engine = this.getEngine();
  13134. this._cache.position.copyFrom(this.position);
  13135. this._cache.upVector.copyFrom(this.upVector);
  13136. this._cache.mode = this.mode;
  13137. this._cache.minZ = this.minZ;
  13138. this._cache.maxZ = this.maxZ;
  13139. this._cache.fov = this.fov;
  13140. this._cache.fovMode = this.fovMode;
  13141. this._cache.aspectRatio = engine.getAspectRatio(this);
  13142. this._cache.orthoLeft = this.orthoLeft;
  13143. this._cache.orthoRight = this.orthoRight;
  13144. this._cache.orthoBottom = this.orthoBottom;
  13145. this._cache.orthoTop = this.orthoTop;
  13146. this._cache.renderWidth = engine.getRenderWidth();
  13147. this._cache.renderHeight = engine.getRenderHeight();
  13148. };
  13149. Camera.prototype._updateFromScene = function () {
  13150. this.updateCache();
  13151. this.update();
  13152. };
  13153. // Synchronized
  13154. Camera.prototype._isSynchronized = function () {
  13155. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13156. };
  13157. Camera.prototype._isSynchronizedViewMatrix = function () {
  13158. if (!_super.prototype._isSynchronized.call(this))
  13159. return false;
  13160. return this._cache.position.equals(this.position)
  13161. && this._cache.upVector.equals(this.upVector)
  13162. && this.isSynchronizedWithParent();
  13163. };
  13164. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13165. var check = this._cache.mode === this.mode
  13166. && this._cache.minZ === this.minZ
  13167. && this._cache.maxZ === this.maxZ;
  13168. if (!check) {
  13169. return false;
  13170. }
  13171. var engine = this.getEngine();
  13172. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13173. check = this._cache.fov === this.fov
  13174. && this._cache.fovMode === this.fovMode
  13175. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13176. }
  13177. else {
  13178. check = this._cache.orthoLeft === this.orthoLeft
  13179. && this._cache.orthoRight === this.orthoRight
  13180. && this._cache.orthoBottom === this.orthoBottom
  13181. && this._cache.orthoTop === this.orthoTop
  13182. && this._cache.renderWidth === engine.getRenderWidth()
  13183. && this._cache.renderHeight === engine.getRenderHeight();
  13184. }
  13185. return check;
  13186. };
  13187. // Controls
  13188. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13189. };
  13190. Camera.prototype.detachControl = function (element) {
  13191. };
  13192. Camera.prototype.update = function () {
  13193. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13194. this._updateRigCameras();
  13195. }
  13196. this._checkInputs();
  13197. };
  13198. Camera.prototype._checkInputs = function () {
  13199. };
  13200. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13201. // invalidate framebuffer
  13202. if (this._postProcesses.length > 0) {
  13203. this._postProcesses[0].markTextureDirty();
  13204. }
  13205. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13206. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13207. var cam = this._rigCameras[i];
  13208. var rigPostProcess = cam._rigPostProcess;
  13209. // for VR rig, there does not have to be a post process
  13210. if (rigPostProcess) {
  13211. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13212. if (isPass) {
  13213. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13214. cam.isIntermediate = this._postProcesses.length === 0;
  13215. }
  13216. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13217. rigPostProcess.markTextureDirty();
  13218. }
  13219. else {
  13220. cam._postProcesses = this._postProcesses.slice(0);
  13221. }
  13222. }
  13223. };
  13224. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13225. if (insertAt === void 0) { insertAt = null; }
  13226. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13227. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13228. return 0;
  13229. }
  13230. if (insertAt == null || insertAt < 0) {
  13231. this._postProcesses.push(postProcess);
  13232. }
  13233. else {
  13234. this._postProcesses.splice(insertAt, 0, postProcess);
  13235. }
  13236. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13237. return this._postProcesses.indexOf(postProcess);
  13238. };
  13239. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13240. if (atIndices === void 0) { atIndices = null; }
  13241. var result = [];
  13242. var i;
  13243. var index;
  13244. if (!atIndices) {
  13245. var idx = this._postProcesses.indexOf(postProcess);
  13246. if (idx !== -1) {
  13247. this._postProcesses.splice(idx, 1);
  13248. }
  13249. }
  13250. else {
  13251. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13252. // iterate descending, so can just splice as we go
  13253. for (i = atIndices.length - 1; i >= 0; i--) {
  13254. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13255. result.push(i);
  13256. continue;
  13257. }
  13258. this._postProcesses.splice(index, 1);
  13259. }
  13260. }
  13261. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13262. return result;
  13263. };
  13264. Camera.prototype.getWorldMatrix = function () {
  13265. if (!this._worldMatrix) {
  13266. this._worldMatrix = BABYLON.Matrix.Identity();
  13267. }
  13268. var viewMatrix = this.getViewMatrix();
  13269. viewMatrix.invertToRef(this._worldMatrix);
  13270. return this._worldMatrix;
  13271. };
  13272. Camera.prototype._getViewMatrix = function () {
  13273. return BABYLON.Matrix.Identity();
  13274. };
  13275. Camera.prototype.getViewMatrix = function (force) {
  13276. this._computedViewMatrix = this._computeViewMatrix(force);
  13277. if (!force && this._isSynchronizedViewMatrix()) {
  13278. return this._computedViewMatrix;
  13279. }
  13280. this._refreshFrustumPlanes = true;
  13281. if (!this.parent || !this.parent.getWorldMatrix) {
  13282. this._globalPosition.copyFrom(this.position);
  13283. }
  13284. else {
  13285. if (!this._worldMatrix) {
  13286. this._worldMatrix = BABYLON.Matrix.Identity();
  13287. }
  13288. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13289. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13290. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13291. this._computedViewMatrix.invert();
  13292. this._markSyncedWithParent();
  13293. }
  13294. this._currentRenderId = this.getScene().getRenderId();
  13295. return this._computedViewMatrix;
  13296. };
  13297. Camera.prototype._computeViewMatrix = function (force) {
  13298. if (!force && this._isSynchronizedViewMatrix()) {
  13299. return this._computedViewMatrix;
  13300. }
  13301. this._computedViewMatrix = this._getViewMatrix();
  13302. this._currentRenderId = this.getScene().getRenderId();
  13303. return this._computedViewMatrix;
  13304. };
  13305. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13306. this._doNotComputeProjectionMatrix = true;
  13307. if (projection !== undefined) {
  13308. this._projectionMatrix = projection;
  13309. }
  13310. };
  13311. ;
  13312. Camera.prototype.unfreezeProjectionMatrix = function () {
  13313. this._doNotComputeProjectionMatrix = false;
  13314. };
  13315. ;
  13316. Camera.prototype.getProjectionMatrix = function (force) {
  13317. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13318. return this._projectionMatrix;
  13319. }
  13320. this._refreshFrustumPlanes = true;
  13321. var engine = this.getEngine();
  13322. var scene = this.getScene();
  13323. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13324. if (this.minZ <= 0) {
  13325. this.minZ = 0.1;
  13326. }
  13327. if (scene.useRightHandedSystem) {
  13328. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13329. }
  13330. else {
  13331. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13332. }
  13333. return this._projectionMatrix;
  13334. }
  13335. var halfWidth = engine.getRenderWidth() / 2.0;
  13336. var halfHeight = engine.getRenderHeight() / 2.0;
  13337. if (scene.useRightHandedSystem) {
  13338. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13339. }
  13340. else {
  13341. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13342. }
  13343. return this._projectionMatrix;
  13344. };
  13345. Camera.prototype.getTranformationMatrix = function () {
  13346. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13347. return this._transformMatrix;
  13348. };
  13349. Camera.prototype.updateFrustumPlanes = function () {
  13350. if (!this._refreshFrustumPlanes) {
  13351. return;
  13352. }
  13353. this.getTranformationMatrix();
  13354. if (!this._frustumPlanes) {
  13355. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13356. }
  13357. else {
  13358. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13359. }
  13360. this._refreshFrustumPlanes = false;
  13361. };
  13362. Camera.prototype.isInFrustum = function (target) {
  13363. this.updateFrustumPlanes();
  13364. return target.isInFrustum(this._frustumPlanes);
  13365. };
  13366. Camera.prototype.isCompletelyInFrustum = function (target) {
  13367. this.updateFrustumPlanes();
  13368. return target.isCompletelyInFrustum(this._frustumPlanes);
  13369. };
  13370. Camera.prototype.dispose = function () {
  13371. // Animations
  13372. this.getScene().stopAnimation(this);
  13373. // Remove from scene
  13374. this.getScene().removeCamera(this);
  13375. while (this._rigCameras.length > 0) {
  13376. this._rigCameras.pop().dispose();
  13377. }
  13378. // Postprocesses
  13379. for (var i = 0; i < this._postProcesses.length; ++i) {
  13380. this._postProcesses[i].dispose(this);
  13381. }
  13382. _super.prototype.dispose.call(this);
  13383. };
  13384. // ---- Camera rigs section ----
  13385. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13386. while (this._rigCameras.length > 0) {
  13387. this._rigCameras.pop().dispose();
  13388. }
  13389. this.cameraRigMode = mode;
  13390. this._cameraRigParams = {};
  13391. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13392. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13393. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13394. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13395. // create the rig cameras, unless none
  13396. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13397. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13398. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13399. }
  13400. switch (this.cameraRigMode) {
  13401. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13402. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13403. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13404. break;
  13405. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13406. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13407. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13408. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13409. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13410. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13411. break;
  13412. case Camera.RIG_MODE_VR:
  13413. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13414. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13415. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13416. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13417. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13418. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13419. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13420. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13421. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13422. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13423. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13424. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13425. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13426. if (metrics.compensateDistortion) {
  13427. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13428. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13429. }
  13430. break;
  13431. case Camera.RIG_MODE_WEBVR:
  13432. if (rigParams.vrDisplay) {
  13433. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13434. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13435. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13436. this._rigCameras[0].setCameraRigParameter("left", true);
  13437. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13438. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13439. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13440. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13441. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13442. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13443. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13444. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13445. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13446. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13447. }
  13448. break;
  13449. }
  13450. this._cascadePostProcessesToRigCams();
  13451. this.
  13452. update();
  13453. };
  13454. Camera.prototype._getVRProjectionMatrix = function () {
  13455. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13456. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13457. return this._projectionMatrix;
  13458. };
  13459. Camera.prototype._getWebVRProjectionMatrix = function () {
  13460. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13461. //babylon compatible matrix
  13462. [8, 9, 10, 11].forEach(function (num) {
  13463. projectionArray[num] *= -1;
  13464. });
  13465. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13466. return this._projectionMatrix;
  13467. };
  13468. //Can be used, but we'll use the free camera's view matrix calculation
  13469. Camera.prototype._getWebVRViewMatrix = function () {
  13470. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13471. //babylon compatible matrix
  13472. [8, 9, 10, 11].forEach(function (num) {
  13473. projectionArray[num] *= -1;
  13474. });
  13475. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13476. return this._webvrViewMatrix;
  13477. };
  13478. Camera.prototype.setCameraRigParameter = function (name, value) {
  13479. if (!this._cameraRigParams) {
  13480. this._cameraRigParams = {};
  13481. }
  13482. this._cameraRigParams[name] = value;
  13483. //provisionnally:
  13484. if (name === "interaxialDistance") {
  13485. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13486. }
  13487. };
  13488. /**
  13489. * needs to be overridden by children so sub has required properties to be copied
  13490. */
  13491. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13492. return null;
  13493. };
  13494. /**
  13495. * May need to be overridden by children
  13496. */
  13497. Camera.prototype._updateRigCameras = function () {
  13498. for (var i = 0; i < this._rigCameras.length; i++) {
  13499. this._rigCameras[i].minZ = this.minZ;
  13500. this._rigCameras[i].maxZ = this.maxZ;
  13501. this._rigCameras[i].fov = this.fov;
  13502. }
  13503. // only update viewport when ANAGLYPH
  13504. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13505. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13506. }
  13507. };
  13508. Camera.prototype._setupInputs = function () {
  13509. };
  13510. Camera.prototype.serialize = function () {
  13511. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13512. // Type
  13513. serializationObject.type = this.getClassName();
  13514. // Parent
  13515. if (this.parent) {
  13516. serializationObject.parentId = this.parent.id;
  13517. }
  13518. if (this.inputs) {
  13519. this.inputs.serialize(serializationObject);
  13520. }
  13521. // Animations
  13522. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13523. serializationObject.ranges = this.serializeAnimationRanges();
  13524. return serializationObject;
  13525. };
  13526. Camera.prototype.clone = function (name) {
  13527. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13528. };
  13529. Camera.prototype.getDirection = function (localAxis) {
  13530. var result = BABYLON.Vector3.Zero();
  13531. this.getDirectionToRef(localAxis, result);
  13532. return result;
  13533. };
  13534. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13535. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13536. };
  13537. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13538. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13539. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13540. switch (type) {
  13541. case "ArcRotateCamera":
  13542. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13543. case "DeviceOrientationCamera":
  13544. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13545. case "FollowCamera":
  13546. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13547. case "ArcFollowCamera":
  13548. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13549. case "GamepadCamera":
  13550. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13551. case "TouchCamera":
  13552. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13553. case "VirtualJoysticksCamera":
  13554. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13555. case "WebVRFreeCamera":
  13556. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13557. case "VRDeviceOrientationFreeCamera":
  13558. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13559. case "AnaglyphArcRotateCamera":
  13560. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13561. case "AnaglyphFreeCamera":
  13562. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13563. case "AnaglyphGamepadCamera":
  13564. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13565. case "AnaglyphUniversalCamera":
  13566. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13567. case "StereoscopicArcRotateCamera":
  13568. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13569. case "StereoscopicFreeCamera":
  13570. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13571. case "StereoscopicGamepadCamera":
  13572. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13573. case "StereoscopicUniversalCamera":
  13574. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13575. case "FreeCamera":
  13576. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13577. default:
  13578. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13579. }
  13580. };
  13581. Camera.Parse = function (parsedCamera, scene) {
  13582. var type = parsedCamera.type;
  13583. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13584. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13585. // Parent
  13586. if (parsedCamera.parentId) {
  13587. camera._waitingParentId = parsedCamera.parentId;
  13588. }
  13589. //If camera has an input manager, let it parse inputs settings
  13590. if (camera.inputs) {
  13591. camera.inputs.parse(parsedCamera);
  13592. camera._setupInputs();
  13593. }
  13594. // Target
  13595. if (parsedCamera.target) {
  13596. if (camera.setTarget) {
  13597. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13598. }
  13599. }
  13600. // Apply 3d rig, when found
  13601. if (parsedCamera.cameraRigMode) {
  13602. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13603. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13604. }
  13605. // Animations
  13606. if (parsedCamera.animations) {
  13607. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13608. var parsedAnimation = parsedCamera.animations[animationIndex];
  13609. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13610. }
  13611. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13612. }
  13613. if (parsedCamera.autoAnimate) {
  13614. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13615. }
  13616. return camera;
  13617. };
  13618. return Camera;
  13619. }(BABYLON.Node));
  13620. // Statics
  13621. Camera._PERSPECTIVE_CAMERA = 0;
  13622. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13623. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13624. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13625. Camera._RIG_MODE_NONE = 0;
  13626. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13627. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13628. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13629. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13630. Camera._RIG_MODE_VR = 20;
  13631. Camera._RIG_MODE_WEBVR = 21;
  13632. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13633. __decorate([
  13634. BABYLON.serializeAsVector3()
  13635. ], Camera.prototype, "position", void 0);
  13636. __decorate([
  13637. BABYLON.serializeAsVector3()
  13638. ], Camera.prototype, "upVector", void 0);
  13639. __decorate([
  13640. BABYLON.serialize()
  13641. ], Camera.prototype, "orthoLeft", void 0);
  13642. __decorate([
  13643. BABYLON.serialize()
  13644. ], Camera.prototype, "orthoRight", void 0);
  13645. __decorate([
  13646. BABYLON.serialize()
  13647. ], Camera.prototype, "orthoBottom", void 0);
  13648. __decorate([
  13649. BABYLON.serialize()
  13650. ], Camera.prototype, "orthoTop", void 0);
  13651. __decorate([
  13652. BABYLON.serialize()
  13653. ], Camera.prototype, "fov", void 0);
  13654. __decorate([
  13655. BABYLON.serialize()
  13656. ], Camera.prototype, "minZ", void 0);
  13657. __decorate([
  13658. BABYLON.serialize()
  13659. ], Camera.prototype, "maxZ", void 0);
  13660. __decorate([
  13661. BABYLON.serialize()
  13662. ], Camera.prototype, "inertia", void 0);
  13663. __decorate([
  13664. BABYLON.serialize()
  13665. ], Camera.prototype, "mode", void 0);
  13666. __decorate([
  13667. BABYLON.serialize()
  13668. ], Camera.prototype, "layerMask", void 0);
  13669. __decorate([
  13670. BABYLON.serialize()
  13671. ], Camera.prototype, "fovMode", void 0);
  13672. __decorate([
  13673. BABYLON.serialize()
  13674. ], Camera.prototype, "cameraRigMode", void 0);
  13675. __decorate([
  13676. BABYLON.serialize()
  13677. ], Camera.prototype, "interaxialDistance", void 0);
  13678. __decorate([
  13679. BABYLON.serialize()
  13680. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13681. BABYLON.Camera = Camera;
  13682. })(BABYLON || (BABYLON = {}));
  13683. //# sourceMappingURL=babylon.camera.js.map
  13684. var BABYLON;
  13685. (function (BABYLON) {
  13686. BABYLON.CameraInputTypes = {};
  13687. var CameraInputsManager = (function () {
  13688. function CameraInputsManager(camera) {
  13689. this.attached = {};
  13690. this.camera = camera;
  13691. this.checkInputs = function () { };
  13692. }
  13693. CameraInputsManager.prototype.add = function (input) {
  13694. var type = input.getSimpleName();
  13695. if (this.attached[type]) {
  13696. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13697. return;
  13698. }
  13699. this.attached[type] = input;
  13700. input.camera = this.camera;
  13701. //for checkInputs, we are dynamically creating a function
  13702. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13703. if (input.checkInputs) {
  13704. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13705. }
  13706. if (this.attachedElement) {
  13707. input.attachControl(this.attachedElement);
  13708. }
  13709. };
  13710. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13711. for (var cam in this.attached) {
  13712. var input = this.attached[cam];
  13713. if (input === inputToRemove) {
  13714. input.detachControl(this.attachedElement);
  13715. delete this.attached[cam];
  13716. this.rebuildInputCheck();
  13717. }
  13718. }
  13719. };
  13720. CameraInputsManager.prototype.removeByType = function (inputType) {
  13721. for (var cam in this.attached) {
  13722. var input = this.attached[cam];
  13723. if (input.getTypeName() === inputType) {
  13724. input.detachControl(this.attachedElement);
  13725. delete this.attached[cam];
  13726. this.rebuildInputCheck();
  13727. }
  13728. }
  13729. };
  13730. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13731. var current = this.checkInputs;
  13732. return function () {
  13733. current();
  13734. fn();
  13735. };
  13736. };
  13737. CameraInputsManager.prototype.attachInput = function (input) {
  13738. input.attachControl(this.attachedElement, this.noPreventDefault);
  13739. };
  13740. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13741. if (this.attachedElement) {
  13742. return;
  13743. }
  13744. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13745. this.attachedElement = element;
  13746. this.noPreventDefault = noPreventDefault;
  13747. for (var cam in this.attached) {
  13748. var input = this.attached[cam];
  13749. this.attached[cam].attachControl(element, noPreventDefault);
  13750. }
  13751. };
  13752. CameraInputsManager.prototype.detachElement = function (element) {
  13753. if (this.attachedElement !== element) {
  13754. return;
  13755. }
  13756. for (var cam in this.attached) {
  13757. var input = this.attached[cam];
  13758. this.attached[cam].detachControl(element);
  13759. }
  13760. this.attachedElement = null;
  13761. };
  13762. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13763. this.checkInputs = function () { };
  13764. for (var cam in this.attached) {
  13765. var input = this.attached[cam];
  13766. if (input.checkInputs) {
  13767. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13768. }
  13769. }
  13770. };
  13771. CameraInputsManager.prototype.clear = function () {
  13772. if (this.attachedElement) {
  13773. this.detachElement(this.attachedElement);
  13774. }
  13775. this.attached = {};
  13776. this.attachedElement = null;
  13777. this.checkInputs = function () { };
  13778. };
  13779. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13780. var inputs = {};
  13781. for (var cam in this.attached) {
  13782. var input = this.attached[cam];
  13783. var res = BABYLON.SerializationHelper.Serialize(input);
  13784. inputs[input.getTypeName()] = res;
  13785. }
  13786. serializedCamera.inputsmgr = inputs;
  13787. };
  13788. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13789. var parsedInputs = parsedCamera.inputsmgr;
  13790. if (parsedInputs) {
  13791. this.clear();
  13792. for (var n in parsedInputs) {
  13793. var construct = BABYLON.CameraInputTypes[n];
  13794. if (construct) {
  13795. var parsedinput = parsedInputs[n];
  13796. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13797. this.add(input);
  13798. }
  13799. }
  13800. }
  13801. else {
  13802. //2016-03-08 this part is for managing backward compatibility
  13803. for (var n in this.attached) {
  13804. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13805. if (construct) {
  13806. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13807. this.remove(this.attached[n]);
  13808. this.add(input);
  13809. }
  13810. }
  13811. }
  13812. };
  13813. return CameraInputsManager;
  13814. }());
  13815. BABYLON.CameraInputsManager = CameraInputsManager;
  13816. })(BABYLON || (BABYLON = {}));
  13817. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  13818. var BABYLON;
  13819. (function (BABYLON) {
  13820. var FreeCameraMouseInput = (function () {
  13821. function FreeCameraMouseInput(touchEnabled) {
  13822. if (touchEnabled === void 0) { touchEnabled = true; }
  13823. this.touchEnabled = touchEnabled;
  13824. this.buttons = [0, 1, 2];
  13825. this.angularSensibility = 2000.0;
  13826. }
  13827. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13828. var _this = this;
  13829. var engine = this.camera.getEngine();
  13830. if (!this._pointerInput) {
  13831. this._pointerInput = function (p, s) {
  13832. var evt = p.event;
  13833. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13834. return;
  13835. }
  13836. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  13837. return;
  13838. }
  13839. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13840. try {
  13841. evt.srcElement.setPointerCapture(evt.pointerId);
  13842. }
  13843. catch (e) {
  13844. }
  13845. _this.previousPosition = {
  13846. x: evt.clientX,
  13847. y: evt.clientY
  13848. };
  13849. if (!noPreventDefault) {
  13850. evt.preventDefault();
  13851. element.focus();
  13852. }
  13853. }
  13854. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13855. try {
  13856. evt.srcElement.releasePointerCapture(evt.pointerId);
  13857. }
  13858. catch (e) {
  13859. }
  13860. _this.previousPosition = null;
  13861. if (!noPreventDefault) {
  13862. evt.preventDefault();
  13863. }
  13864. }
  13865. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13866. if (!_this.previousPosition || engine.isPointerLock) {
  13867. return;
  13868. }
  13869. var offsetX = evt.clientX - _this.previousPosition.x;
  13870. var offsetY = evt.clientY - _this.previousPosition.y;
  13871. if (_this.camera.getScene().useRightHandedSystem) {
  13872. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13873. }
  13874. else {
  13875. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13876. }
  13877. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13878. _this.previousPosition = {
  13879. x: evt.clientX,
  13880. y: evt.clientY
  13881. };
  13882. if (!noPreventDefault) {
  13883. evt.preventDefault();
  13884. }
  13885. }
  13886. };
  13887. }
  13888. this._onMouseMove = function (evt) {
  13889. if (!engine.isPointerLock) {
  13890. return;
  13891. }
  13892. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13893. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13894. if (_this.camera.getScene().useRightHandedSystem) {
  13895. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13896. }
  13897. else {
  13898. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13899. }
  13900. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13901. _this.previousPosition = null;
  13902. if (!noPreventDefault) {
  13903. evt.preventDefault();
  13904. }
  13905. };
  13906. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13907. element.addEventListener("mousemove", this._onMouseMove, false);
  13908. };
  13909. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13910. if (this._observer && element) {
  13911. this.camera.getScene().onPointerObservable.remove(this._observer);
  13912. element.removeEventListener("mousemove", this._onMouseMove);
  13913. this._observer = null;
  13914. this._onMouseMove = null;
  13915. this.previousPosition = null;
  13916. }
  13917. };
  13918. FreeCameraMouseInput.prototype.getTypeName = function () {
  13919. return "FreeCameraMouseInput";
  13920. };
  13921. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13922. return "mouse";
  13923. };
  13924. return FreeCameraMouseInput;
  13925. }());
  13926. __decorate([
  13927. BABYLON.serialize()
  13928. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  13929. __decorate([
  13930. BABYLON.serialize()
  13931. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13932. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13933. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13934. })(BABYLON || (BABYLON = {}));
  13935. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  13936. var BABYLON;
  13937. (function (BABYLON) {
  13938. var FreeCameraKeyboardMoveInput = (function () {
  13939. function FreeCameraKeyboardMoveInput() {
  13940. this._keys = [];
  13941. this.keysUp = [38];
  13942. this.keysDown = [40];
  13943. this.keysLeft = [37];
  13944. this.keysRight = [39];
  13945. }
  13946. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13947. var _this = this;
  13948. if (!this._onKeyDown) {
  13949. element.tabIndex = 1;
  13950. this._onKeyDown = function (evt) {
  13951. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13952. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13953. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13954. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13955. var index = _this._keys.indexOf(evt.keyCode);
  13956. if (index === -1) {
  13957. _this._keys.push(evt.keyCode);
  13958. }
  13959. if (!noPreventDefault) {
  13960. evt.preventDefault();
  13961. }
  13962. }
  13963. };
  13964. this._onKeyUp = function (evt) {
  13965. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13966. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13967. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13968. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13969. var index = _this._keys.indexOf(evt.keyCode);
  13970. if (index >= 0) {
  13971. _this._keys.splice(index, 1);
  13972. }
  13973. if (!noPreventDefault) {
  13974. evt.preventDefault();
  13975. }
  13976. }
  13977. };
  13978. element.addEventListener("keydown", this._onKeyDown, false);
  13979. element.addEventListener("keyup", this._onKeyUp, false);
  13980. BABYLON.Tools.RegisterTopRootEvents([
  13981. { name: "blur", handler: this._onLostFocus }
  13982. ]);
  13983. }
  13984. };
  13985. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13986. if (this._onKeyDown) {
  13987. element.removeEventListener("keydown", this._onKeyDown);
  13988. element.removeEventListener("keyup", this._onKeyUp);
  13989. BABYLON.Tools.UnregisterTopRootEvents([
  13990. { name: "blur", handler: this._onLostFocus }
  13991. ]);
  13992. this._keys = [];
  13993. this._onKeyDown = null;
  13994. this._onKeyUp = null;
  13995. }
  13996. };
  13997. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13998. if (this._onKeyDown) {
  13999. var camera = this.camera;
  14000. // Keyboard
  14001. for (var index = 0; index < this._keys.length; index++) {
  14002. var keyCode = this._keys[index];
  14003. var speed = camera._computeLocalCameraSpeed();
  14004. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14005. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14006. }
  14007. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14008. camera._localDirection.copyFromFloats(0, 0, speed);
  14009. }
  14010. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14011. camera._localDirection.copyFromFloats(speed, 0, 0);
  14012. }
  14013. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14014. camera._localDirection.copyFromFloats(0, 0, -speed);
  14015. }
  14016. if (camera.getScene().useRightHandedSystem) {
  14017. camera._localDirection.z *= -1;
  14018. }
  14019. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14020. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14021. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14022. }
  14023. }
  14024. };
  14025. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14026. return "FreeCameraKeyboardMoveInput";
  14027. };
  14028. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14029. this._keys = [];
  14030. };
  14031. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14032. return "keyboard";
  14033. };
  14034. return FreeCameraKeyboardMoveInput;
  14035. }());
  14036. __decorate([
  14037. BABYLON.serialize()
  14038. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14039. __decorate([
  14040. BABYLON.serialize()
  14041. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14042. __decorate([
  14043. BABYLON.serialize()
  14044. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14045. __decorate([
  14046. BABYLON.serialize()
  14047. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14048. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14049. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14050. })(BABYLON || (BABYLON = {}));
  14051. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14052. var BABYLON;
  14053. (function (BABYLON) {
  14054. var FreeCameraTouchInput = (function () {
  14055. function FreeCameraTouchInput() {
  14056. this._offsetX = null;
  14057. this._offsetY = null;
  14058. this._pointerCount = 0;
  14059. this._pointerPressed = [];
  14060. this.touchAngularSensibility = 200000.0;
  14061. this.touchMoveSensibility = 250.0;
  14062. }
  14063. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14064. var _this = this;
  14065. var previousPosition;
  14066. if (this._pointerInput === undefined) {
  14067. this._onLostFocus = function (evt) {
  14068. _this._offsetX = null;
  14069. _this._offsetY = null;
  14070. };
  14071. this._pointerInput = function (p, s) {
  14072. var evt = p.event;
  14073. if (evt.pointerType === "mouse") {
  14074. return;
  14075. }
  14076. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14077. if (!noPreventDefault) {
  14078. evt.preventDefault();
  14079. }
  14080. _this._pointerPressed.push(evt.pointerId);
  14081. if (_this._pointerPressed.length !== 1) {
  14082. return;
  14083. }
  14084. previousPosition = {
  14085. x: evt.clientX,
  14086. y: evt.clientY
  14087. };
  14088. }
  14089. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14090. if (!noPreventDefault) {
  14091. evt.preventDefault();
  14092. }
  14093. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14094. if (index === -1) {
  14095. return;
  14096. }
  14097. _this._pointerPressed.splice(index, 1);
  14098. if (index != 0) {
  14099. return;
  14100. }
  14101. previousPosition = null;
  14102. _this._offsetX = null;
  14103. _this._offsetY = null;
  14104. }
  14105. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14106. if (!noPreventDefault) {
  14107. evt.preventDefault();
  14108. }
  14109. if (!previousPosition) {
  14110. return;
  14111. }
  14112. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14113. if (index != 0) {
  14114. return;
  14115. }
  14116. _this._offsetX = evt.clientX - previousPosition.x;
  14117. _this._offsetY = -(evt.clientY - previousPosition.y);
  14118. }
  14119. };
  14120. }
  14121. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14122. element.addEventListener("blur", this._onLostFocus);
  14123. };
  14124. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14125. if (this._pointerInput && element) {
  14126. this.camera.getScene().onPointerObservable.remove(this._observer);
  14127. this._observer = null;
  14128. element.removeEventListener("blur", this._onLostFocus);
  14129. this._onLostFocus = null;
  14130. this._pointerPressed = [];
  14131. this._offsetX = null;
  14132. this._offsetY = null;
  14133. this._pointerCount = 0;
  14134. }
  14135. };
  14136. FreeCameraTouchInput.prototype.checkInputs = function () {
  14137. if (this._offsetX) {
  14138. var camera = this.camera;
  14139. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14140. if (this._pointerPressed.length > 1) {
  14141. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14142. }
  14143. else {
  14144. var speed = camera._computeLocalCameraSpeed();
  14145. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14146. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14147. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14148. }
  14149. }
  14150. };
  14151. FreeCameraTouchInput.prototype.getTypeName = function () {
  14152. return "FreeCameraTouchInput";
  14153. };
  14154. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14155. return "touch";
  14156. };
  14157. return FreeCameraTouchInput;
  14158. }());
  14159. __decorate([
  14160. BABYLON.serialize()
  14161. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14162. __decorate([
  14163. BABYLON.serialize()
  14164. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14165. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14166. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14167. })(BABYLON || (BABYLON = {}));
  14168. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14169. var BABYLON;
  14170. (function (BABYLON) {
  14171. var FreeCameraDeviceOrientationInput = (function () {
  14172. function FreeCameraDeviceOrientationInput() {
  14173. var _this = this;
  14174. this._screenOrientationAngle = 0;
  14175. this._screenQuaternion = new BABYLON.Quaternion();
  14176. this._alpha = 0;
  14177. this._beta = 0;
  14178. this._gamma = 0;
  14179. this._orientationChanged = function () {
  14180. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14181. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14182. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14183. };
  14184. this._deviceOrientation = function (evt) {
  14185. _this._alpha = evt.alpha;
  14186. _this._beta = evt.beta;
  14187. _this._gamma = evt.gamma;
  14188. };
  14189. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14190. this._orientationChanged();
  14191. }
  14192. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14193. get: function () {
  14194. return this._camera;
  14195. },
  14196. set: function (camera) {
  14197. this._camera = camera;
  14198. if (!this._camera.rotationQuaternion)
  14199. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14200. },
  14201. enumerable: true,
  14202. configurable: true
  14203. });
  14204. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14205. window.addEventListener("orientationchange", this._orientationChanged);
  14206. window.addEventListener("deviceorientation", this._deviceOrientation);
  14207. //In certain cases, the attach control is called AFTER orientation was changed,
  14208. //So this is needed.
  14209. this._orientationChanged();
  14210. };
  14211. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14212. window.removeEventListener("orientationchange", this._orientationChanged);
  14213. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14214. };
  14215. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14216. //if no device orientation provided, don't update the rotation.
  14217. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14218. if (!this._alpha)
  14219. return;
  14220. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14221. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14222. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14223. //Mirror on XY Plane
  14224. this._camera.rotationQuaternion.z *= -1;
  14225. this._camera.rotationQuaternion.w *= -1;
  14226. };
  14227. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14228. return "FreeCameraDeviceOrientationInput";
  14229. };
  14230. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14231. return "deviceOrientation";
  14232. };
  14233. return FreeCameraDeviceOrientationInput;
  14234. }());
  14235. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14236. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14237. })(BABYLON || (BABYLON = {}));
  14238. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14239. var BABYLON;
  14240. (function (BABYLON) {
  14241. var FreeCameraGamepadInput = (function () {
  14242. function FreeCameraGamepadInput() {
  14243. this.gamepadAngularSensibility = 200;
  14244. this.gamepadMoveSensibility = 40;
  14245. }
  14246. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14247. var _this = this;
  14248. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14249. };
  14250. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14251. if (this._gamepads) {
  14252. this._gamepads.dispose();
  14253. }
  14254. this.gamepad = null;
  14255. };
  14256. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14257. if (this.gamepad) {
  14258. var camera = this.camera;
  14259. var LSValues = this.gamepad.leftStick;
  14260. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14261. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14262. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14263. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14264. var RSValues = this.gamepad.rightStick;
  14265. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14266. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14267. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14268. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14269. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14270. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14271. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14272. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14273. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14274. }
  14275. };
  14276. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14277. // Only the first gamepad can control the camera
  14278. if (gamepad.index === 0) {
  14279. this.gamepad = gamepad;
  14280. }
  14281. };
  14282. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14283. return "FreeCameraGamepadInput";
  14284. };
  14285. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14286. return "gamepad";
  14287. };
  14288. return FreeCameraGamepadInput;
  14289. }());
  14290. __decorate([
  14291. BABYLON.serialize()
  14292. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14293. __decorate([
  14294. BABYLON.serialize()
  14295. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14296. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14297. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14298. })(BABYLON || (BABYLON = {}));
  14299. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  14300. var BABYLON;
  14301. (function (BABYLON) {
  14302. var ArcRotateCameraKeyboardMoveInput = (function () {
  14303. function ArcRotateCameraKeyboardMoveInput() {
  14304. this._keys = [];
  14305. this.keysUp = [38];
  14306. this.keysDown = [40];
  14307. this.keysLeft = [37];
  14308. this.keysRight = [39];
  14309. }
  14310. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14311. var _this = this;
  14312. element.tabIndex = 1;
  14313. this._onKeyDown = function (evt) {
  14314. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14315. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14316. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14317. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14318. var index = _this._keys.indexOf(evt.keyCode);
  14319. if (index === -1) {
  14320. _this._keys.push(evt.keyCode);
  14321. }
  14322. if (evt.preventDefault) {
  14323. if (!noPreventDefault) {
  14324. evt.preventDefault();
  14325. }
  14326. }
  14327. }
  14328. };
  14329. this._onKeyUp = function (evt) {
  14330. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14331. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14332. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14333. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14334. var index = _this._keys.indexOf(evt.keyCode);
  14335. if (index >= 0) {
  14336. _this._keys.splice(index, 1);
  14337. }
  14338. if (evt.preventDefault) {
  14339. if (!noPreventDefault) {
  14340. evt.preventDefault();
  14341. }
  14342. }
  14343. }
  14344. };
  14345. this._onLostFocus = function () {
  14346. _this._keys = [];
  14347. };
  14348. element.addEventListener("keydown", this._onKeyDown, false);
  14349. element.addEventListener("keyup", this._onKeyUp, false);
  14350. BABYLON.Tools.RegisterTopRootEvents([
  14351. { name: "blur", handler: this._onLostFocus }
  14352. ]);
  14353. };
  14354. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14355. if (element) {
  14356. element.removeEventListener("keydown", this._onKeyDown);
  14357. element.removeEventListener("keyup", this._onKeyUp);
  14358. }
  14359. BABYLON.Tools.UnregisterTopRootEvents([
  14360. { name: "blur", handler: this._onLostFocus }
  14361. ]);
  14362. this._keys = [];
  14363. this._onKeyDown = null;
  14364. this._onKeyUp = null;
  14365. this._onLostFocus = null;
  14366. };
  14367. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14368. if (this._onKeyDown) {
  14369. var camera = this.camera;
  14370. for (var index = 0; index < this._keys.length; index++) {
  14371. var keyCode = this._keys[index];
  14372. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14373. camera.inertialAlphaOffset -= 0.01;
  14374. }
  14375. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14376. camera.inertialBetaOffset -= 0.01;
  14377. }
  14378. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14379. camera.inertialAlphaOffset += 0.01;
  14380. }
  14381. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14382. camera.inertialBetaOffset += 0.01;
  14383. }
  14384. }
  14385. }
  14386. };
  14387. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14388. return "ArcRotateCameraKeyboardMoveInput";
  14389. };
  14390. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14391. return "keyboard";
  14392. };
  14393. return ArcRotateCameraKeyboardMoveInput;
  14394. }());
  14395. __decorate([
  14396. BABYLON.serialize()
  14397. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14398. __decorate([
  14399. BABYLON.serialize()
  14400. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14401. __decorate([
  14402. BABYLON.serialize()
  14403. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14404. __decorate([
  14405. BABYLON.serialize()
  14406. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14407. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14408. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14409. })(BABYLON || (BABYLON = {}));
  14410. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  14411. var BABYLON;
  14412. (function (BABYLON) {
  14413. var ArcRotateCameraMouseWheelInput = (function () {
  14414. function ArcRotateCameraMouseWheelInput() {
  14415. this.wheelPrecision = 3.0;
  14416. }
  14417. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14418. var _this = this;
  14419. this._wheel = function (p, s) {
  14420. //sanity check - this should be a PointerWheel event.
  14421. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14422. return;
  14423. var event = p.event;
  14424. var delta = 0;
  14425. if (event.wheelDelta) {
  14426. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14427. }
  14428. else if (event.detail) {
  14429. delta = -event.detail / _this.wheelPrecision;
  14430. }
  14431. if (delta)
  14432. _this.camera.inertialRadiusOffset += delta;
  14433. if (event.preventDefault) {
  14434. if (!noPreventDefault) {
  14435. event.preventDefault();
  14436. }
  14437. }
  14438. };
  14439. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14440. };
  14441. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14442. if (this._observer && element) {
  14443. this.camera.getScene().onPointerObservable.remove(this._observer);
  14444. this._observer = null;
  14445. this._wheel = null;
  14446. }
  14447. };
  14448. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14449. return "ArcRotateCameraMouseWheelInput";
  14450. };
  14451. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14452. return "mousewheel";
  14453. };
  14454. return ArcRotateCameraMouseWheelInput;
  14455. }());
  14456. __decorate([
  14457. BABYLON.serialize()
  14458. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14459. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14460. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14461. })(BABYLON || (BABYLON = {}));
  14462. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  14463. var BABYLON;
  14464. (function (BABYLON) {
  14465. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14466. var ArcRotateCameraPointersInput = (function () {
  14467. function ArcRotateCameraPointersInput() {
  14468. this.buttons = [0, 1, 2];
  14469. this.angularSensibilityX = 1000.0;
  14470. this.angularSensibilityY = 1000.0;
  14471. this.pinchPrecision = 6.0;
  14472. this.panningSensibility = 50.0;
  14473. this._isPanClick = false;
  14474. this.pinchInwards = true;
  14475. }
  14476. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14477. var _this = this;
  14478. var engine = this.camera.getEngine();
  14479. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14480. var pointA, pointB;
  14481. var previousPinchDistance = 0;
  14482. this._pointerInput = function (p, s) {
  14483. var evt = p.event;
  14484. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14485. return;
  14486. }
  14487. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14488. try {
  14489. evt.srcElement.setPointerCapture(evt.pointerId);
  14490. }
  14491. catch (e) {
  14492. }
  14493. // Manage panning with pan button click
  14494. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14495. // manage pointers
  14496. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14497. if (pointA === undefined) {
  14498. pointA = cacheSoloPointer;
  14499. }
  14500. else if (pointB === undefined) {
  14501. pointB = cacheSoloPointer;
  14502. }
  14503. if (!noPreventDefault) {
  14504. evt.preventDefault();
  14505. element.focus();
  14506. }
  14507. }
  14508. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14509. try {
  14510. evt.srcElement.releasePointerCapture(evt.pointerId);
  14511. }
  14512. catch (e) {
  14513. }
  14514. cacheSoloPointer = null;
  14515. previousPinchDistance = 0;
  14516. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14517. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14518. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14519. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14520. pointA = pointB = undefined;
  14521. if (!noPreventDefault) {
  14522. evt.preventDefault();
  14523. }
  14524. }
  14525. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14526. if (!noPreventDefault) {
  14527. evt.preventDefault();
  14528. }
  14529. // One button down
  14530. if (pointA && pointB === undefined) {
  14531. if (_this.panningSensibility !== 0 &&
  14532. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14533. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14534. _this.camera
  14535. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14536. _this.camera
  14537. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14538. }
  14539. else {
  14540. var offsetX = evt.clientX - cacheSoloPointer.x;
  14541. var offsetY = evt.clientY - cacheSoloPointer.y;
  14542. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14543. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14544. }
  14545. cacheSoloPointer.x = evt.clientX;
  14546. cacheSoloPointer.y = evt.clientY;
  14547. }
  14548. else if (pointA && pointB) {
  14549. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14550. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14551. ed.x = evt.clientX;
  14552. ed.y = evt.clientY;
  14553. var direction = _this.pinchInwards ? 1 : -1;
  14554. var distX = pointA.x - pointB.x;
  14555. var distY = pointA.y - pointB.y;
  14556. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14557. if (previousPinchDistance === 0) {
  14558. previousPinchDistance = pinchSquaredDistance;
  14559. return;
  14560. }
  14561. if (pinchSquaredDistance !== previousPinchDistance) {
  14562. _this.camera
  14563. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14564. (_this.pinchPrecision *
  14565. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14566. direction);
  14567. previousPinchDistance = pinchSquaredDistance;
  14568. }
  14569. }
  14570. }
  14571. };
  14572. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14573. this._onContextMenu = function (evt) {
  14574. evt.preventDefault();
  14575. };
  14576. if (!this.camera._useCtrlForPanning) {
  14577. element.addEventListener("contextmenu", this._onContextMenu, false);
  14578. }
  14579. this._onLostFocus = function () {
  14580. //this._keys = [];
  14581. pointA = pointB = undefined;
  14582. previousPinchDistance = 0;
  14583. cacheSoloPointer = null;
  14584. };
  14585. this._onMouseMove = function (evt) {
  14586. if (!engine.isPointerLock) {
  14587. return;
  14588. }
  14589. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14590. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14591. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14592. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14593. if (!noPreventDefault) {
  14594. evt.preventDefault();
  14595. }
  14596. };
  14597. this._onGestureStart = function (e) {
  14598. if (window.MSGesture === undefined) {
  14599. return;
  14600. }
  14601. if (!_this._MSGestureHandler) {
  14602. _this._MSGestureHandler = new MSGesture();
  14603. _this._MSGestureHandler.target = element;
  14604. }
  14605. _this._MSGestureHandler.addPointer(e.pointerId);
  14606. };
  14607. this._onGesture = function (e) {
  14608. _this.camera.radius *= e.scale;
  14609. if (e.preventDefault) {
  14610. if (!noPreventDefault) {
  14611. e.stopPropagation();
  14612. e.preventDefault();
  14613. }
  14614. }
  14615. };
  14616. element.addEventListener("mousemove", this._onMouseMove, false);
  14617. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14618. element.addEventListener("MSGestureChange", this._onGesture, false);
  14619. element.addEventListener("keydown", this._onKeyDown, false);
  14620. element.addEventListener("keyup", this._onKeyUp, false);
  14621. BABYLON.Tools.RegisterTopRootEvents([
  14622. { name: "blur", handler: this._onLostFocus }
  14623. ]);
  14624. };
  14625. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14626. if (element && this._observer) {
  14627. this.camera.getScene().onPointerObservable.remove(this._observer);
  14628. this._observer = null;
  14629. element.removeEventListener("contextmenu", this._onContextMenu);
  14630. element.removeEventListener("mousemove", this._onMouseMove);
  14631. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14632. element.removeEventListener("MSGestureChange", this._onGesture);
  14633. element.removeEventListener("keydown", this._onKeyDown);
  14634. element.removeEventListener("keyup", this._onKeyUp);
  14635. this._isPanClick = false;
  14636. this.pinchInwards = true;
  14637. this._onKeyDown = null;
  14638. this._onKeyUp = null;
  14639. this._onMouseMove = null;
  14640. this._onGestureStart = null;
  14641. this._onGesture = null;
  14642. this._MSGestureHandler = null;
  14643. this._onLostFocus = null;
  14644. this._onContextMenu = null;
  14645. }
  14646. BABYLON.Tools.UnregisterTopRootEvents([
  14647. { name: "blur", handler: this._onLostFocus }
  14648. ]);
  14649. };
  14650. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14651. return "ArcRotateCameraPointersInput";
  14652. };
  14653. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14654. return "pointers";
  14655. };
  14656. return ArcRotateCameraPointersInput;
  14657. }());
  14658. __decorate([
  14659. BABYLON.serialize()
  14660. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14661. __decorate([
  14662. BABYLON.serialize()
  14663. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14664. __decorate([
  14665. BABYLON.serialize()
  14666. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14667. __decorate([
  14668. BABYLON.serialize()
  14669. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14670. __decorate([
  14671. BABYLON.serialize()
  14672. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14673. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14674. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14675. })(BABYLON || (BABYLON = {}));
  14676. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  14677. var BABYLON;
  14678. (function (BABYLON) {
  14679. var ArcRotateCameraGamepadInput = (function () {
  14680. function ArcRotateCameraGamepadInput() {
  14681. this.gamepadRotationSensibility = 80;
  14682. this.gamepadMoveSensibility = 40;
  14683. }
  14684. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14685. var _this = this;
  14686. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14687. };
  14688. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14689. if (this._gamepads) {
  14690. this._gamepads.dispose();
  14691. }
  14692. this.gamepad = null;
  14693. };
  14694. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14695. if (this.gamepad) {
  14696. var camera = this.camera;
  14697. var RSValues = this.gamepad.rightStick;
  14698. if (RSValues.x != 0) {
  14699. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14700. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14701. camera.inertialAlphaOffset += normalizedRX;
  14702. }
  14703. }
  14704. if (RSValues.y != 0) {
  14705. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14706. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14707. camera.inertialBetaOffset += normalizedRY;
  14708. }
  14709. }
  14710. var LSValues = this.gamepad.leftStick;
  14711. if (LSValues.y != 0) {
  14712. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14713. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14714. this.camera.inertialRadiusOffset -= normalizedLY;
  14715. }
  14716. }
  14717. }
  14718. };
  14719. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14720. // Only the first gamepad can control the camera
  14721. if (gamepad.index === 0) {
  14722. this.gamepad = gamepad;
  14723. }
  14724. };
  14725. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14726. return "ArcRotateCameraGamepadInput";
  14727. };
  14728. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14729. return "gamepad";
  14730. };
  14731. return ArcRotateCameraGamepadInput;
  14732. }());
  14733. __decorate([
  14734. BABYLON.serialize()
  14735. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14736. __decorate([
  14737. BABYLON.serialize()
  14738. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14739. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14740. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14741. })(BABYLON || (BABYLON = {}));
  14742. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  14743. var BABYLON;
  14744. (function (BABYLON) {
  14745. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14746. function ArcRotateCameraVRDeviceOrientationInput() {
  14747. this.alphaCorrection = 1;
  14748. this.betaCorrection = 1;
  14749. this.gammaCorrection = 1;
  14750. this._alpha = 0;
  14751. this._beta = 0;
  14752. this._gamma = 0;
  14753. this._dirty = false;
  14754. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14755. }
  14756. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14757. this.camera.attachControl(element, noPreventDefault);
  14758. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14759. };
  14760. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14761. var camera = this.camera;
  14762. this._alpha = +evt.alpha | 0;
  14763. this._beta = +evt.beta | 0;
  14764. this._gamma = +evt.gamma | 0;
  14765. this._dirty = true;
  14766. };
  14767. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14768. if (this._dirty) {
  14769. this._dirty = false;
  14770. if (this._gamma < 0) {
  14771. this._gamma = 180 + this._gamma;
  14772. }
  14773. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14774. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14775. }
  14776. };
  14777. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14778. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14779. };
  14780. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14781. return "ArcRotateCameraVRDeviceOrientationInput";
  14782. };
  14783. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14784. return "VRDeviceOrientation";
  14785. };
  14786. return ArcRotateCameraVRDeviceOrientationInput;
  14787. }());
  14788. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14789. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14790. })(BABYLON || (BABYLON = {}));
  14791. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  14792. var BABYLON;
  14793. (function (BABYLON) {
  14794. var TargetCamera = (function (_super) {
  14795. __extends(TargetCamera, _super);
  14796. function TargetCamera(name, position, scene) {
  14797. var _this = _super.call(this, name, position, scene) || this;
  14798. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14799. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  14800. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  14801. _this.speed = 2.0;
  14802. _this.noRotationConstraint = false;
  14803. _this.lockedTarget = null;
  14804. _this._currentTarget = BABYLON.Vector3.Zero();
  14805. _this._viewMatrix = BABYLON.Matrix.Zero();
  14806. _this._camMatrix = BABYLON.Matrix.Zero();
  14807. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14808. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14809. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14810. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14811. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14812. _this._lookAtTemp = BABYLON.Matrix.Zero();
  14813. _this._tempMatrix = BABYLON.Matrix.Zero();
  14814. return _this;
  14815. }
  14816. TargetCamera.prototype.getFrontPosition = function (distance) {
  14817. var direction = this.getTarget().subtract(this.position);
  14818. direction.normalize();
  14819. direction.scaleInPlace(distance);
  14820. return this.globalPosition.add(direction);
  14821. };
  14822. TargetCamera.prototype._getLockedTargetPosition = function () {
  14823. if (!this.lockedTarget) {
  14824. return null;
  14825. }
  14826. if (this.lockedTarget.absolutePosition) {
  14827. this.lockedTarget.computeWorldMatrix();
  14828. }
  14829. return this.lockedTarget.absolutePosition || this.lockedTarget;
  14830. };
  14831. // Cache
  14832. TargetCamera.prototype._initCache = function () {
  14833. _super.prototype._initCache.call(this);
  14834. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14835. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14836. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14837. };
  14838. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14839. if (!ignoreParentClass) {
  14840. _super.prototype._updateCache.call(this);
  14841. }
  14842. var lockedTargetPosition = this._getLockedTargetPosition();
  14843. if (!lockedTargetPosition) {
  14844. this._cache.lockedTarget = null;
  14845. }
  14846. else {
  14847. if (!this._cache.lockedTarget) {
  14848. this._cache.lockedTarget = lockedTargetPosition.clone();
  14849. }
  14850. else {
  14851. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14852. }
  14853. }
  14854. this._cache.rotation.copyFrom(this.rotation);
  14855. if (this.rotationQuaternion)
  14856. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14857. };
  14858. // Synchronized
  14859. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14860. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14861. return false;
  14862. }
  14863. var lockedTargetPosition = this._getLockedTargetPosition();
  14864. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14865. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14866. };
  14867. // Methods
  14868. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14869. var engine = this.getEngine();
  14870. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14871. };
  14872. // Target
  14873. TargetCamera.prototype.setTarget = function (target) {
  14874. this.upVector.normalize();
  14875. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14876. this._camMatrix.invert();
  14877. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14878. var vDir = target.subtract(this.position);
  14879. if (vDir.x >= 0.0) {
  14880. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14881. }
  14882. else {
  14883. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14884. }
  14885. this.rotation.z = 0;
  14886. if (isNaN(this.rotation.x)) {
  14887. this.rotation.x = 0;
  14888. }
  14889. if (isNaN(this.rotation.y)) {
  14890. this.rotation.y = 0;
  14891. }
  14892. if (isNaN(this.rotation.z)) {
  14893. this.rotation.z = 0;
  14894. }
  14895. if (this.rotationQuaternion) {
  14896. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14897. }
  14898. };
  14899. TargetCamera.prototype.getTarget = function () {
  14900. return this._currentTarget;
  14901. };
  14902. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14903. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14904. };
  14905. TargetCamera.prototype._updatePosition = function () {
  14906. this.position.addInPlace(this.cameraDirection);
  14907. };
  14908. TargetCamera.prototype._checkInputs = function () {
  14909. var needToMove = this._decideIfNeedsToMove();
  14910. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14911. // Move
  14912. if (needToMove) {
  14913. this._updatePosition();
  14914. }
  14915. // Rotate
  14916. if (needToRotate) {
  14917. this.rotation.x += this.cameraRotation.x;
  14918. this.rotation.y += this.cameraRotation.y;
  14919. if (!this.noRotationConstraint) {
  14920. var limit = (Math.PI / 2) * 0.95;
  14921. if (this.rotation.x > limit)
  14922. this.rotation.x = limit;
  14923. if (this.rotation.x < -limit)
  14924. this.rotation.x = -limit;
  14925. }
  14926. }
  14927. // Inertia
  14928. if (needToMove) {
  14929. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14930. this.cameraDirection.x = 0;
  14931. }
  14932. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14933. this.cameraDirection.y = 0;
  14934. }
  14935. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14936. this.cameraDirection.z = 0;
  14937. }
  14938. this.cameraDirection.scaleInPlace(this.inertia);
  14939. }
  14940. if (needToRotate) {
  14941. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14942. this.cameraRotation.x = 0;
  14943. }
  14944. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14945. this.cameraRotation.y = 0;
  14946. }
  14947. this.cameraRotation.scaleInPlace(this.inertia);
  14948. }
  14949. _super.prototype._checkInputs.call(this);
  14950. };
  14951. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14952. if (this.rotationQuaternion) {
  14953. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14954. //update the up vector!
  14955. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14956. }
  14957. else {
  14958. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14959. }
  14960. };
  14961. TargetCamera.prototype._getViewMatrix = function () {
  14962. if (!this.lockedTarget) {
  14963. // Compute
  14964. this._updateCameraRotationMatrix();
  14965. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14966. // Computing target and final matrix
  14967. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14968. }
  14969. else {
  14970. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14971. }
  14972. if (this.getScene().useRightHandedSystem) {
  14973. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14974. }
  14975. else {
  14976. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14977. }
  14978. return this._viewMatrix;
  14979. };
  14980. /**
  14981. * @override
  14982. * Override Camera.createRigCamera
  14983. */
  14984. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14985. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14986. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14987. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14988. if (!this.rotationQuaternion) {
  14989. this.rotationQuaternion = new BABYLON.Quaternion();
  14990. }
  14991. rigCamera._cameraRigParams = {};
  14992. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14993. }
  14994. return rigCamera;
  14995. }
  14996. return null;
  14997. };
  14998. /**
  14999. * @override
  15000. * Override Camera._updateRigCameras
  15001. */
  15002. TargetCamera.prototype._updateRigCameras = function () {
  15003. var camLeft = this._rigCameras[0];
  15004. var camRight = this._rigCameras[1];
  15005. switch (this.cameraRigMode) {
  15006. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15007. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15009. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15010. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15011. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15012. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15013. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15014. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15015. camLeft.setTarget(this.getTarget());
  15016. camRight.setTarget(this.getTarget());
  15017. break;
  15018. case BABYLON.Camera.RIG_MODE_VR:
  15019. case BABYLON.Camera.RIG_MODE_WEBVR:
  15020. if (camLeft.rotationQuaternion) {
  15021. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15022. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15023. }
  15024. else {
  15025. camLeft.rotation.copyFrom(this.rotation);
  15026. camRight.rotation.copyFrom(this.rotation);
  15027. }
  15028. camLeft.position.copyFrom(this.position);
  15029. camRight.position.copyFrom(this.position);
  15030. break;
  15031. }
  15032. _super.prototype._updateRigCameras.call(this);
  15033. };
  15034. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15035. if (!this._rigCamTransformMatrix) {
  15036. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15037. }
  15038. var target = this.getTarget();
  15039. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15040. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15041. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15042. };
  15043. TargetCamera.prototype.getClassName = function () {
  15044. return "TargetCamera";
  15045. };
  15046. return TargetCamera;
  15047. }(BABYLON.Camera));
  15048. __decorate([
  15049. BABYLON.serializeAsVector3()
  15050. ], TargetCamera.prototype, "rotation", void 0);
  15051. __decorate([
  15052. BABYLON.serialize()
  15053. ], TargetCamera.prototype, "speed", void 0);
  15054. __decorate([
  15055. BABYLON.serializeAsMeshReference("lockedTargetId")
  15056. ], TargetCamera.prototype, "lockedTarget", void 0);
  15057. BABYLON.TargetCamera = TargetCamera;
  15058. })(BABYLON || (BABYLON = {}));
  15059. //# sourceMappingURL=babylon.targetCamera.js.map
  15060. var BABYLON;
  15061. (function (BABYLON) {
  15062. var FreeCamera = (function (_super) {
  15063. __extends(FreeCamera, _super);
  15064. function FreeCamera(name, position, scene) {
  15065. var _this = _super.call(this, name, position, scene) || this;
  15066. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15067. _this.checkCollisions = false;
  15068. _this.applyGravity = false;
  15069. _this._collider = new BABYLON.Collider();
  15070. _this._needMoveForGravity = false;
  15071. _this._oldPosition = BABYLON.Vector3.Zero();
  15072. _this._diffPosition = BABYLON.Vector3.Zero();
  15073. _this._newPosition = BABYLON.Vector3.Zero();
  15074. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15075. if (collidedMesh === void 0) { collidedMesh = null; }
  15076. //TODO move this to the collision coordinator!
  15077. if (_this.getScene().workerCollisions)
  15078. newPosition.multiplyInPlace(_this._collider.radius);
  15079. var updatePosition = function (newPos) {
  15080. _this._newPosition.copyFrom(newPos);
  15081. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15082. var oldPosition = _this.position.clone();
  15083. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15084. _this.position.addInPlace(_this._diffPosition);
  15085. if (_this.onCollide && collidedMesh) {
  15086. _this.onCollide(collidedMesh);
  15087. }
  15088. }
  15089. };
  15090. updatePosition(newPosition);
  15091. };
  15092. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  15093. _this.inputs.addKeyboard().addMouse();
  15094. return _this;
  15095. }
  15096. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15097. //-- begin properties for backward compatibility for inputs
  15098. get: function () {
  15099. var mouse = this.inputs.attached["mouse"];
  15100. if (mouse)
  15101. return mouse.angularSensibility;
  15102. },
  15103. set: function (value) {
  15104. var mouse = this.inputs.attached["mouse"];
  15105. if (mouse)
  15106. mouse.angularSensibility = value;
  15107. },
  15108. enumerable: true,
  15109. configurable: true
  15110. });
  15111. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15112. get: function () {
  15113. var keyboard = this.inputs.attached["keyboard"];
  15114. if (keyboard)
  15115. return keyboard.keysUp;
  15116. },
  15117. set: function (value) {
  15118. var keyboard = this.inputs.attached["keyboard"];
  15119. if (keyboard)
  15120. keyboard.keysUp = value;
  15121. },
  15122. enumerable: true,
  15123. configurable: true
  15124. });
  15125. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15126. get: function () {
  15127. var keyboard = this.inputs.attached["keyboard"];
  15128. if (keyboard)
  15129. return keyboard.keysDown;
  15130. },
  15131. set: function (value) {
  15132. var keyboard = this.inputs.attached["keyboard"];
  15133. if (keyboard)
  15134. keyboard.keysDown = value;
  15135. },
  15136. enumerable: true,
  15137. configurable: true
  15138. });
  15139. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15140. get: function () {
  15141. var keyboard = this.inputs.attached["keyboard"];
  15142. if (keyboard)
  15143. return keyboard.keysLeft;
  15144. },
  15145. set: function (value) {
  15146. var keyboard = this.inputs.attached["keyboard"];
  15147. if (keyboard)
  15148. keyboard.keysLeft = value;
  15149. },
  15150. enumerable: true,
  15151. configurable: true
  15152. });
  15153. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15154. get: function () {
  15155. var keyboard = this.inputs.attached["keyboard"];
  15156. if (keyboard)
  15157. return keyboard.keysRight;
  15158. },
  15159. set: function (value) {
  15160. var keyboard = this.inputs.attached["keyboard"];
  15161. if (keyboard)
  15162. keyboard.keysRight = value;
  15163. },
  15164. enumerable: true,
  15165. configurable: true
  15166. });
  15167. // Controls
  15168. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15169. this.inputs.attachElement(element, noPreventDefault);
  15170. };
  15171. FreeCamera.prototype.detachControl = function (element) {
  15172. this.inputs.detachElement(element);
  15173. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15174. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15175. };
  15176. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15177. var globalPosition;
  15178. if (this.parent) {
  15179. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15180. }
  15181. else {
  15182. globalPosition = this.position;
  15183. }
  15184. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15185. this._collider.radius = this.ellipsoid;
  15186. //no need for clone, as long as gravity is not on.
  15187. var actualVelocity = velocity;
  15188. //add gravity to the velocity to prevent the dual-collision checking
  15189. if (this.applyGravity) {
  15190. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15191. actualVelocity = velocity.add(this.getScene().gravity);
  15192. }
  15193. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15194. };
  15195. FreeCamera.prototype._checkInputs = function () {
  15196. if (!this._localDirection) {
  15197. this._localDirection = BABYLON.Vector3.Zero();
  15198. this._transformedDirection = BABYLON.Vector3.Zero();
  15199. }
  15200. this.inputs.checkInputs();
  15201. _super.prototype._checkInputs.call(this);
  15202. };
  15203. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15204. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15205. };
  15206. FreeCamera.prototype._updatePosition = function () {
  15207. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15208. this._collideWithWorld(this.cameraDirection);
  15209. }
  15210. else {
  15211. this.position.addInPlace(this.cameraDirection);
  15212. }
  15213. };
  15214. FreeCamera.prototype.dispose = function () {
  15215. this.inputs.clear();
  15216. _super.prototype.dispose.call(this);
  15217. };
  15218. FreeCamera.prototype.getClassName = function () {
  15219. return "FreeCamera";
  15220. };
  15221. return FreeCamera;
  15222. }(BABYLON.TargetCamera));
  15223. __decorate([
  15224. BABYLON.serializeAsVector3()
  15225. ], FreeCamera.prototype, "ellipsoid", void 0);
  15226. __decorate([
  15227. BABYLON.serialize()
  15228. ], FreeCamera.prototype, "checkCollisions", void 0);
  15229. __decorate([
  15230. BABYLON.serialize()
  15231. ], FreeCamera.prototype, "applyGravity", void 0);
  15232. BABYLON.FreeCamera = FreeCamera;
  15233. })(BABYLON || (BABYLON = {}));
  15234. //# sourceMappingURL=babylon.freeCamera.js.map
  15235. var BABYLON;
  15236. (function (BABYLON) {
  15237. var FreeCameraInputsManager = (function (_super) {
  15238. __extends(FreeCameraInputsManager, _super);
  15239. function FreeCameraInputsManager(camera) {
  15240. return _super.call(this, camera) || this;
  15241. }
  15242. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15243. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15244. return this;
  15245. };
  15246. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15247. if (touchEnabled === void 0) { touchEnabled = true; }
  15248. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15249. return this;
  15250. };
  15251. FreeCameraInputsManager.prototype.addGamepad = function () {
  15252. this.add(new BABYLON.FreeCameraGamepadInput());
  15253. return this;
  15254. };
  15255. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15256. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15257. return this;
  15258. };
  15259. FreeCameraInputsManager.prototype.addTouch = function () {
  15260. this.add(new BABYLON.FreeCameraTouchInput());
  15261. return this;
  15262. };
  15263. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15264. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15265. return this;
  15266. };
  15267. return FreeCameraInputsManager;
  15268. }(BABYLON.CameraInputsManager));
  15269. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15270. })(BABYLON || (BABYLON = {}));
  15271. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  15272. var BABYLON;
  15273. (function (BABYLON) {
  15274. var FollowCamera = (function (_super) {
  15275. __extends(FollowCamera, _super);
  15276. function FollowCamera(name, position, scene, lockedTarget) {
  15277. var _this = _super.call(this, name, position, scene) || this;
  15278. _this.radius = 12;
  15279. _this.rotationOffset = 0;
  15280. _this.heightOffset = 4;
  15281. _this.cameraAcceleration = 0.05;
  15282. _this.maxCameraSpeed = 20;
  15283. _this.lockedTarget = lockedTarget;
  15284. return _this;
  15285. }
  15286. FollowCamera.prototype.getRadians = function (degrees) {
  15287. return degrees * Math.PI / 180;
  15288. };
  15289. FollowCamera.prototype.follow = function (cameraTarget) {
  15290. if (!cameraTarget)
  15291. return;
  15292. var yRotation;
  15293. if (cameraTarget.rotationQuaternion) {
  15294. var rotMatrix = new BABYLON.Matrix();
  15295. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15296. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15297. }
  15298. else {
  15299. yRotation = cameraTarget.rotation.y;
  15300. }
  15301. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15302. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15303. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15304. var dx = targetX - this.position.x;
  15305. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15306. var dz = (targetZ) - this.position.z;
  15307. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15308. var vy = dy * this.cameraAcceleration;
  15309. var vz = dz * this.cameraAcceleration * 2;
  15310. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15311. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15312. }
  15313. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15314. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15315. }
  15316. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15317. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15318. }
  15319. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15320. this.setTarget(cameraTarget.position);
  15321. };
  15322. FollowCamera.prototype._checkInputs = function () {
  15323. _super.prototype._checkInputs.call(this);
  15324. this.follow(this.lockedTarget);
  15325. };
  15326. FollowCamera.prototype.getClassName = function () {
  15327. return "FollowCamera";
  15328. };
  15329. return FollowCamera;
  15330. }(BABYLON.TargetCamera));
  15331. __decorate([
  15332. BABYLON.serialize()
  15333. ], FollowCamera.prototype, "radius", void 0);
  15334. __decorate([
  15335. BABYLON.serialize()
  15336. ], FollowCamera.prototype, "rotationOffset", void 0);
  15337. __decorate([
  15338. BABYLON.serialize()
  15339. ], FollowCamera.prototype, "heightOffset", void 0);
  15340. __decorate([
  15341. BABYLON.serialize()
  15342. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15343. __decorate([
  15344. BABYLON.serialize()
  15345. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15346. __decorate([
  15347. BABYLON.serializeAsMeshReference("lockedTargetId")
  15348. ], FollowCamera.prototype, "lockedTarget", void 0);
  15349. BABYLON.FollowCamera = FollowCamera;
  15350. var ArcFollowCamera = (function (_super) {
  15351. __extends(ArcFollowCamera, _super);
  15352. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15353. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15354. _this.alpha = alpha;
  15355. _this.beta = beta;
  15356. _this.radius = radius;
  15357. _this.target = target;
  15358. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15359. _this.follow();
  15360. return _this;
  15361. }
  15362. ArcFollowCamera.prototype.follow = function () {
  15363. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15364. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15365. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15366. this.position = this.target.position.add(this._cartesianCoordinates);
  15367. this.setTarget(this.target.position);
  15368. };
  15369. ArcFollowCamera.prototype._checkInputs = function () {
  15370. _super.prototype._checkInputs.call(this);
  15371. this.follow();
  15372. };
  15373. ArcFollowCamera.prototype.getClassName = function () {
  15374. return "ArcFollowCamera";
  15375. };
  15376. return ArcFollowCamera;
  15377. }(BABYLON.TargetCamera));
  15378. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15379. })(BABYLON || (BABYLON = {}));
  15380. //# sourceMappingURL=babylon.followCamera.js.map
  15381. var BABYLON;
  15382. (function (BABYLON) {
  15383. // We're mainly based on the logic defined into the FreeCamera code
  15384. var TouchCamera = (function (_super) {
  15385. __extends(TouchCamera, _super);
  15386. //-- end properties for backward compatibility for inputs
  15387. function TouchCamera(name, position, scene) {
  15388. var _this = _super.call(this, name, position, scene) || this;
  15389. _this.inputs.addTouch();
  15390. _this._setupInputs();
  15391. return _this;
  15392. }
  15393. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15394. //-- Begin properties for backward compatibility for inputs
  15395. get: function () {
  15396. var touch = this.inputs.attached["touch"];
  15397. if (touch)
  15398. return touch.touchAngularSensibility;
  15399. },
  15400. set: function (value) {
  15401. var touch = this.inputs.attached["touch"];
  15402. if (touch)
  15403. touch.touchAngularSensibility = value;
  15404. },
  15405. enumerable: true,
  15406. configurable: true
  15407. });
  15408. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15409. get: function () {
  15410. var touch = this.inputs.attached["touch"];
  15411. if (touch)
  15412. return touch.touchMoveSensibility;
  15413. },
  15414. set: function (value) {
  15415. var touch = this.inputs.attached["touch"];
  15416. if (touch)
  15417. touch.touchMoveSensibility = value;
  15418. },
  15419. enumerable: true,
  15420. configurable: true
  15421. });
  15422. TouchCamera.prototype.getClassName = function () {
  15423. return "TouchCamera";
  15424. };
  15425. TouchCamera.prototype._setupInputs = function () {
  15426. var mouse = this.inputs.attached["mouse"];
  15427. if (mouse) {
  15428. mouse.touchEnabled = false;
  15429. }
  15430. };
  15431. return TouchCamera;
  15432. }(BABYLON.FreeCamera));
  15433. BABYLON.TouchCamera = TouchCamera;
  15434. })(BABYLON || (BABYLON = {}));
  15435. //# sourceMappingURL=babylon.touchCamera.js.map
  15436. var BABYLON;
  15437. (function (BABYLON) {
  15438. var ArcRotateCamera = (function (_super) {
  15439. __extends(ArcRotateCamera, _super);
  15440. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15441. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15442. _this.inertialAlphaOffset = 0;
  15443. _this.inertialBetaOffset = 0;
  15444. _this.inertialRadiusOffset = 0;
  15445. _this.lowerAlphaLimit = null;
  15446. _this.upperAlphaLimit = null;
  15447. _this.lowerBetaLimit = 0.01;
  15448. _this.upperBetaLimit = Math.PI;
  15449. _this.lowerRadiusLimit = null;
  15450. _this.upperRadiusLimit = null;
  15451. _this.inertialPanningX = 0;
  15452. _this.inertialPanningY = 0;
  15453. //-- end properties for backward compatibility for inputs
  15454. _this.zoomOnFactor = 1;
  15455. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  15456. _this.allowUpsideDown = true;
  15457. _this._viewMatrix = new BABYLON.Matrix();
  15458. // Panning
  15459. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15460. _this.checkCollisions = false;
  15461. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15462. _this._collider = new BABYLON.Collider();
  15463. _this._previousPosition = BABYLON.Vector3.Zero();
  15464. _this._collisionVelocity = BABYLON.Vector3.Zero();
  15465. _this._newPosition = BABYLON.Vector3.Zero();
  15466. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15467. if (collidedMesh === void 0) { collidedMesh = null; }
  15468. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15469. newPosition.multiplyInPlace(_this._collider.radius);
  15470. }
  15471. if (!collidedMesh) {
  15472. _this._previousPosition.copyFrom(_this.position);
  15473. }
  15474. else {
  15475. _this.setPosition(newPosition);
  15476. if (_this.onCollide) {
  15477. _this.onCollide(collidedMesh);
  15478. }
  15479. }
  15480. // Recompute because of constraints
  15481. var cosa = Math.cos(_this.alpha);
  15482. var sina = Math.sin(_this.alpha);
  15483. var cosb = Math.cos(_this.beta);
  15484. var sinb = Math.sin(_this.beta);
  15485. if (sinb === 0) {
  15486. sinb = 0.0001;
  15487. }
  15488. var target = _this._getTargetPosition();
  15489. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15490. _this.position.copyFrom(_this._newPosition);
  15491. var up = _this.upVector;
  15492. if (_this.allowUpsideDown && _this.beta < 0) {
  15493. up = up.clone();
  15494. up = up.negate();
  15495. }
  15496. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15497. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15498. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15499. _this._collisionTriggered = false;
  15500. };
  15501. if (!target) {
  15502. _this.target = BABYLON.Vector3.Zero();
  15503. }
  15504. else {
  15505. _this.target = target;
  15506. }
  15507. _this.alpha = alpha;
  15508. _this.beta = beta;
  15509. _this.radius = radius;
  15510. _this.getViewMatrix();
  15511. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  15512. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15513. return _this;
  15514. }
  15515. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15516. //-- begin properties for backward compatibility for inputs
  15517. get: function () {
  15518. var pointers = this.inputs.attached["pointers"];
  15519. if (pointers)
  15520. return pointers.angularSensibilityX;
  15521. },
  15522. set: function (value) {
  15523. var pointers = this.inputs.attached["pointers"];
  15524. if (pointers) {
  15525. pointers.angularSensibilityX = value;
  15526. }
  15527. },
  15528. enumerable: true,
  15529. configurable: true
  15530. });
  15531. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15532. get: function () {
  15533. var pointers = this.inputs.attached["pointers"];
  15534. if (pointers)
  15535. return pointers.angularSensibilityY;
  15536. },
  15537. set: function (value) {
  15538. var pointers = this.inputs.attached["pointers"];
  15539. if (pointers) {
  15540. pointers.angularSensibilityY = value;
  15541. }
  15542. },
  15543. enumerable: true,
  15544. configurable: true
  15545. });
  15546. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15547. get: function () {
  15548. var pointers = this.inputs.attached["pointers"];
  15549. if (pointers)
  15550. return pointers.pinchPrecision;
  15551. },
  15552. set: function (value) {
  15553. var pointers = this.inputs.attached["pointers"];
  15554. if (pointers) {
  15555. pointers.pinchPrecision = value;
  15556. }
  15557. },
  15558. enumerable: true,
  15559. configurable: true
  15560. });
  15561. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15562. get: function () {
  15563. var pointers = this.inputs.attached["pointers"];
  15564. if (pointers)
  15565. return pointers.panningSensibility;
  15566. },
  15567. set: function (value) {
  15568. var pointers = this.inputs.attached["pointers"];
  15569. if (pointers) {
  15570. pointers.panningSensibility = value;
  15571. }
  15572. },
  15573. enumerable: true,
  15574. configurable: true
  15575. });
  15576. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15577. get: function () {
  15578. var keyboard = this.inputs.attached["keyboard"];
  15579. if (keyboard)
  15580. return keyboard.keysUp;
  15581. },
  15582. set: function (value) {
  15583. var keyboard = this.inputs.attached["keyboard"];
  15584. if (keyboard)
  15585. keyboard.keysUp = value;
  15586. },
  15587. enumerable: true,
  15588. configurable: true
  15589. });
  15590. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15591. get: function () {
  15592. var keyboard = this.inputs.attached["keyboard"];
  15593. if (keyboard)
  15594. return keyboard.keysDown;
  15595. },
  15596. set: function (value) {
  15597. var keyboard = this.inputs.attached["keyboard"];
  15598. if (keyboard)
  15599. keyboard.keysDown = value;
  15600. },
  15601. enumerable: true,
  15602. configurable: true
  15603. });
  15604. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15605. get: function () {
  15606. var keyboard = this.inputs.attached["keyboard"];
  15607. if (keyboard)
  15608. return keyboard.keysLeft;
  15609. },
  15610. set: function (value) {
  15611. var keyboard = this.inputs.attached["keyboard"];
  15612. if (keyboard)
  15613. keyboard.keysLeft = value;
  15614. },
  15615. enumerable: true,
  15616. configurable: true
  15617. });
  15618. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15619. get: function () {
  15620. var keyboard = this.inputs.attached["keyboard"];
  15621. if (keyboard)
  15622. return keyboard.keysRight;
  15623. },
  15624. set: function (value) {
  15625. var keyboard = this.inputs.attached["keyboard"];
  15626. if (keyboard)
  15627. keyboard.keysRight = value;
  15628. },
  15629. enumerable: true,
  15630. configurable: true
  15631. });
  15632. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15633. get: function () {
  15634. var mousewheel = this.inputs.attached["mousewheel"];
  15635. if (mousewheel)
  15636. return mousewheel.wheelPrecision;
  15637. },
  15638. set: function (value) {
  15639. var mousewheel = this.inputs.attached["mousewheel"];
  15640. if (mousewheel)
  15641. mousewheel.wheelPrecision = value;
  15642. },
  15643. enumerable: true,
  15644. configurable: true
  15645. });
  15646. // Cache
  15647. ArcRotateCamera.prototype._initCache = function () {
  15648. _super.prototype._initCache.call(this);
  15649. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15650. this._cache.alpha = undefined;
  15651. this._cache.beta = undefined;
  15652. this._cache.radius = undefined;
  15653. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15654. };
  15655. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15656. if (!ignoreParentClass) {
  15657. _super.prototype._updateCache.call(this);
  15658. }
  15659. this._cache.target.copyFrom(this._getTargetPosition());
  15660. this._cache.alpha = this.alpha;
  15661. this._cache.beta = this.beta;
  15662. this._cache.radius = this.radius;
  15663. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15664. };
  15665. ArcRotateCamera.prototype._getTargetPosition = function () {
  15666. if (this.target.getAbsolutePosition) {
  15667. var pos = this.target.getAbsolutePosition();
  15668. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15669. }
  15670. return this.target;
  15671. };
  15672. // Synchronized
  15673. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15674. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15675. return false;
  15676. return this._cache.target.equals(this.target)
  15677. && this._cache.alpha === this.alpha
  15678. && this._cache.beta === this.beta
  15679. && this._cache.radius === this.radius
  15680. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15681. };
  15682. // Methods
  15683. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15684. var _this = this;
  15685. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15686. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15687. this._useCtrlForPanning = useCtrlForPanning;
  15688. this._panningMouseButton = panningMouseButton;
  15689. this.inputs.attachElement(element, noPreventDefault);
  15690. this._reset = function () {
  15691. _this.inertialAlphaOffset = 0;
  15692. _this.inertialBetaOffset = 0;
  15693. _this.inertialRadiusOffset = 0;
  15694. };
  15695. };
  15696. ArcRotateCamera.prototype.detachControl = function (element) {
  15697. this.inputs.detachElement(element);
  15698. if (this._reset) {
  15699. this._reset();
  15700. }
  15701. };
  15702. ArcRotateCamera.prototype._checkInputs = function () {
  15703. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15704. if (this._collisionTriggered) {
  15705. return;
  15706. }
  15707. this.inputs.checkInputs();
  15708. // Inertia
  15709. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15710. if (this.getScene().useRightHandedSystem) {
  15711. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15712. }
  15713. else {
  15714. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15715. }
  15716. this.beta += this.inertialBetaOffset;
  15717. this.radius -= this.inertialRadiusOffset;
  15718. this.inertialAlphaOffset *= this.inertia;
  15719. this.inertialBetaOffset *= this.inertia;
  15720. this.inertialRadiusOffset *= this.inertia;
  15721. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15722. this.inertialAlphaOffset = 0;
  15723. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15724. this.inertialBetaOffset = 0;
  15725. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15726. this.inertialRadiusOffset = 0;
  15727. }
  15728. // Panning inertia
  15729. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15730. if (!this._localDirection) {
  15731. this._localDirection = BABYLON.Vector3.Zero();
  15732. this._transformedDirection = BABYLON.Vector3.Zero();
  15733. }
  15734. this.inertialPanningX *= this.inertia;
  15735. this.inertialPanningY *= this.inertia;
  15736. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15737. this.inertialPanningX = 0;
  15738. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15739. this.inertialPanningY = 0;
  15740. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15741. this._localDirection.multiplyInPlace(this.panningAxis);
  15742. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15743. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15744. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15745. if (!this.panningAxis.y) {
  15746. this._transformedDirection.y = 0;
  15747. }
  15748. if (!this.target.getAbsolutePosition) {
  15749. this.target.addInPlace(this._transformedDirection);
  15750. }
  15751. }
  15752. // Limits
  15753. this._checkLimits();
  15754. _super.prototype._checkInputs.call(this);
  15755. };
  15756. ArcRotateCamera.prototype._checkLimits = function () {
  15757. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15758. if (this.allowUpsideDown && this.beta > Math.PI) {
  15759. this.beta = this.beta - (2 * Math.PI);
  15760. }
  15761. }
  15762. else {
  15763. if (this.beta < this.lowerBetaLimit) {
  15764. this.beta = this.lowerBetaLimit;
  15765. }
  15766. }
  15767. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15768. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15769. this.beta = this.beta + (2 * Math.PI);
  15770. }
  15771. }
  15772. else {
  15773. if (this.beta > this.upperBetaLimit) {
  15774. this.beta = this.upperBetaLimit;
  15775. }
  15776. }
  15777. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15778. this.alpha = this.lowerAlphaLimit;
  15779. }
  15780. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15781. this.alpha = this.upperAlphaLimit;
  15782. }
  15783. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15784. this.radius = this.lowerRadiusLimit;
  15785. }
  15786. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15787. this.radius = this.upperRadiusLimit;
  15788. }
  15789. };
  15790. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15791. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15792. this.radius = radiusv3.length();
  15793. // Alpha
  15794. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15795. if (radiusv3.z < 0) {
  15796. this.alpha = 2 * Math.PI - this.alpha;
  15797. }
  15798. // Beta
  15799. this.beta = Math.acos(radiusv3.y / this.radius);
  15800. this._checkLimits();
  15801. };
  15802. ArcRotateCamera.prototype.setPosition = function (position) {
  15803. if (this.position.equals(position)) {
  15804. return;
  15805. }
  15806. this.position.copyFrom(position);
  15807. this.rebuildAnglesAndRadius();
  15808. };
  15809. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15810. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15811. if (this._getTargetPosition().equals(target)) {
  15812. return;
  15813. }
  15814. if (toBoundingCenter && target.getBoundingInfo) {
  15815. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15816. }
  15817. else {
  15818. this._targetBoundingCenter = null;
  15819. }
  15820. this.target = target;
  15821. this.rebuildAnglesAndRadius();
  15822. };
  15823. ArcRotateCamera.prototype._getViewMatrix = function () {
  15824. // Compute
  15825. var cosa = Math.cos(this.alpha);
  15826. var sina = Math.sin(this.alpha);
  15827. var cosb = Math.cos(this.beta);
  15828. var sinb = Math.sin(this.beta);
  15829. if (sinb === 0) {
  15830. sinb = 0.0001;
  15831. }
  15832. var target = this._getTargetPosition();
  15833. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15834. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15835. this._collider.radius = this.collisionRadius;
  15836. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15837. this._collisionTriggered = true;
  15838. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15839. }
  15840. else {
  15841. this.position.copyFrom(this._newPosition);
  15842. var up = this.upVector;
  15843. if (this.allowUpsideDown && this.beta < 0) {
  15844. up = up.clone();
  15845. up = up.negate();
  15846. }
  15847. if (this.getScene().useRightHandedSystem) {
  15848. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15849. }
  15850. else {
  15851. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15852. }
  15853. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15854. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15855. }
  15856. this._currentTarget = target;
  15857. return this._viewMatrix;
  15858. };
  15859. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15860. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15861. meshes = meshes || this.getScene().meshes;
  15862. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15863. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15864. this.radius = distance * this.zoomOnFactor;
  15865. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15866. };
  15867. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15868. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15869. var meshesOrMinMaxVector;
  15870. var distance;
  15871. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15872. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15873. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15874. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15875. }
  15876. else {
  15877. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15878. distance = meshesOrMinMaxVectorAndDistance.distance;
  15879. }
  15880. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15881. if (!doNotUpdateMaxZ) {
  15882. this.maxZ = distance * 2;
  15883. }
  15884. };
  15885. /**
  15886. * @override
  15887. * Override Camera.createRigCamera
  15888. */
  15889. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15890. var alphaShift;
  15891. switch (this.cameraRigMode) {
  15892. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15895. case BABYLON.Camera.RIG_MODE_VR:
  15896. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15897. break;
  15898. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15899. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15900. break;
  15901. }
  15902. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15903. rigCam._cameraRigParams = {};
  15904. return rigCam;
  15905. };
  15906. /**
  15907. * @override
  15908. * Override Camera._updateRigCameras
  15909. */
  15910. ArcRotateCamera.prototype._updateRigCameras = function () {
  15911. var camLeft = this._rigCameras[0];
  15912. var camRight = this._rigCameras[1];
  15913. camLeft.beta = camRight.beta = this.beta;
  15914. camLeft.radius = camRight.radius = this.radius;
  15915. switch (this.cameraRigMode) {
  15916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15919. case BABYLON.Camera.RIG_MODE_VR:
  15920. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15921. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15922. break;
  15923. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15924. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15925. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15926. break;
  15927. }
  15928. _super.prototype._updateRigCameras.call(this);
  15929. };
  15930. ArcRotateCamera.prototype.dispose = function () {
  15931. this.inputs.clear();
  15932. _super.prototype.dispose.call(this);
  15933. };
  15934. ArcRotateCamera.prototype.getClassName = function () {
  15935. return "ArcRotateCamera";
  15936. };
  15937. return ArcRotateCamera;
  15938. }(BABYLON.TargetCamera));
  15939. __decorate([
  15940. BABYLON.serialize()
  15941. ], ArcRotateCamera.prototype, "alpha", void 0);
  15942. __decorate([
  15943. BABYLON.serialize()
  15944. ], ArcRotateCamera.prototype, "beta", void 0);
  15945. __decorate([
  15946. BABYLON.serialize()
  15947. ], ArcRotateCamera.prototype, "radius", void 0);
  15948. __decorate([
  15949. BABYLON.serializeAsVector3()
  15950. ], ArcRotateCamera.prototype, "target", void 0);
  15951. __decorate([
  15952. BABYLON.serialize()
  15953. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15954. __decorate([
  15955. BABYLON.serialize()
  15956. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15957. __decorate([
  15958. BABYLON.serialize()
  15959. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15960. __decorate([
  15961. BABYLON.serialize()
  15962. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15963. __decorate([
  15964. BABYLON.serialize()
  15965. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15966. __decorate([
  15967. BABYLON.serialize()
  15968. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15969. __decorate([
  15970. BABYLON.serialize()
  15971. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15972. __decorate([
  15973. BABYLON.serialize()
  15974. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15975. __decorate([
  15976. BABYLON.serialize()
  15977. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15978. __decorate([
  15979. BABYLON.serialize()
  15980. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15981. __decorate([
  15982. BABYLON.serialize()
  15983. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15984. __decorate([
  15985. BABYLON.serialize()
  15986. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15987. __decorate([
  15988. BABYLON.serialize()
  15989. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15990. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15991. })(BABYLON || (BABYLON = {}));
  15992. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  15993. var BABYLON;
  15994. (function (BABYLON) {
  15995. var ArcRotateCameraInputsManager = (function (_super) {
  15996. __extends(ArcRotateCameraInputsManager, _super);
  15997. function ArcRotateCameraInputsManager(camera) {
  15998. return _super.call(this, camera) || this;
  15999. }
  16000. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  16001. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  16002. return this;
  16003. };
  16004. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16005. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16006. return this;
  16007. };
  16008. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16009. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16010. return this;
  16011. };
  16012. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16013. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16014. return this;
  16015. };
  16016. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16017. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16018. return this;
  16019. };
  16020. return ArcRotateCameraInputsManager;
  16021. }(BABYLON.CameraInputsManager));
  16022. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16023. })(BABYLON || (BABYLON = {}));
  16024. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16025. var BABYLON;
  16026. (function (BABYLON) {
  16027. var RenderingManager = (function () {
  16028. function RenderingManager(scene) {
  16029. this._renderingGroups = new Array();
  16030. this._autoClearDepthStencil = {};
  16031. this._customOpaqueSortCompareFn = {};
  16032. this._customAlphaTestSortCompareFn = {};
  16033. this._customTransparentSortCompareFn = {};
  16034. this._renderinGroupInfo = null;
  16035. this._scene = scene;
  16036. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16037. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16038. }
  16039. }
  16040. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16041. if (depth === void 0) { depth = true; }
  16042. if (stencil === void 0) { stencil = true; }
  16043. if (this._depthStencilBufferAlreadyCleaned) {
  16044. return;
  16045. }
  16046. this._scene.getEngine().clear(0, false, depth, stencil);
  16047. this._depthStencilBufferAlreadyCleaned = true;
  16048. };
  16049. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16050. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16051. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16052. var info = null;
  16053. if (observable) {
  16054. if (!this._renderinGroupInfo) {
  16055. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16056. }
  16057. info = this._renderinGroupInfo;
  16058. info.scene = this._scene;
  16059. info.camera = this._scene.activeCamera;
  16060. }
  16061. // Dispatch sprites
  16062. if (renderSprites) {
  16063. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16064. var manager = this._scene.spriteManagers[index];
  16065. this.dispatchSprites(manager);
  16066. }
  16067. }
  16068. // Render
  16069. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16070. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16071. var renderingGroup = this._renderingGroups[index];
  16072. this._currentIndex = index;
  16073. if (renderingGroup) {
  16074. var renderingGroupMask = 0;
  16075. // Fire PRECLEAR stage
  16076. if (observable) {
  16077. renderingGroupMask = Math.pow(2, index);
  16078. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16079. info.renderingGroupId = index;
  16080. observable.notifyObservers(info, renderingGroupMask);
  16081. }
  16082. // Clear depth/stencil if needed
  16083. var autoClear = this._autoClearDepthStencil[index];
  16084. if (autoClear && autoClear.autoClear) {
  16085. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16086. }
  16087. // Fire PREOPAQUE stage
  16088. if (observable) {
  16089. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16090. observable.notifyObservers(info, renderingGroupMask);
  16091. }
  16092. // Fire PRETRANSPARENT stage
  16093. if (observable) {
  16094. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16095. observable.notifyObservers(info, renderingGroupMask);
  16096. }
  16097. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16098. // Fire POSTTRANSPARENT stage
  16099. if (observable) {
  16100. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16101. observable.notifyObservers(info, renderingGroupMask);
  16102. }
  16103. }
  16104. }
  16105. };
  16106. RenderingManager.prototype.reset = function () {
  16107. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16108. var renderingGroup = this._renderingGroups[index];
  16109. if (renderingGroup) {
  16110. renderingGroup.prepare();
  16111. }
  16112. }
  16113. };
  16114. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16115. if (!this._renderingGroups[renderingGroupId]) {
  16116. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16117. }
  16118. };
  16119. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16120. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16121. this._prepareRenderingGroup(renderingGroupId);
  16122. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16123. };
  16124. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16125. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16126. this._prepareRenderingGroup(renderingGroupId);
  16127. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16128. };
  16129. RenderingManager.prototype.dispatch = function (subMesh) {
  16130. var mesh = subMesh.getMesh();
  16131. var renderingGroupId = mesh.renderingGroupId || 0;
  16132. this._prepareRenderingGroup(renderingGroupId);
  16133. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16134. };
  16135. /**
  16136. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16137. * This allowed control for front to back rendering or reversly depending of the special needs.
  16138. *
  16139. * @param renderingGroupId The rendering group id corresponding to its index
  16140. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16141. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16142. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16143. */
  16144. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16145. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16146. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16147. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16148. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16149. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16150. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16151. if (this._renderingGroups[renderingGroupId]) {
  16152. var group = this._renderingGroups[renderingGroupId];
  16153. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16154. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16155. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16156. }
  16157. };
  16158. /**
  16159. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16160. *
  16161. * @param renderingGroupId The rendering group id corresponding to its index
  16162. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16163. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16164. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16165. */
  16166. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16167. if (depth === void 0) { depth = true; }
  16168. if (stencil === void 0) { stencil = true; }
  16169. this._autoClearDepthStencil[renderingGroupId] = {
  16170. autoClear: autoClearDepthStencil,
  16171. depth: depth,
  16172. stencil: stencil
  16173. };
  16174. };
  16175. return RenderingManager;
  16176. }());
  16177. /**
  16178. * The max id used for rendering groups (not included)
  16179. */
  16180. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16181. /**
  16182. * The min id used for rendering groups (included)
  16183. */
  16184. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16185. BABYLON.RenderingManager = RenderingManager;
  16186. })(BABYLON || (BABYLON = {}));
  16187. //# sourceMappingURL=babylon.renderingManager.js.map
  16188. var BABYLON;
  16189. (function (BABYLON) {
  16190. var RenderingGroup = (function () {
  16191. /**
  16192. * Creates a new rendering group.
  16193. * @param index The rendering group index
  16194. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16195. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16196. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16197. */
  16198. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16199. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16200. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16201. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16202. this.index = index;
  16203. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16204. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16205. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16206. this._particleSystems = new BABYLON.SmartArray(256);
  16207. this._spriteManagers = new BABYLON.SmartArray(256);
  16208. this._scene = scene;
  16209. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16210. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16211. this.transparentSortCompareFn = transparentSortCompareFn;
  16212. }
  16213. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16214. /**
  16215. * Set the opaque sort comparison function.
  16216. * If null the sub meshes will be render in the order they were created
  16217. */
  16218. set: function (value) {
  16219. this._opaqueSortCompareFn = value;
  16220. if (value) {
  16221. this._renderOpaque = this.renderOpaqueSorted;
  16222. }
  16223. else {
  16224. this._renderOpaque = RenderingGroup.renderUnsorted;
  16225. }
  16226. },
  16227. enumerable: true,
  16228. configurable: true
  16229. });
  16230. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16231. /**
  16232. * Set the alpha test sort comparison function.
  16233. * If null the sub meshes will be render in the order they were created
  16234. */
  16235. set: function (value) {
  16236. this._alphaTestSortCompareFn = value;
  16237. if (value) {
  16238. this._renderAlphaTest = this.renderAlphaTestSorted;
  16239. }
  16240. else {
  16241. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16242. }
  16243. },
  16244. enumerable: true,
  16245. configurable: true
  16246. });
  16247. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16248. /**
  16249. * Set the transparent sort comparison function.
  16250. * If null the sub meshes will be render in the order they were created
  16251. */
  16252. set: function (value) {
  16253. if (value) {
  16254. this._transparentSortCompareFn = value;
  16255. }
  16256. else {
  16257. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16258. }
  16259. this._renderTransparent = this.renderTransparentSorted;
  16260. },
  16261. enumerable: true,
  16262. configurable: true
  16263. });
  16264. /**
  16265. * Render all the sub meshes contained in the group.
  16266. * @param customRenderFunction Used to override the default render behaviour of the group.
  16267. * @returns true if rendered some submeshes.
  16268. */
  16269. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16270. if (customRenderFunction) {
  16271. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16272. return;
  16273. }
  16274. var engine = this._scene.getEngine();
  16275. // Opaque
  16276. if (this._opaqueSubMeshes.length !== 0) {
  16277. this._renderOpaque(this._opaqueSubMeshes);
  16278. }
  16279. // Alpha test
  16280. if (this._alphaTestSubMeshes.length !== 0) {
  16281. engine.setAlphaTesting(true);
  16282. this._renderAlphaTest(this._alphaTestSubMeshes);
  16283. engine.setAlphaTesting(false);
  16284. }
  16285. // Sprites
  16286. if (renderSprites) {
  16287. this._renderSprites();
  16288. }
  16289. // Particles
  16290. if (renderParticles) {
  16291. this._renderParticles(activeMeshes);
  16292. }
  16293. if (this.onBeforeTransparentRendering) {
  16294. this.onBeforeTransparentRendering();
  16295. }
  16296. // Transparent
  16297. if (this._transparentSubMeshes.length !== 0) {
  16298. this._renderTransparent(this._transparentSubMeshes);
  16299. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16300. }
  16301. };
  16302. /**
  16303. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16304. * @param subMeshes The submeshes to render
  16305. */
  16306. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16307. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16308. };
  16309. /**
  16310. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16311. * @param subMeshes The submeshes to render
  16312. */
  16313. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16314. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16315. };
  16316. /**
  16317. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16318. * @param subMeshes The submeshes to render
  16319. */
  16320. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16321. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16322. };
  16323. /**
  16324. * Renders the submeshes in a specified order.
  16325. * @param subMeshes The submeshes to sort before render
  16326. * @param sortCompareFn The comparison function use to sort
  16327. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16328. * @param transparent Specifies to activate blending if true
  16329. */
  16330. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16331. var subIndex = 0;
  16332. var subMesh;
  16333. for (; subIndex < subMeshes.length; subIndex++) {
  16334. subMesh = subMeshes.data[subIndex];
  16335. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16336. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16337. }
  16338. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16339. sortedArray.sort(sortCompareFn);
  16340. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16341. subMesh = sortedArray[subIndex];
  16342. subMesh.render(transparent);
  16343. }
  16344. };
  16345. /**
  16346. * Renders the submeshes in the order they were dispatched (no sort applied).
  16347. * @param subMeshes The submeshes to render
  16348. */
  16349. RenderingGroup.renderUnsorted = function (subMeshes) {
  16350. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16351. var submesh = subMeshes.data[subIndex];
  16352. submesh.render(false);
  16353. }
  16354. };
  16355. /**
  16356. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16357. * are rendered back to front if in the same alpha index.
  16358. *
  16359. * @param a The first submesh
  16360. * @param b The second submesh
  16361. * @returns The result of the comparison
  16362. */
  16363. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16364. // Alpha index first
  16365. if (a._alphaIndex > b._alphaIndex) {
  16366. return 1;
  16367. }
  16368. if (a._alphaIndex < b._alphaIndex) {
  16369. return -1;
  16370. }
  16371. // Then distance to camera
  16372. return RenderingGroup.backToFrontSortCompare(a, b);
  16373. };
  16374. /**
  16375. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16376. * are rendered back to front.
  16377. *
  16378. * @param a The first submesh
  16379. * @param b The second submesh
  16380. * @returns The result of the comparison
  16381. */
  16382. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16383. // Then distance to camera
  16384. if (a._distanceToCamera < b._distanceToCamera) {
  16385. return 1;
  16386. }
  16387. if (a._distanceToCamera > b._distanceToCamera) {
  16388. return -1;
  16389. }
  16390. return 0;
  16391. };
  16392. /**
  16393. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16394. * are rendered front to back (prevent overdraw).
  16395. *
  16396. * @param a The first submesh
  16397. * @param b The second submesh
  16398. * @returns The result of the comparison
  16399. */
  16400. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16401. // Then distance to camera
  16402. if (a._distanceToCamera < b._distanceToCamera) {
  16403. return -1;
  16404. }
  16405. if (a._distanceToCamera > b._distanceToCamera) {
  16406. return 1;
  16407. }
  16408. return 0;
  16409. };
  16410. /**
  16411. * Resets the different lists of submeshes to prepare a new frame.
  16412. */
  16413. RenderingGroup.prototype.prepare = function () {
  16414. this._opaqueSubMeshes.reset();
  16415. this._transparentSubMeshes.reset();
  16416. this._alphaTestSubMeshes.reset();
  16417. this._particleSystems.reset();
  16418. this._spriteManagers.reset();
  16419. };
  16420. /**
  16421. * Inserts the submesh in its correct queue depending on its material.
  16422. * @param subMesh The submesh to dispatch
  16423. */
  16424. RenderingGroup.prototype.dispatch = function (subMesh) {
  16425. var material = subMesh.getMaterial();
  16426. var mesh = subMesh.getMesh();
  16427. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16428. this._transparentSubMeshes.push(subMesh);
  16429. }
  16430. else if (material.needAlphaTesting()) {
  16431. this._alphaTestSubMeshes.push(subMesh);
  16432. }
  16433. else {
  16434. this._opaqueSubMeshes.push(subMesh); // Opaque
  16435. }
  16436. };
  16437. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16438. this._spriteManagers.push(spriteManager);
  16439. };
  16440. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16441. this._particleSystems.push(particleSystem);
  16442. };
  16443. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16444. if (this._particleSystems.length === 0) {
  16445. return;
  16446. }
  16447. // Particles
  16448. var activeCamera = this._scene.activeCamera;
  16449. this._scene._particlesDuration.beginMonitoring();
  16450. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16451. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16452. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16453. continue;
  16454. }
  16455. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  16456. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16457. }
  16458. }
  16459. this._scene._particlesDuration.endMonitoring(false);
  16460. };
  16461. RenderingGroup.prototype._renderSprites = function () {
  16462. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16463. return;
  16464. }
  16465. // Sprites
  16466. var activeCamera = this._scene.activeCamera;
  16467. this._scene._spritesDuration.beginMonitoring();
  16468. for (var id = 0; id < this._spriteManagers.length; id++) {
  16469. var spriteManager = this._scene.spriteManagers[id];
  16470. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16471. spriteManager.render();
  16472. }
  16473. }
  16474. this._scene._spritesDuration.endMonitoring(false);
  16475. };
  16476. return RenderingGroup;
  16477. }());
  16478. BABYLON.RenderingGroup = RenderingGroup;
  16479. })(BABYLON || (BABYLON = {}));
  16480. //# sourceMappingURL=babylon.renderingGroup.js.map
  16481. var BABYLON;
  16482. (function (BABYLON) {
  16483. var PointerEventTypes = (function () {
  16484. function PointerEventTypes() {
  16485. }
  16486. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16487. get: function () {
  16488. return PointerEventTypes._POINTERDOWN;
  16489. },
  16490. enumerable: true,
  16491. configurable: true
  16492. });
  16493. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16494. get: function () {
  16495. return PointerEventTypes._POINTERUP;
  16496. },
  16497. enumerable: true,
  16498. configurable: true
  16499. });
  16500. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16501. get: function () {
  16502. return PointerEventTypes._POINTERMOVE;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16508. get: function () {
  16509. return PointerEventTypes._POINTERWHEEL;
  16510. },
  16511. enumerable: true,
  16512. configurable: true
  16513. });
  16514. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16515. get: function () {
  16516. return PointerEventTypes._POINTERPICK;
  16517. },
  16518. enumerable: true,
  16519. configurable: true
  16520. });
  16521. return PointerEventTypes;
  16522. }());
  16523. PointerEventTypes._POINTERDOWN = 0x01;
  16524. PointerEventTypes._POINTERUP = 0x02;
  16525. PointerEventTypes._POINTERMOVE = 0x04;
  16526. PointerEventTypes._POINTERWHEEL = 0x08;
  16527. PointerEventTypes._POINTERPICK = 0x10;
  16528. BABYLON.PointerEventTypes = PointerEventTypes;
  16529. var PointerInfoBase = (function () {
  16530. function PointerInfoBase(type, event) {
  16531. this.type = type;
  16532. this.event = event;
  16533. }
  16534. return PointerInfoBase;
  16535. }());
  16536. BABYLON.PointerInfoBase = PointerInfoBase;
  16537. /**
  16538. * This class is used to store pointer related info for the onPrePointerObservable event.
  16539. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16540. */
  16541. var PointerInfoPre = (function (_super) {
  16542. __extends(PointerInfoPre, _super);
  16543. function PointerInfoPre(type, event, localX, localY) {
  16544. var _this = _super.call(this, type, event) || this;
  16545. _this.skipOnPointerObservable = false;
  16546. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16547. return _this;
  16548. }
  16549. return PointerInfoPre;
  16550. }(PointerInfoBase));
  16551. BABYLON.PointerInfoPre = PointerInfoPre;
  16552. /**
  16553. * This type contains all the data related to a pointer event in Babylon.js.
  16554. * 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.
  16555. */
  16556. var PointerInfo = (function (_super) {
  16557. __extends(PointerInfo, _super);
  16558. function PointerInfo(type, event, pickInfo) {
  16559. var _this = _super.call(this, type, event) || this;
  16560. _this.pickInfo = pickInfo;
  16561. return _this;
  16562. }
  16563. return PointerInfo;
  16564. }(PointerInfoBase));
  16565. BABYLON.PointerInfo = PointerInfo;
  16566. /**
  16567. * This class is used by the onRenderingGroupObservable
  16568. */
  16569. var RenderingGroupInfo = (function () {
  16570. function RenderingGroupInfo() {
  16571. }
  16572. return RenderingGroupInfo;
  16573. }());
  16574. /**
  16575. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16576. * This stage will be fired no matter what
  16577. */
  16578. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16579. /**
  16580. * Called before opaque object are rendered.
  16581. * This stage will be fired only if there's 3D Opaque content to render
  16582. */
  16583. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16584. /**
  16585. * Called after the opaque objects are rendered and before the transparent ones
  16586. * This stage will be fired only if there's 3D transparent content to render
  16587. */
  16588. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16589. /**
  16590. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16591. * This stage will be fired no matter what
  16592. */
  16593. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16594. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16595. /**
  16596. * Represents a scene to be rendered by the engine.
  16597. * @see http://doc.babylonjs.com/page.php?p=21911
  16598. */
  16599. var Scene = (function () {
  16600. /**
  16601. * @constructor
  16602. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16603. */
  16604. function Scene(engine) {
  16605. // Members
  16606. this.autoClear = true;
  16607. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16608. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16609. this.forceWireframe = false;
  16610. this.forcePointsCloud = false;
  16611. this.forceShowBoundingBoxes = false;
  16612. this.animationsEnabled = true;
  16613. this.constantlyUpdateMeshUnderPointer = false;
  16614. this.useRightHandedSystem = false;
  16615. this.hoverCursor = "pointer";
  16616. // Metadata
  16617. this.metadata = null;
  16618. // Events
  16619. /**
  16620. * An event triggered when the scene is disposed.
  16621. * @type {BABYLON.Observable}
  16622. */
  16623. this.onDisposeObservable = new BABYLON.Observable();
  16624. /**
  16625. * An event triggered before rendering the scene
  16626. * @type {BABYLON.Observable}
  16627. */
  16628. this.onBeforeRenderObservable = new BABYLON.Observable();
  16629. /**
  16630. * An event triggered after rendering the scene
  16631. * @type {BABYLON.Observable}
  16632. */
  16633. this.onAfterRenderObservable = new BABYLON.Observable();
  16634. /**
  16635. * An event triggered when the scene is ready
  16636. * @type {BABYLON.Observable}
  16637. */
  16638. this.onReadyObservable = new BABYLON.Observable();
  16639. /**
  16640. * An event triggered before rendering a camera
  16641. * @type {BABYLON.Observable}
  16642. */
  16643. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16644. /**
  16645. * An event triggered after rendering a camera
  16646. * @type {BABYLON.Observable}
  16647. */
  16648. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16649. /**
  16650. * An event triggered when a camera is created
  16651. * @type {BABYLON.Observable}
  16652. */
  16653. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16654. /**
  16655. * An event triggered when a camera is removed
  16656. * @type {BABYLON.Observable}
  16657. */
  16658. this.onCameraRemovedObservable = new BABYLON.Observable();
  16659. /**
  16660. * An event triggered when a light is created
  16661. * @type {BABYLON.Observable}
  16662. */
  16663. this.onNewLightAddedObservable = new BABYLON.Observable();
  16664. /**
  16665. * An event triggered when a light is removed
  16666. * @type {BABYLON.Observable}
  16667. */
  16668. this.onLightRemovedObservable = new BABYLON.Observable();
  16669. /**
  16670. * An event triggered when a geometry is created
  16671. * @type {BABYLON.Observable}
  16672. */
  16673. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16674. /**
  16675. * An event triggered when a geometry is removed
  16676. * @type {BABYLON.Observable}
  16677. */
  16678. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16679. /**
  16680. * An event triggered when a mesh is created
  16681. * @type {BABYLON.Observable}
  16682. */
  16683. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16684. /**
  16685. * An event triggered when a mesh is removed
  16686. * @type {BABYLON.Observable}
  16687. */
  16688. this.onMeshRemovedObservable = new BABYLON.Observable();
  16689. /**
  16690. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16691. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16692. * 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)
  16693. */
  16694. this.onRenderingGroupObservable = new BABYLON.Observable();
  16695. // Animations
  16696. this.animations = [];
  16697. /**
  16698. * 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).
  16699. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16700. */
  16701. this.onPrePointerObservable = new BABYLON.Observable();
  16702. /**
  16703. * Observable event triggered each time an input event is received from the rendering canvas
  16704. */
  16705. this.onPointerObservable = new BABYLON.Observable();
  16706. 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
  16707. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16708. this._startingPointerTime = 0;
  16709. // Fog
  16710. /**
  16711. * is fog enabled on this scene.
  16712. * @type {boolean}
  16713. */
  16714. this.fogEnabled = true;
  16715. this.fogMode = Scene.FOGMODE_NONE;
  16716. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16717. this.fogDensity = 0.1;
  16718. this.fogStart = 0;
  16719. this.fogEnd = 1000.0;
  16720. // Lights
  16721. /**
  16722. * is shadow enabled on this scene.
  16723. * @type {boolean}
  16724. */
  16725. this.shadowsEnabled = true;
  16726. /**
  16727. * is light enabled on this scene.
  16728. * @type {boolean}
  16729. */
  16730. this.lightsEnabled = true;
  16731. /**
  16732. * All of the lights added to this scene.
  16733. * @see BABYLON.Light
  16734. * @type {BABYLON.Light[]}
  16735. */
  16736. this.lights = new Array();
  16737. // Cameras
  16738. /**
  16739. * All of the cameras added to this scene.
  16740. * @see BABYLON.Camera
  16741. * @type {BABYLON.Camera[]}
  16742. */
  16743. this.cameras = new Array();
  16744. this.activeCameras = new Array();
  16745. // Meshes
  16746. /**
  16747. * All of the (abstract) meshes added to this scene.
  16748. * @see BABYLON.AbstractMesh
  16749. * @type {BABYLON.AbstractMesh[]}
  16750. */
  16751. this.meshes = new Array();
  16752. // Geometries
  16753. this._geometries = new Array();
  16754. this.materials = new Array();
  16755. this.multiMaterials = new Array();
  16756. // Textures
  16757. this.texturesEnabled = true;
  16758. this.textures = new Array();
  16759. // Particles
  16760. this.particlesEnabled = true;
  16761. this.particleSystems = new Array();
  16762. // Sprites
  16763. this.spritesEnabled = true;
  16764. this.spriteManagers = new Array();
  16765. // Layers
  16766. this.layers = new Array();
  16767. this.highlightLayers = new Array();
  16768. // Skeletons
  16769. this.skeletonsEnabled = true;
  16770. this.skeletons = new Array();
  16771. // Lens flares
  16772. this.lensFlaresEnabled = true;
  16773. this.lensFlareSystems = new Array();
  16774. // Collisions
  16775. this.collisionsEnabled = true;
  16776. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16777. // Postprocesses
  16778. this.postProcessesEnabled = true;
  16779. // Customs render targets
  16780. this.renderTargetsEnabled = true;
  16781. this.dumpNextRenderTargets = false;
  16782. this.customRenderTargets = new Array();
  16783. // Imported meshes
  16784. this.importedMeshesFiles = new Array();
  16785. // Probes
  16786. this.probesEnabled = true;
  16787. this.reflectionProbes = new Array();
  16788. this._actionManagers = new Array();
  16789. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16790. // Procedural textures
  16791. this.proceduralTexturesEnabled = true;
  16792. this._proceduralTextures = new Array();
  16793. this.soundTracks = new Array();
  16794. this._audioEnabled = true;
  16795. this._headphone = false;
  16796. // Performance counters
  16797. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16798. this._totalLightsCounter = new BABYLON.PerfCounter();
  16799. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16800. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16801. this._totalVertices = new BABYLON.PerfCounter();
  16802. this._activeIndices = new BABYLON.PerfCounter();
  16803. this._activeParticles = new BABYLON.PerfCounter();
  16804. this._lastFrameDuration = new BABYLON.PerfCounter();
  16805. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16806. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16807. this._particlesDuration = new BABYLON.PerfCounter();
  16808. this._renderDuration = new BABYLON.PerfCounter();
  16809. this._spritesDuration = new BABYLON.PerfCounter();
  16810. this._activeBones = new BABYLON.PerfCounter();
  16811. this._renderId = 0;
  16812. this._executeWhenReadyTimeoutId = -1;
  16813. this._intermediateRendering = false;
  16814. this._toBeDisposed = new BABYLON.SmartArray(256);
  16815. this._pendingData = []; //ANY
  16816. this._activeMeshes = new BABYLON.SmartArray(256);
  16817. this._processedMaterials = new BABYLON.SmartArray(256);
  16818. this._renderTargets = new BABYLON.SmartArray(256);
  16819. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16820. this._activeSkeletons = new BABYLON.SmartArray(32);
  16821. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16822. this._activeAnimatables = new Array();
  16823. this._transformMatrix = BABYLON.Matrix.Zero();
  16824. this._edgesRenderers = new BABYLON.SmartArray(16);
  16825. this._uniqueIdCounter = 0;
  16826. this._engine = engine;
  16827. engine.scenes.push(this);
  16828. this._externalData = new BABYLON.StringDictionary();
  16829. this._uid = null;
  16830. this._renderingManager = new BABYLON.RenderingManager(this);
  16831. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16832. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16833. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16834. if (BABYLON.OutlineRenderer) {
  16835. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16836. }
  16837. this.attachControl();
  16838. if (BABYLON.SoundTrack) {
  16839. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16840. }
  16841. //simplification queue
  16842. if (BABYLON.SimplificationQueue) {
  16843. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16844. }
  16845. //collision coordinator initialization. For now legacy per default.
  16846. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16847. }
  16848. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16849. get: function () {
  16850. return Scene._FOGMODE_NONE;
  16851. },
  16852. enumerable: true,
  16853. configurable: true
  16854. });
  16855. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16856. get: function () {
  16857. return Scene._FOGMODE_EXP;
  16858. },
  16859. enumerable: true,
  16860. configurable: true
  16861. });
  16862. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16863. get: function () {
  16864. return Scene._FOGMODE_EXP2;
  16865. },
  16866. enumerable: true,
  16867. configurable: true
  16868. });
  16869. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16870. get: function () {
  16871. return Scene._FOGMODE_LINEAR;
  16872. },
  16873. enumerable: true,
  16874. configurable: true
  16875. });
  16876. Object.defineProperty(Scene.prototype, "onDispose", {
  16877. set: function (callback) {
  16878. if (this._onDisposeObserver) {
  16879. this.onDisposeObservable.remove(this._onDisposeObserver);
  16880. }
  16881. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16882. },
  16883. enumerable: true,
  16884. configurable: true
  16885. });
  16886. Object.defineProperty(Scene.prototype, "beforeRender", {
  16887. set: function (callback) {
  16888. if (this._onBeforeRenderObserver) {
  16889. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16890. }
  16891. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16892. },
  16893. enumerable: true,
  16894. configurable: true
  16895. });
  16896. Object.defineProperty(Scene.prototype, "afterRender", {
  16897. set: function (callback) {
  16898. if (this._onAfterRenderObserver) {
  16899. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16900. }
  16901. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16902. },
  16903. enumerable: true,
  16904. configurable: true
  16905. });
  16906. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16907. set: function (callback) {
  16908. if (this._onBeforeCameraRenderObserver) {
  16909. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16910. }
  16911. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16912. },
  16913. enumerable: true,
  16914. configurable: true
  16915. });
  16916. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16917. set: function (callback) {
  16918. if (this._onAfterCameraRenderObserver) {
  16919. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16920. }
  16921. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16922. },
  16923. enumerable: true,
  16924. configurable: true
  16925. });
  16926. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16927. get: function () {
  16928. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16929. },
  16930. enumerable: true,
  16931. configurable: true
  16932. });
  16933. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16934. get: function () {
  16935. if (!this._defaultMaterial) {
  16936. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16937. }
  16938. return this._defaultMaterial;
  16939. },
  16940. enumerable: true,
  16941. configurable: true
  16942. });
  16943. Object.defineProperty(Scene.prototype, "debugLayer", {
  16944. // Properties
  16945. get: function () {
  16946. if (!this._debugLayer) {
  16947. this._debugLayer = new BABYLON.DebugLayer(this);
  16948. }
  16949. return this._debugLayer;
  16950. },
  16951. enumerable: true,
  16952. configurable: true
  16953. });
  16954. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16955. get: function () {
  16956. return this._workerCollisions;
  16957. },
  16958. set: function (enabled) {
  16959. enabled = (enabled && !!Worker);
  16960. this._workerCollisions = enabled;
  16961. if (this.collisionCoordinator) {
  16962. this.collisionCoordinator.destroy();
  16963. }
  16964. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16965. this.collisionCoordinator.init(this);
  16966. },
  16967. enumerable: true,
  16968. configurable: true
  16969. });
  16970. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16971. get: function () {
  16972. return this._selectionOctree;
  16973. },
  16974. enumerable: true,
  16975. configurable: true
  16976. });
  16977. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16978. /**
  16979. * The mesh that is currently under the pointer.
  16980. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16981. */
  16982. get: function () {
  16983. return this._pointerOverMesh;
  16984. },
  16985. enumerable: true,
  16986. configurable: true
  16987. });
  16988. Object.defineProperty(Scene.prototype, "pointerX", {
  16989. /**
  16990. * Current on-screen X position of the pointer
  16991. * @return {number} X position of the pointer
  16992. */
  16993. get: function () {
  16994. return this._pointerX;
  16995. },
  16996. enumerable: true,
  16997. configurable: true
  16998. });
  16999. Object.defineProperty(Scene.prototype, "pointerY", {
  17000. /**
  17001. * Current on-screen Y position of the pointer
  17002. * @return {number} Y position of the pointer
  17003. */
  17004. get: function () {
  17005. return this._pointerY;
  17006. },
  17007. enumerable: true,
  17008. configurable: true
  17009. });
  17010. Scene.prototype.getCachedMaterial = function () {
  17011. return this._cachedMaterial;
  17012. };
  17013. Scene.prototype.getBoundingBoxRenderer = function () {
  17014. return this._boundingBoxRenderer;
  17015. };
  17016. Scene.prototype.getOutlineRenderer = function () {
  17017. return this._outlineRenderer;
  17018. };
  17019. Scene.prototype.getEngine = function () {
  17020. return this._engine;
  17021. };
  17022. Scene.prototype.getTotalVertices = function () {
  17023. return this._totalVertices.current;
  17024. };
  17025. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17026. get: function () {
  17027. return this._totalVertices;
  17028. },
  17029. enumerable: true,
  17030. configurable: true
  17031. });
  17032. Scene.prototype.getActiveIndices = function () {
  17033. return this._activeIndices.current;
  17034. };
  17035. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17036. get: function () {
  17037. return this._activeIndices;
  17038. },
  17039. enumerable: true,
  17040. configurable: true
  17041. });
  17042. Scene.prototype.getActiveParticles = function () {
  17043. return this._activeParticles.current;
  17044. };
  17045. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17046. get: function () {
  17047. return this._activeParticles;
  17048. },
  17049. enumerable: true,
  17050. configurable: true
  17051. });
  17052. Scene.prototype.getActiveBones = function () {
  17053. return this._activeBones.current;
  17054. };
  17055. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17056. get: function () {
  17057. return this._activeBones;
  17058. },
  17059. enumerable: true,
  17060. configurable: true
  17061. });
  17062. // Stats
  17063. Scene.prototype.getLastFrameDuration = function () {
  17064. return this._lastFrameDuration.current;
  17065. };
  17066. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17067. get: function () {
  17068. return this._lastFrameDuration;
  17069. },
  17070. enumerable: true,
  17071. configurable: true
  17072. });
  17073. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17074. return this._evaluateActiveMeshesDuration.current;
  17075. };
  17076. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17077. get: function () {
  17078. return this._evaluateActiveMeshesDuration;
  17079. },
  17080. enumerable: true,
  17081. configurable: true
  17082. });
  17083. Scene.prototype.getActiveMeshes = function () {
  17084. return this._activeMeshes;
  17085. };
  17086. Scene.prototype.getRenderTargetsDuration = function () {
  17087. return this._renderTargetsDuration.current;
  17088. };
  17089. Scene.prototype.getRenderDuration = function () {
  17090. return this._renderDuration.current;
  17091. };
  17092. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17093. get: function () {
  17094. return this._renderDuration;
  17095. },
  17096. enumerable: true,
  17097. configurable: true
  17098. });
  17099. Scene.prototype.getParticlesDuration = function () {
  17100. return this._particlesDuration.current;
  17101. };
  17102. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17103. get: function () {
  17104. return this._particlesDuration;
  17105. },
  17106. enumerable: true,
  17107. configurable: true
  17108. });
  17109. Scene.prototype.getSpritesDuration = function () {
  17110. return this._spritesDuration.current;
  17111. };
  17112. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17113. get: function () {
  17114. return this._spritesDuration;
  17115. },
  17116. enumerable: true,
  17117. configurable: true
  17118. });
  17119. Scene.prototype.getAnimationRatio = function () {
  17120. return this._animationRatio;
  17121. };
  17122. Scene.prototype.getRenderId = function () {
  17123. return this._renderId;
  17124. };
  17125. Scene.prototype.incrementRenderId = function () {
  17126. this._renderId++;
  17127. };
  17128. Scene.prototype._updatePointerPosition = function (evt) {
  17129. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17130. this._pointerX = evt.clientX - canvasRect.left;
  17131. this._pointerY = evt.clientY - canvasRect.top;
  17132. this._unTranslatedPointerX = this._pointerX;
  17133. this._unTranslatedPointerY = this._pointerY;
  17134. if (this.cameraToUseForPointers) {
  17135. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17136. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17137. }
  17138. };
  17139. // Pointers handling
  17140. /**
  17141. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17142. * @param attachUp defines if you want to attach events to pointerup
  17143. * @param attachDown defines if you want to attach events to pointerdown
  17144. * @param attachMove defines if you want to attach events to pointermove
  17145. */
  17146. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17147. var _this = this;
  17148. if (attachUp === void 0) { attachUp = true; }
  17149. if (attachDown === void 0) { attachDown = true; }
  17150. if (attachMove === void 0) { attachMove = true; }
  17151. var spritePredicate = function (sprite) {
  17152. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17153. };
  17154. this._onPointerMove = function (evt) {
  17155. _this._updatePointerPosition(evt);
  17156. // PreObservable support
  17157. if (_this.onPrePointerObservable.hasObservers()) {
  17158. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17159. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17160. _this.onPrePointerObservable.notifyObservers(pi, type);
  17161. if (pi.skipOnPointerObservable) {
  17162. return;
  17163. }
  17164. }
  17165. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17166. return;
  17167. }
  17168. var canvas = _this._engine.getRenderingCanvas();
  17169. if (!_this.pointerMovePredicate) {
  17170. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17171. }
  17172. // Meshes
  17173. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17174. if (pickResult.hit && pickResult.pickedMesh) {
  17175. _this.setPointerOverSprite(null);
  17176. _this.setPointerOverMesh(pickResult.pickedMesh);
  17177. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17178. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17179. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17180. }
  17181. else {
  17182. canvas.style.cursor = _this.hoverCursor;
  17183. }
  17184. }
  17185. else {
  17186. canvas.style.cursor = "";
  17187. }
  17188. }
  17189. else {
  17190. _this.setPointerOverMesh(null);
  17191. // Sprites
  17192. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17193. if (pickResult.hit && pickResult.pickedSprite) {
  17194. _this.setPointerOverSprite(pickResult.pickedSprite);
  17195. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17196. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17197. }
  17198. else {
  17199. canvas.style.cursor = _this.hoverCursor;
  17200. }
  17201. }
  17202. else {
  17203. _this.setPointerOverSprite(null);
  17204. // Restore pointer
  17205. canvas.style.cursor = "";
  17206. }
  17207. }
  17208. if (_this.onPointerMove) {
  17209. _this.onPointerMove(evt, pickResult);
  17210. }
  17211. if (_this.onPointerObservable.hasObservers()) {
  17212. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17213. var pi = new PointerInfo(type, evt, pickResult);
  17214. _this.onPointerObservable.notifyObservers(pi, type);
  17215. }
  17216. };
  17217. this._onPointerDown = function (evt) {
  17218. _this._updatePointerPosition(evt);
  17219. // PreObservable support
  17220. if (_this.onPrePointerObservable.hasObservers()) {
  17221. var type = PointerEventTypes.POINTERDOWN;
  17222. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17223. _this.onPrePointerObservable.notifyObservers(pi, type);
  17224. if (pi.skipOnPointerObservable) {
  17225. return;
  17226. }
  17227. }
  17228. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17229. return;
  17230. }
  17231. _this._startingPointerPosition.x = _this._pointerX;
  17232. _this._startingPointerPosition.y = _this._pointerY;
  17233. _this._startingPointerTime = new Date().getTime();
  17234. if (!_this.pointerDownPredicate) {
  17235. _this.pointerDownPredicate = function (mesh) {
  17236. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17237. };
  17238. }
  17239. // Meshes
  17240. _this._pickedDownMesh = null;
  17241. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17242. if (pickResult.hit && pickResult.pickedMesh) {
  17243. if (pickResult.pickedMesh.actionManager) {
  17244. _this._pickedDownMesh = pickResult.pickedMesh;
  17245. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17246. switch (evt.button) {
  17247. case 0:
  17248. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17249. break;
  17250. case 1:
  17251. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17252. break;
  17253. case 2:
  17254. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17255. break;
  17256. }
  17257. if (pickResult.pickedMesh.actionManager) {
  17258. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17259. }
  17260. }
  17261. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17262. var that = _this;
  17263. window.setTimeout(function () {
  17264. 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);
  17265. if (pickResult.hit && pickResult.pickedMesh) {
  17266. if (pickResult.pickedMesh.actionManager) {
  17267. 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)) {
  17268. that._startingPointerTime = 0;
  17269. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17270. }
  17271. }
  17272. }
  17273. }, BABYLON.ActionManager.LongPressDelay);
  17274. }
  17275. }
  17276. }
  17277. if (_this.onPointerDown) {
  17278. _this.onPointerDown(evt, pickResult);
  17279. }
  17280. if (_this.onPointerObservable.hasObservers()) {
  17281. var type = PointerEventTypes.POINTERDOWN;
  17282. var pi = new PointerInfo(type, evt, pickResult);
  17283. _this.onPointerObservable.notifyObservers(pi, type);
  17284. }
  17285. // Sprites
  17286. _this._pickedDownSprite = null;
  17287. if (_this.spriteManagers.length > 0) {
  17288. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17289. if (pickResult.hit && pickResult.pickedSprite) {
  17290. if (pickResult.pickedSprite.actionManager) {
  17291. _this._pickedDownSprite = pickResult.pickedSprite;
  17292. switch (evt.button) {
  17293. case 0:
  17294. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17295. break;
  17296. case 1:
  17297. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17298. break;
  17299. case 2:
  17300. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17301. break;
  17302. }
  17303. if (pickResult.pickedSprite.actionManager) {
  17304. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17305. }
  17306. }
  17307. }
  17308. }
  17309. };
  17310. this._onPointerUp = function (evt) {
  17311. _this._updatePointerPosition(evt);
  17312. // PreObservable support
  17313. if (_this.onPrePointerObservable.hasObservers()) {
  17314. var type = PointerEventTypes.POINTERUP;
  17315. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17316. _this.onPrePointerObservable.notifyObservers(pi, type);
  17317. if (pi.skipOnPointerObservable) {
  17318. return;
  17319. }
  17320. }
  17321. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17322. return;
  17323. }
  17324. if (!_this.pointerUpPredicate) {
  17325. _this.pointerUpPredicate = function (mesh) {
  17326. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17327. };
  17328. }
  17329. // Meshes
  17330. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17331. if (pickResult.hit && pickResult.pickedMesh) {
  17332. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17333. if (_this.onPointerPick) {
  17334. _this.onPointerPick(evt, pickResult);
  17335. }
  17336. if (_this.onPointerObservable.hasObservers()) {
  17337. var type = PointerEventTypes.POINTERPICK;
  17338. var pi = new PointerInfo(type, evt, pickResult);
  17339. _this.onPointerObservable.notifyObservers(pi, type);
  17340. }
  17341. }
  17342. if (pickResult.pickedMesh.actionManager) {
  17343. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17344. if (pickResult.pickedMesh.actionManager) {
  17345. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17346. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17347. }
  17348. }
  17349. }
  17350. }
  17351. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17352. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17353. }
  17354. if (_this.onPointerUp) {
  17355. _this.onPointerUp(evt, pickResult);
  17356. }
  17357. if (_this.onPointerObservable.hasObservers()) {
  17358. var type = PointerEventTypes.POINTERUP;
  17359. var pi = new PointerInfo(type, evt, pickResult);
  17360. _this.onPointerObservable.notifyObservers(pi, type);
  17361. }
  17362. _this._startingPointerTime = 0;
  17363. // Sprites
  17364. if (_this.spriteManagers.length > 0) {
  17365. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17366. if (pickResult.hit && pickResult.pickedSprite) {
  17367. if (pickResult.pickedSprite.actionManager) {
  17368. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17369. if (pickResult.pickedSprite.actionManager) {
  17370. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17371. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17372. }
  17373. }
  17374. }
  17375. }
  17376. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17377. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17378. }
  17379. }
  17380. };
  17381. this._onKeyDown = function (evt) {
  17382. if (_this.actionManager) {
  17383. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17384. }
  17385. };
  17386. this._onKeyUp = function (evt) {
  17387. if (_this.actionManager) {
  17388. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17389. }
  17390. };
  17391. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17392. var canvas = this._engine.getRenderingCanvas();
  17393. if (attachMove) {
  17394. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17395. // Wheel
  17396. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17397. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17398. }
  17399. if (attachDown) {
  17400. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17401. }
  17402. if (attachUp) {
  17403. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17404. }
  17405. canvas.tabIndex = 1;
  17406. canvas.addEventListener("keydown", this._onKeyDown, false);
  17407. canvas.addEventListener("keyup", this._onKeyUp, false);
  17408. };
  17409. Scene.prototype.detachControl = function () {
  17410. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17411. var canvas = this._engine.getRenderingCanvas();
  17412. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17413. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17414. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17415. // Wheel
  17416. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17417. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17418. canvas.removeEventListener("keydown", this._onKeyDown);
  17419. canvas.removeEventListener("keyup", this._onKeyUp);
  17420. };
  17421. // Ready
  17422. Scene.prototype.isReady = function () {
  17423. if (this._pendingData.length > 0) {
  17424. return false;
  17425. }
  17426. var index;
  17427. for (index = 0; index < this._geometries.length; index++) {
  17428. var geometry = this._geometries[index];
  17429. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17430. return false;
  17431. }
  17432. }
  17433. for (index = 0; index < this.meshes.length; index++) {
  17434. var mesh = this.meshes[index];
  17435. if (!mesh.isReady()) {
  17436. return false;
  17437. }
  17438. var mat = mesh.material;
  17439. if (mat) {
  17440. if (!mat.isReady(mesh)) {
  17441. return false;
  17442. }
  17443. }
  17444. }
  17445. return true;
  17446. };
  17447. Scene.prototype.resetCachedMaterial = function () {
  17448. this._cachedMaterial = null;
  17449. };
  17450. Scene.prototype.registerBeforeRender = function (func) {
  17451. this.onBeforeRenderObservable.add(func);
  17452. };
  17453. Scene.prototype.unregisterBeforeRender = function (func) {
  17454. this.onBeforeRenderObservable.removeCallback(func);
  17455. };
  17456. Scene.prototype.registerAfterRender = function (func) {
  17457. this.onAfterRenderObservable.add(func);
  17458. };
  17459. Scene.prototype.unregisterAfterRender = function (func) {
  17460. this.onAfterRenderObservable.removeCallback(func);
  17461. };
  17462. Scene.prototype._addPendingData = function (data) {
  17463. this._pendingData.push(data);
  17464. };
  17465. Scene.prototype._removePendingData = function (data) {
  17466. var index = this._pendingData.indexOf(data);
  17467. if (index !== -1) {
  17468. this._pendingData.splice(index, 1);
  17469. }
  17470. };
  17471. Scene.prototype.getWaitingItemsCount = function () {
  17472. return this._pendingData.length;
  17473. };
  17474. /**
  17475. * Registers a function to be executed when the scene is ready.
  17476. * @param {Function} func - the function to be executed.
  17477. */
  17478. Scene.prototype.executeWhenReady = function (func) {
  17479. var _this = this;
  17480. this.onReadyObservable.add(func);
  17481. if (this._executeWhenReadyTimeoutId !== -1) {
  17482. return;
  17483. }
  17484. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17485. _this._checkIsReady();
  17486. }, 150);
  17487. };
  17488. Scene.prototype._checkIsReady = function () {
  17489. var _this = this;
  17490. if (this.isReady()) {
  17491. this.onReadyObservable.notifyObservers(this);
  17492. this.onReadyObservable.clear();
  17493. this._executeWhenReadyTimeoutId = -1;
  17494. return;
  17495. }
  17496. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17497. _this._checkIsReady();
  17498. }, 150);
  17499. };
  17500. // Animations
  17501. /**
  17502. * Will start the animation sequence of a given target
  17503. * @param target - the target
  17504. * @param {number} from - from which frame should animation start
  17505. * @param {number} to - till which frame should animation run.
  17506. * @param {boolean} [loop] - should the animation loop
  17507. * @param {number} [speedRatio] - the speed in which to run the animation
  17508. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17509. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17510. * @return {BABYLON.Animatable} the animatable object created for this animation
  17511. * @see BABYLON.Animatable
  17512. * @see http://doc.babylonjs.com/page.php?p=22081
  17513. */
  17514. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17515. if (speedRatio === void 0) { speedRatio = 1.0; }
  17516. this.stopAnimation(target);
  17517. if (!animatable) {
  17518. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17519. }
  17520. // Local animations
  17521. if (target.animations) {
  17522. animatable.appendAnimations(target, target.animations);
  17523. }
  17524. // Children animations
  17525. if (target.getAnimatables) {
  17526. var animatables = target.getAnimatables();
  17527. for (var index = 0; index < animatables.length; index++) {
  17528. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17529. }
  17530. }
  17531. animatable.reset();
  17532. return animatable;
  17533. };
  17534. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17535. if (speedRatio === undefined) {
  17536. speedRatio = 1.0;
  17537. }
  17538. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17539. return animatable;
  17540. };
  17541. Scene.prototype.getAnimatableByTarget = function (target) {
  17542. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17543. if (this._activeAnimatables[index].target === target) {
  17544. return this._activeAnimatables[index];
  17545. }
  17546. }
  17547. return null;
  17548. };
  17549. Object.defineProperty(Scene.prototype, "Animatables", {
  17550. get: function () {
  17551. return this._activeAnimatables;
  17552. },
  17553. enumerable: true,
  17554. configurable: true
  17555. });
  17556. /**
  17557. * Will stop the animation of the given target
  17558. * @param target - the target
  17559. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17560. * @see beginAnimation
  17561. */
  17562. Scene.prototype.stopAnimation = function (target, animationName) {
  17563. var animatable = this.getAnimatableByTarget(target);
  17564. if (animatable) {
  17565. animatable.stop(animationName);
  17566. }
  17567. };
  17568. Scene.prototype._animate = function () {
  17569. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17570. return;
  17571. }
  17572. if (!this._animationStartDate) {
  17573. if (this._pendingData.length > 0) {
  17574. return;
  17575. }
  17576. this._animationStartDate = BABYLON.Tools.Now;
  17577. }
  17578. // Getting time
  17579. var now = BABYLON.Tools.Now;
  17580. var delay = now - this._animationStartDate;
  17581. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17582. this._activeAnimatables[index]._animate(delay);
  17583. }
  17584. };
  17585. // Matrix
  17586. Scene.prototype.getViewMatrix = function () {
  17587. return this._viewMatrix;
  17588. };
  17589. Scene.prototype.getProjectionMatrix = function () {
  17590. return this._projectionMatrix;
  17591. };
  17592. Scene.prototype.getTransformMatrix = function () {
  17593. return this._transformMatrix;
  17594. };
  17595. Scene.prototype.setTransformMatrix = function (view, projection) {
  17596. this._viewMatrix = view;
  17597. this._projectionMatrix = projection;
  17598. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17599. // Update frustum
  17600. if (!this._frustumPlanes) {
  17601. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17602. }
  17603. else {
  17604. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17605. }
  17606. };
  17607. // Methods
  17608. Scene.prototype.addMesh = function (newMesh) {
  17609. newMesh.uniqueId = this._uniqueIdCounter++;
  17610. var position = this.meshes.push(newMesh);
  17611. //notify the collision coordinator
  17612. this.collisionCoordinator.onMeshAdded(newMesh);
  17613. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17614. };
  17615. Scene.prototype.removeMesh = function (toRemove) {
  17616. var index = this.meshes.indexOf(toRemove);
  17617. if (index !== -1) {
  17618. // Remove from the scene if mesh found
  17619. this.meshes.splice(index, 1);
  17620. }
  17621. //notify the collision coordinator
  17622. this.collisionCoordinator.onMeshRemoved(toRemove);
  17623. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17624. return index;
  17625. };
  17626. Scene.prototype.removeSkeleton = function (toRemove) {
  17627. var index = this.skeletons.indexOf(toRemove);
  17628. if (index !== -1) {
  17629. // Remove from the scene if mesh found
  17630. this.skeletons.splice(index, 1);
  17631. }
  17632. return index;
  17633. };
  17634. Scene.prototype.removeLight = function (toRemove) {
  17635. var index = this.lights.indexOf(toRemove);
  17636. if (index !== -1) {
  17637. // Remove from the scene if mesh found
  17638. this.lights.splice(index, 1);
  17639. }
  17640. this.onLightRemovedObservable.notifyObservers(toRemove);
  17641. return index;
  17642. };
  17643. Scene.prototype.removeCamera = function (toRemove) {
  17644. var index = this.cameras.indexOf(toRemove);
  17645. if (index !== -1) {
  17646. // Remove from the scene if mesh found
  17647. this.cameras.splice(index, 1);
  17648. }
  17649. // Remove from activeCameras
  17650. var index2 = this.activeCameras.indexOf(toRemove);
  17651. if (index2 !== -1) {
  17652. // Remove from the scene if mesh found
  17653. this.activeCameras.splice(index2, 1);
  17654. }
  17655. // Reset the activeCamera
  17656. if (this.activeCamera === toRemove) {
  17657. if (this.cameras.length > 0) {
  17658. this.activeCamera = this.cameras[0];
  17659. }
  17660. else {
  17661. this.activeCamera = null;
  17662. }
  17663. }
  17664. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17665. return index;
  17666. };
  17667. Scene.prototype.addLight = function (newLight) {
  17668. newLight.uniqueId = this._uniqueIdCounter++;
  17669. var position = this.lights.push(newLight);
  17670. this.onNewLightAddedObservable.notifyObservers(newLight);
  17671. };
  17672. Scene.prototype.addCamera = function (newCamera) {
  17673. newCamera.uniqueId = this._uniqueIdCounter++;
  17674. var position = this.cameras.push(newCamera);
  17675. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17676. };
  17677. /**
  17678. * Switch active camera
  17679. * @param {Camera} newCamera - new active camera
  17680. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17681. */
  17682. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17683. if (attachControl === void 0) { attachControl = true; }
  17684. var canvas = this._engine.getRenderingCanvas();
  17685. this.activeCamera.detachControl(canvas);
  17686. this.activeCamera = newCamera;
  17687. if (attachControl) {
  17688. newCamera.attachControl(canvas);
  17689. }
  17690. };
  17691. /**
  17692. * sets the active camera of the scene using its ID
  17693. * @param {string} id - the camera's ID
  17694. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17695. * @see activeCamera
  17696. */
  17697. Scene.prototype.setActiveCameraByID = function (id) {
  17698. var camera = this.getCameraByID(id);
  17699. if (camera) {
  17700. this.activeCamera = camera;
  17701. return camera;
  17702. }
  17703. return null;
  17704. };
  17705. /**
  17706. * sets the active camera of the scene using its name
  17707. * @param {string} name - the camera's name
  17708. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17709. * @see activeCamera
  17710. */
  17711. Scene.prototype.setActiveCameraByName = function (name) {
  17712. var camera = this.getCameraByName(name);
  17713. if (camera) {
  17714. this.activeCamera = camera;
  17715. return camera;
  17716. }
  17717. return null;
  17718. };
  17719. /**
  17720. * get a material using its id
  17721. * @param {string} the material's ID
  17722. * @return {BABYLON.Material|null} the material or null if none found.
  17723. */
  17724. Scene.prototype.getMaterialByID = function (id) {
  17725. for (var index = 0; index < this.materials.length; index++) {
  17726. if (this.materials[index].id === id) {
  17727. return this.materials[index];
  17728. }
  17729. }
  17730. return null;
  17731. };
  17732. /**
  17733. * get a material using its name
  17734. * @param {string} the material's name
  17735. * @return {BABYLON.Material|null} the material or null if none found.
  17736. */
  17737. Scene.prototype.getMaterialByName = function (name) {
  17738. for (var index = 0; index < this.materials.length; index++) {
  17739. if (this.materials[index].name === name) {
  17740. return this.materials[index];
  17741. }
  17742. }
  17743. return null;
  17744. };
  17745. Scene.prototype.getLensFlareSystemByName = function (name) {
  17746. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17747. if (this.lensFlareSystems[index].name === name) {
  17748. return this.lensFlareSystems[index];
  17749. }
  17750. }
  17751. return null;
  17752. };
  17753. Scene.prototype.getLensFlareSystemByID = function (id) {
  17754. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17755. if (this.lensFlareSystems[index].id === id) {
  17756. return this.lensFlareSystems[index];
  17757. }
  17758. }
  17759. return null;
  17760. };
  17761. Scene.prototype.getCameraByID = function (id) {
  17762. for (var index = 0; index < this.cameras.length; index++) {
  17763. if (this.cameras[index].id === id) {
  17764. return this.cameras[index];
  17765. }
  17766. }
  17767. return null;
  17768. };
  17769. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17770. for (var index = 0; index < this.cameras.length; index++) {
  17771. if (this.cameras[index].uniqueId === uniqueId) {
  17772. return this.cameras[index];
  17773. }
  17774. }
  17775. return null;
  17776. };
  17777. /**
  17778. * get a camera using its name
  17779. * @param {string} the camera's name
  17780. * @return {BABYLON.Camera|null} the camera or null if none found.
  17781. */
  17782. Scene.prototype.getCameraByName = function (name) {
  17783. for (var index = 0; index < this.cameras.length; index++) {
  17784. if (this.cameras[index].name === name) {
  17785. return this.cameras[index];
  17786. }
  17787. }
  17788. return null;
  17789. };
  17790. /**
  17791. * get a bone using its id
  17792. * @param {string} the bone's id
  17793. * @return {BABYLON.Bone|null} the bone or null if not found
  17794. */
  17795. Scene.prototype.getBoneByID = function (id) {
  17796. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17797. var skeleton = this.skeletons[skeletonIndex];
  17798. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17799. if (skeleton.bones[boneIndex].id === id) {
  17800. return skeleton.bones[boneIndex];
  17801. }
  17802. }
  17803. }
  17804. return null;
  17805. };
  17806. /**
  17807. * get a bone using its id
  17808. * @param {string} the bone's name
  17809. * @return {BABYLON.Bone|null} the bone or null if not found
  17810. */
  17811. Scene.prototype.getBoneByName = function (name) {
  17812. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17813. var skeleton = this.skeletons[skeletonIndex];
  17814. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17815. if (skeleton.bones[boneIndex].name === name) {
  17816. return skeleton.bones[boneIndex];
  17817. }
  17818. }
  17819. }
  17820. return null;
  17821. };
  17822. /**
  17823. * get a light node using its name
  17824. * @param {string} the light's name
  17825. * @return {BABYLON.Light|null} the light or null if none found.
  17826. */
  17827. Scene.prototype.getLightByName = function (name) {
  17828. for (var index = 0; index < this.lights.length; index++) {
  17829. if (this.lights[index].name === name) {
  17830. return this.lights[index];
  17831. }
  17832. }
  17833. return null;
  17834. };
  17835. /**
  17836. * get a light node using its ID
  17837. * @param {string} the light's id
  17838. * @return {BABYLON.Light|null} the light or null if none found.
  17839. */
  17840. Scene.prototype.getLightByID = function (id) {
  17841. for (var index = 0; index < this.lights.length; index++) {
  17842. if (this.lights[index].id === id) {
  17843. return this.lights[index];
  17844. }
  17845. }
  17846. return null;
  17847. };
  17848. /**
  17849. * get a light node using its scene-generated unique ID
  17850. * @param {number} the light's unique id
  17851. * @return {BABYLON.Light|null} the light or null if none found.
  17852. */
  17853. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17854. for (var index = 0; index < this.lights.length; index++) {
  17855. if (this.lights[index].uniqueId === uniqueId) {
  17856. return this.lights[index];
  17857. }
  17858. }
  17859. return null;
  17860. };
  17861. /**
  17862. * get a particle system by id
  17863. * @param id {number} the particle system id
  17864. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17865. */
  17866. Scene.prototype.getParticleSystemByID = function (id) {
  17867. for (var index = 0; index < this.particleSystems.length; index++) {
  17868. if (this.particleSystems[index].id === id) {
  17869. return this.particleSystems[index];
  17870. }
  17871. }
  17872. return null;
  17873. };
  17874. /**
  17875. * get a geometry using its ID
  17876. * @param {string} the geometry's id
  17877. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17878. */
  17879. Scene.prototype.getGeometryByID = function (id) {
  17880. for (var index = 0; index < this._geometries.length; index++) {
  17881. if (this._geometries[index].id === id) {
  17882. return this._geometries[index];
  17883. }
  17884. }
  17885. return null;
  17886. };
  17887. /**
  17888. * add a new geometry to this scene.
  17889. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17890. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17891. * @return {boolean} was the geometry added or not
  17892. */
  17893. Scene.prototype.pushGeometry = function (geometry, force) {
  17894. if (!force && this.getGeometryByID(geometry.id)) {
  17895. return false;
  17896. }
  17897. this._geometries.push(geometry);
  17898. //notify the collision coordinator
  17899. this.collisionCoordinator.onGeometryAdded(geometry);
  17900. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17901. return true;
  17902. };
  17903. /**
  17904. * Removes an existing geometry
  17905. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17906. * @return {boolean} was the geometry removed or not
  17907. */
  17908. Scene.prototype.removeGeometry = function (geometry) {
  17909. var index = this._geometries.indexOf(geometry);
  17910. if (index > -1) {
  17911. this._geometries.splice(index, 1);
  17912. //notify the collision coordinator
  17913. this.collisionCoordinator.onGeometryDeleted(geometry);
  17914. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17915. return true;
  17916. }
  17917. return false;
  17918. };
  17919. Scene.prototype.getGeometries = function () {
  17920. return this._geometries;
  17921. };
  17922. /**
  17923. * Get the first added mesh found of a given ID
  17924. * @param {string} id - the id to search for
  17925. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17926. */
  17927. Scene.prototype.getMeshByID = function (id) {
  17928. for (var index = 0; index < this.meshes.length; index++) {
  17929. if (this.meshes[index].id === id) {
  17930. return this.meshes[index];
  17931. }
  17932. }
  17933. return null;
  17934. };
  17935. Scene.prototype.getMeshesByID = function (id) {
  17936. return this.meshes.filter(function (m) {
  17937. return m.id === id;
  17938. });
  17939. };
  17940. /**
  17941. * Get a mesh with its auto-generated unique id
  17942. * @param {number} uniqueId - the unique id to search for
  17943. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17944. */
  17945. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17946. for (var index = 0; index < this.meshes.length; index++) {
  17947. if (this.meshes[index].uniqueId === uniqueId) {
  17948. return this.meshes[index];
  17949. }
  17950. }
  17951. return null;
  17952. };
  17953. /**
  17954. * Get a the last added mesh found of a given ID
  17955. * @param {string} id - the id to search for
  17956. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17957. */
  17958. Scene.prototype.getLastMeshByID = function (id) {
  17959. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17960. if (this.meshes[index].id === id) {
  17961. return this.meshes[index];
  17962. }
  17963. }
  17964. return null;
  17965. };
  17966. /**
  17967. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17968. * @param {string} id - the id to search for
  17969. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17970. */
  17971. Scene.prototype.getLastEntryByID = function (id) {
  17972. var index;
  17973. for (index = this.meshes.length - 1; index >= 0; index--) {
  17974. if (this.meshes[index].id === id) {
  17975. return this.meshes[index];
  17976. }
  17977. }
  17978. for (index = this.cameras.length - 1; index >= 0; index--) {
  17979. if (this.cameras[index].id === id) {
  17980. return this.cameras[index];
  17981. }
  17982. }
  17983. for (index = this.lights.length - 1; index >= 0; index--) {
  17984. if (this.lights[index].id === id) {
  17985. return this.lights[index];
  17986. }
  17987. }
  17988. return null;
  17989. };
  17990. Scene.prototype.getNodeByID = function (id) {
  17991. var mesh = this.getMeshByID(id);
  17992. if (mesh) {
  17993. return mesh;
  17994. }
  17995. var light = this.getLightByID(id);
  17996. if (light) {
  17997. return light;
  17998. }
  17999. var camera = this.getCameraByID(id);
  18000. if (camera) {
  18001. return camera;
  18002. }
  18003. var bone = this.getBoneByID(id);
  18004. return bone;
  18005. };
  18006. Scene.prototype.getNodeByName = function (name) {
  18007. var mesh = this.getMeshByName(name);
  18008. if (mesh) {
  18009. return mesh;
  18010. }
  18011. var light = this.getLightByName(name);
  18012. if (light) {
  18013. return light;
  18014. }
  18015. var camera = this.getCameraByName(name);
  18016. if (camera) {
  18017. return camera;
  18018. }
  18019. var bone = this.getBoneByName(name);
  18020. return bone;
  18021. };
  18022. Scene.prototype.getMeshByName = function (name) {
  18023. for (var index = 0; index < this.meshes.length; index++) {
  18024. if (this.meshes[index].name === name) {
  18025. return this.meshes[index];
  18026. }
  18027. }
  18028. return null;
  18029. };
  18030. Scene.prototype.getSoundByName = function (name) {
  18031. var index;
  18032. if (BABYLON.AudioEngine) {
  18033. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18034. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18035. return this.mainSoundTrack.soundCollection[index];
  18036. }
  18037. }
  18038. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18039. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18040. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18041. return this.soundTracks[sdIndex].soundCollection[index];
  18042. }
  18043. }
  18044. }
  18045. }
  18046. return null;
  18047. };
  18048. Scene.prototype.getLastSkeletonByID = function (id) {
  18049. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18050. if (this.skeletons[index].id === id) {
  18051. return this.skeletons[index];
  18052. }
  18053. }
  18054. return null;
  18055. };
  18056. Scene.prototype.getSkeletonById = function (id) {
  18057. for (var index = 0; index < this.skeletons.length; index++) {
  18058. if (this.skeletons[index].id === id) {
  18059. return this.skeletons[index];
  18060. }
  18061. }
  18062. return null;
  18063. };
  18064. Scene.prototype.getSkeletonByName = function (name) {
  18065. for (var index = 0; index < this.skeletons.length; index++) {
  18066. if (this.skeletons[index].name === name) {
  18067. return this.skeletons[index];
  18068. }
  18069. }
  18070. return null;
  18071. };
  18072. Scene.prototype.isActiveMesh = function (mesh) {
  18073. return (this._activeMeshes.indexOf(mesh) !== -1);
  18074. };
  18075. Object.defineProperty(Scene.prototype, "uid", {
  18076. /**
  18077. * Return a unique id as a string which can serve as an identifier for the scene
  18078. */
  18079. get: function () {
  18080. if (!this._uid) {
  18081. this._uid = BABYLON.Tools.RandomId();
  18082. }
  18083. return this._uid;
  18084. },
  18085. enumerable: true,
  18086. configurable: true
  18087. });
  18088. /**
  18089. * Add an externaly attached data from its key.
  18090. * This method call will fail and return false, if such key already exists.
  18091. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18092. * @param key the unique key that identifies the data
  18093. * @param data the data object to associate to the key for this Engine instance
  18094. * @return true if no such key were already present and the data was added successfully, false otherwise
  18095. */
  18096. Scene.prototype.addExternalData = function (key, data) {
  18097. return this._externalData.add(key, data);
  18098. };
  18099. /**
  18100. * Get an externaly attached data from its key
  18101. * @param key the unique key that identifies the data
  18102. * @return the associated data, if present (can be null), or undefined if not present
  18103. */
  18104. Scene.prototype.getExternalData = function (key) {
  18105. return this._externalData.get(key);
  18106. };
  18107. /**
  18108. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18109. * @param key the unique key that identifies the data
  18110. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18111. * @return the associated data, can be null if the factory returned null.
  18112. */
  18113. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18114. return this._externalData.getOrAddWithFactory(key, factory);
  18115. };
  18116. /**
  18117. * Remove an externaly attached data from the Engine instance
  18118. * @param key the unique key that identifies the data
  18119. * @return true if the data was successfully removed, false if it doesn't exist
  18120. */
  18121. Scene.prototype.removeExternalData = function (key) {
  18122. return this._externalData.remove(key);
  18123. };
  18124. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18125. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18126. var material = subMesh.getMaterial();
  18127. if (mesh.showSubMeshesBoundingBox) {
  18128. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18129. }
  18130. if (material) {
  18131. // Render targets
  18132. if (material.getRenderTargetTextures) {
  18133. if (this._processedMaterials.indexOf(material) === -1) {
  18134. this._processedMaterials.push(material);
  18135. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18136. }
  18137. }
  18138. // Dispatch
  18139. this._activeIndices.addCount(subMesh.indexCount, false);
  18140. this._renderingManager.dispatch(subMesh);
  18141. }
  18142. }
  18143. };
  18144. Scene.prototype._isInIntermediateRendering = function () {
  18145. return this._intermediateRendering;
  18146. };
  18147. Scene.prototype._evaluateActiveMeshes = function () {
  18148. this.activeCamera._activeMeshes.reset();
  18149. this._activeMeshes.reset();
  18150. this._renderingManager.reset();
  18151. this._processedMaterials.reset();
  18152. this._activeParticleSystems.reset();
  18153. this._activeSkeletons.reset();
  18154. this._softwareSkinnedMeshes.reset();
  18155. this._boundingBoxRenderer.reset();
  18156. this._edgesRenderers.reset();
  18157. // Meshes
  18158. var meshes;
  18159. var len;
  18160. if (this._selectionOctree) {
  18161. var selection = this._selectionOctree.select(this._frustumPlanes);
  18162. meshes = selection.data;
  18163. len = selection.length;
  18164. }
  18165. else {
  18166. len = this.meshes.length;
  18167. meshes = this.meshes;
  18168. }
  18169. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18170. var mesh = meshes[meshIndex];
  18171. if (mesh.isBlocked) {
  18172. continue;
  18173. }
  18174. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18175. if (!mesh.isReady() || !mesh.isEnabled()) {
  18176. continue;
  18177. }
  18178. mesh.computeWorldMatrix();
  18179. // Intersections
  18180. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18181. this._meshesForIntersections.pushNoDuplicate(mesh);
  18182. }
  18183. // Switch to current LOD
  18184. var meshLOD = mesh.getLOD(this.activeCamera);
  18185. if (!meshLOD) {
  18186. continue;
  18187. }
  18188. mesh._preActivate();
  18189. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18190. this._activeMeshes.push(mesh);
  18191. this.activeCamera._activeMeshes.push(mesh);
  18192. mesh._activate(this._renderId);
  18193. this._activeMesh(mesh, meshLOD);
  18194. }
  18195. }
  18196. // Particle systems
  18197. this._particlesDuration.beginMonitoring();
  18198. var beforeParticlesDate = BABYLON.Tools.Now;
  18199. if (this.particlesEnabled) {
  18200. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18201. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18202. var particleSystem = this.particleSystems[particleIndex];
  18203. if (!particleSystem.isStarted()) {
  18204. continue;
  18205. }
  18206. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18207. this._activeParticleSystems.push(particleSystem);
  18208. particleSystem.animate();
  18209. this._renderingManager.dispatchParticles(particleSystem);
  18210. }
  18211. }
  18212. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18213. }
  18214. this._particlesDuration.endMonitoring(false);
  18215. };
  18216. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18217. if (mesh.skeleton && this.skeletonsEnabled) {
  18218. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18219. mesh.skeleton.prepare();
  18220. }
  18221. if (!mesh.computeBonesUsingShaders) {
  18222. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18223. }
  18224. }
  18225. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18226. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18227. }
  18228. if (sourceMesh._edgesRenderer) {
  18229. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18230. }
  18231. if (mesh && mesh.subMeshes) {
  18232. // Submeshes Octrees
  18233. var len;
  18234. var subMeshes;
  18235. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18236. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18237. len = intersections.length;
  18238. subMeshes = intersections.data;
  18239. }
  18240. else {
  18241. subMeshes = mesh.subMeshes;
  18242. len = subMeshes.length;
  18243. }
  18244. for (var subIndex = 0; subIndex < len; subIndex++) {
  18245. var subMesh = subMeshes[subIndex];
  18246. this._evaluateSubMesh(subMesh, mesh);
  18247. }
  18248. }
  18249. };
  18250. Scene.prototype.updateTransformMatrix = function (force) {
  18251. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18252. };
  18253. Scene.prototype._renderForCamera = function (camera) {
  18254. var engine = this._engine;
  18255. var startTime = BABYLON.Tools.Now;
  18256. this.activeCamera = camera;
  18257. if (!this.activeCamera)
  18258. throw new Error("Active camera not set");
  18259. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18260. // Viewport
  18261. engine.setViewport(this.activeCamera.viewport);
  18262. // Camera
  18263. this.resetCachedMaterial();
  18264. this._renderId++;
  18265. this.updateTransformMatrix();
  18266. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18267. // Meshes
  18268. this._evaluateActiveMeshesDuration.beginMonitoring();
  18269. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18270. this._evaluateActiveMeshes();
  18271. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18272. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18273. // Software skinning
  18274. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18275. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18276. mesh.applySkeleton(mesh.skeleton);
  18277. }
  18278. // Render targets
  18279. this._renderTargetsDuration.beginMonitoring();
  18280. var needsRestoreFrameBuffer = false;
  18281. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18282. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18283. this._intermediateRendering = true;
  18284. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18285. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18286. var renderTarget = this._renderTargets.data[renderIndex];
  18287. if (renderTarget._shouldRender()) {
  18288. this._renderId++;
  18289. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18290. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18291. }
  18292. }
  18293. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18294. this._intermediateRendering = false;
  18295. this._renderId++;
  18296. needsRestoreFrameBuffer = true; // Restore back buffer
  18297. }
  18298. // Render HighlightLayer Texture
  18299. var stencilState = this._engine.getStencilBuffer();
  18300. var renderhighlights = false;
  18301. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18302. this._intermediateRendering = true;
  18303. for (var i = 0; i < this.highlightLayers.length; i++) {
  18304. var highlightLayer = this.highlightLayers[i];
  18305. if (highlightLayer.shouldRender() &&
  18306. (!highlightLayer.camera ||
  18307. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18308. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18309. renderhighlights = true;
  18310. var renderTarget = highlightLayer._mainTexture;
  18311. if (renderTarget._shouldRender()) {
  18312. this._renderId++;
  18313. renderTarget.render(false, false);
  18314. needsRestoreFrameBuffer = true;
  18315. }
  18316. }
  18317. }
  18318. this._intermediateRendering = false;
  18319. this._renderId++;
  18320. }
  18321. if (needsRestoreFrameBuffer) {
  18322. engine.restoreDefaultFramebuffer();
  18323. }
  18324. this._renderTargetsDuration.endMonitoring(false);
  18325. // Prepare Frame
  18326. this.postProcessManager._prepareFrame();
  18327. this._renderDuration.beginMonitoring();
  18328. // Backgrounds
  18329. var layerIndex;
  18330. var layer;
  18331. if (this.layers.length) {
  18332. engine.setDepthBuffer(false);
  18333. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18334. layer = this.layers[layerIndex];
  18335. if (layer.isBackground) {
  18336. layer.render();
  18337. }
  18338. }
  18339. engine.setDepthBuffer(true);
  18340. }
  18341. // Render
  18342. BABYLON.Tools.StartPerformanceCounter("Main render");
  18343. // Activate HighlightLayer stencil
  18344. if (renderhighlights) {
  18345. this._engine.setStencilBuffer(true);
  18346. }
  18347. this._renderingManager.render(null, null, true, true);
  18348. // Restore HighlightLayer stencil
  18349. if (renderhighlights) {
  18350. this._engine.setStencilBuffer(stencilState);
  18351. }
  18352. BABYLON.Tools.EndPerformanceCounter("Main render");
  18353. // Bounding boxes
  18354. this._boundingBoxRenderer.render();
  18355. // Edges
  18356. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18357. this._edgesRenderers.data[edgesRendererIndex].render();
  18358. }
  18359. // Lens flares
  18360. if (this.lensFlaresEnabled) {
  18361. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18362. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18363. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18364. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18365. lensFlareSystem.render();
  18366. }
  18367. }
  18368. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18369. }
  18370. // Foregrounds
  18371. if (this.layers.length) {
  18372. engine.setDepthBuffer(false);
  18373. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18374. layer = this.layers[layerIndex];
  18375. if (!layer.isBackground) {
  18376. layer.render();
  18377. }
  18378. }
  18379. engine.setDepthBuffer(true);
  18380. }
  18381. // Highlight Layer
  18382. if (renderhighlights) {
  18383. engine.setDepthBuffer(false);
  18384. for (var i = 0; i < this.highlightLayers.length; i++) {
  18385. if (this.highlightLayers[i].shouldRender()) {
  18386. this.highlightLayers[i].render();
  18387. }
  18388. }
  18389. engine.setDepthBuffer(true);
  18390. }
  18391. this._renderDuration.endMonitoring(false);
  18392. // Finalize frame
  18393. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18394. // Update camera
  18395. this.activeCamera._updateFromScene();
  18396. // Reset some special arrays
  18397. this._renderTargets.reset();
  18398. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18399. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18400. };
  18401. Scene.prototype._processSubCameras = function (camera) {
  18402. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18403. this._renderForCamera(camera);
  18404. return;
  18405. }
  18406. // rig cameras
  18407. for (var index = 0; index < camera._rigCameras.length; index++) {
  18408. this._renderForCamera(camera._rigCameras[index]);
  18409. }
  18410. this.activeCamera = camera;
  18411. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18412. // Update camera
  18413. this.activeCamera._updateFromScene();
  18414. };
  18415. Scene.prototype._checkIntersections = function () {
  18416. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18417. var sourceMesh = this._meshesForIntersections.data[index];
  18418. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18419. var action = sourceMesh.actionManager.actions[actionIndex];
  18420. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18421. var parameters = action.getTriggerParameter();
  18422. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18423. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18424. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18425. if (areIntersecting && currentIntersectionInProgress === -1) {
  18426. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18427. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18428. sourceMesh._intersectionsInProgress.push(otherMesh);
  18429. }
  18430. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18431. sourceMesh._intersectionsInProgress.push(otherMesh);
  18432. }
  18433. }
  18434. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18435. //They intersected, and now they don't.
  18436. //is this trigger an exit trigger? execute an event.
  18437. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18438. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18439. }
  18440. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18441. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18442. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18443. }
  18444. }
  18445. }
  18446. }
  18447. }
  18448. };
  18449. Scene.prototype.render = function () {
  18450. this._lastFrameDuration.beginMonitoring();
  18451. this._particlesDuration.fetchNewFrame();
  18452. this._spritesDuration.fetchNewFrame();
  18453. this._activeParticles.fetchNewFrame();
  18454. this._renderDuration.fetchNewFrame();
  18455. this._renderTargetsDuration.fetchNewFrame();
  18456. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18457. this._totalVertices.fetchNewFrame();
  18458. this._activeIndices.fetchNewFrame();
  18459. this._activeBones.fetchNewFrame();
  18460. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18461. this._meshesForIntersections.reset();
  18462. this.resetCachedMaterial();
  18463. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18464. // Actions
  18465. if (this.actionManager) {
  18466. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18467. }
  18468. //Simplification Queue
  18469. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18470. this.simplificationQueue.executeNext();
  18471. }
  18472. // Animations
  18473. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18474. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18475. this._animate();
  18476. // Physics
  18477. if (this._physicsEngine) {
  18478. BABYLON.Tools.StartPerformanceCounter("Physics");
  18479. this._physicsEngine._step(deltaTime / 1000.0);
  18480. BABYLON.Tools.EndPerformanceCounter("Physics");
  18481. }
  18482. // Before render
  18483. this.onBeforeRenderObservable.notifyObservers(this);
  18484. // Customs render targets
  18485. this._renderTargetsDuration.beginMonitoring();
  18486. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18487. var engine = this.getEngine();
  18488. var currentActiveCamera = this.activeCamera;
  18489. if (this.renderTargetsEnabled) {
  18490. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18491. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18492. var renderTarget = this.customRenderTargets[customIndex];
  18493. if (renderTarget._shouldRender()) {
  18494. this._renderId++;
  18495. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18496. if (!this.activeCamera)
  18497. throw new Error("Active camera not set");
  18498. // Viewport
  18499. engine.setViewport(this.activeCamera.viewport);
  18500. // Camera
  18501. this.updateTransformMatrix();
  18502. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18503. }
  18504. }
  18505. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18506. this._renderId++;
  18507. }
  18508. if (this.customRenderTargets.length > 0) {
  18509. engine.restoreDefaultFramebuffer();
  18510. }
  18511. this._renderTargetsDuration.endMonitoring();
  18512. this.activeCamera = currentActiveCamera;
  18513. // Procedural textures
  18514. if (this.proceduralTexturesEnabled) {
  18515. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18516. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18517. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18518. if (proceduralTexture._shouldRender()) {
  18519. proceduralTexture.render();
  18520. }
  18521. }
  18522. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18523. }
  18524. // Clear
  18525. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18526. // Shadows
  18527. if (this.shadowsEnabled) {
  18528. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18529. var light = this.lights[lightIndex];
  18530. var shadowGenerator = light.getShadowGenerator();
  18531. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18532. this._renderTargets.push(shadowGenerator.getShadowMap());
  18533. }
  18534. }
  18535. }
  18536. // Depth renderer
  18537. if (this._depthRenderer) {
  18538. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18539. }
  18540. // RenderPipeline
  18541. this.postProcessRenderPipelineManager.update();
  18542. // Multi-cameras?
  18543. if (this.activeCameras.length > 0) {
  18544. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18545. if (cameraIndex > 0) {
  18546. this._engine.clear(0, false, true, true);
  18547. }
  18548. this._processSubCameras(this.activeCameras[cameraIndex]);
  18549. }
  18550. }
  18551. else {
  18552. if (!this.activeCamera) {
  18553. throw new Error("No camera defined");
  18554. }
  18555. this._processSubCameras(this.activeCamera);
  18556. }
  18557. // Intersection checks
  18558. this._checkIntersections();
  18559. // Update the audio listener attached to the camera
  18560. if (BABYLON.AudioEngine) {
  18561. this._updateAudioParameters();
  18562. }
  18563. // After render
  18564. if (this.afterRender) {
  18565. this.afterRender();
  18566. }
  18567. this.onAfterRenderObservable.notifyObservers(this);
  18568. // Cleaning
  18569. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18570. this._toBeDisposed.data[index].dispose();
  18571. this._toBeDisposed[index] = null;
  18572. }
  18573. this._toBeDisposed.reset();
  18574. if (this.dumpNextRenderTargets) {
  18575. this.dumpNextRenderTargets = false;
  18576. }
  18577. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18578. this._lastFrameDuration.endMonitoring();
  18579. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18580. this._totalLightsCounter.addCount(this.lights.length, true);
  18581. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18582. this._totalTexturesCounter.addCount(this.textures.length, true);
  18583. this._activeBones.addCount(0, true);
  18584. this._activeIndices.addCount(0, true);
  18585. this._activeParticles.addCount(0, true);
  18586. };
  18587. Scene.prototype._updateAudioParameters = function () {
  18588. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18589. return;
  18590. }
  18591. var listeningCamera;
  18592. var audioEngine = BABYLON.Engine.audioEngine;
  18593. if (this.activeCameras.length > 0) {
  18594. listeningCamera = this.activeCameras[0];
  18595. }
  18596. else {
  18597. listeningCamera = this.activeCamera;
  18598. }
  18599. if (listeningCamera && audioEngine.canUseWebAudio) {
  18600. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18601. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18602. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18603. cameraDirection.normalize();
  18604. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18605. var i;
  18606. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18607. var sound = this.mainSoundTrack.soundCollection[i];
  18608. if (sound.useCustomAttenuation) {
  18609. sound.updateDistanceFromListener();
  18610. }
  18611. }
  18612. for (i = 0; i < this.soundTracks.length; i++) {
  18613. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18614. sound = this.soundTracks[i].soundCollection[j];
  18615. if (sound.useCustomAttenuation) {
  18616. sound.updateDistanceFromListener();
  18617. }
  18618. }
  18619. }
  18620. }
  18621. };
  18622. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18623. // Audio
  18624. get: function () {
  18625. return this._audioEnabled;
  18626. },
  18627. set: function (value) {
  18628. this._audioEnabled = value;
  18629. if (BABYLON.AudioEngine) {
  18630. if (this._audioEnabled) {
  18631. this._enableAudio();
  18632. }
  18633. else {
  18634. this._disableAudio();
  18635. }
  18636. }
  18637. },
  18638. enumerable: true,
  18639. configurable: true
  18640. });
  18641. Scene.prototype._disableAudio = function () {
  18642. var i;
  18643. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18644. this.mainSoundTrack.soundCollection[i].pause();
  18645. }
  18646. for (i = 0; i < this.soundTracks.length; i++) {
  18647. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18648. this.soundTracks[i].soundCollection[j].pause();
  18649. }
  18650. }
  18651. };
  18652. Scene.prototype._enableAudio = function () {
  18653. var i;
  18654. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18655. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18656. this.mainSoundTrack.soundCollection[i].play();
  18657. }
  18658. }
  18659. for (i = 0; i < this.soundTracks.length; i++) {
  18660. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18661. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18662. this.soundTracks[i].soundCollection[j].play();
  18663. }
  18664. }
  18665. }
  18666. };
  18667. Object.defineProperty(Scene.prototype, "headphone", {
  18668. get: function () {
  18669. return this._headphone;
  18670. },
  18671. set: function (value) {
  18672. this._headphone = value;
  18673. if (BABYLON.AudioEngine) {
  18674. if (this._headphone) {
  18675. this._switchAudioModeForHeadphones();
  18676. }
  18677. else {
  18678. this._switchAudioModeForNormalSpeakers();
  18679. }
  18680. }
  18681. },
  18682. enumerable: true,
  18683. configurable: true
  18684. });
  18685. Scene.prototype._switchAudioModeForHeadphones = function () {
  18686. this.mainSoundTrack.switchPanningModelToHRTF();
  18687. for (var i = 0; i < this.soundTracks.length; i++) {
  18688. this.soundTracks[i].switchPanningModelToHRTF();
  18689. }
  18690. };
  18691. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18692. this.mainSoundTrack.switchPanningModelToEqualPower();
  18693. for (var i = 0; i < this.soundTracks.length; i++) {
  18694. this.soundTracks[i].switchPanningModelToEqualPower();
  18695. }
  18696. };
  18697. Scene.prototype.enableDepthRenderer = function () {
  18698. if (this._depthRenderer) {
  18699. return this._depthRenderer;
  18700. }
  18701. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18702. return this._depthRenderer;
  18703. };
  18704. Scene.prototype.disableDepthRenderer = function () {
  18705. if (!this._depthRenderer) {
  18706. return;
  18707. }
  18708. this._depthRenderer.dispose();
  18709. this._depthRenderer = null;
  18710. };
  18711. Scene.prototype.freezeMaterials = function () {
  18712. for (var i = 0; i < this.materials.length; i++) {
  18713. this.materials[i].freeze();
  18714. }
  18715. };
  18716. Scene.prototype.unfreezeMaterials = function () {
  18717. for (var i = 0; i < this.materials.length; i++) {
  18718. this.materials[i].unfreeze();
  18719. }
  18720. };
  18721. Scene.prototype.dispose = function () {
  18722. this.beforeRender = null;
  18723. this.afterRender = null;
  18724. this.skeletons = [];
  18725. this._boundingBoxRenderer.dispose();
  18726. if (this._depthRenderer) {
  18727. this._depthRenderer.dispose();
  18728. }
  18729. // Debug layer
  18730. if (this._debugLayer) {
  18731. this._debugLayer.hide();
  18732. }
  18733. // Events
  18734. this.onDisposeObservable.notifyObservers(this);
  18735. this.onDisposeObservable.clear();
  18736. this.onBeforeRenderObservable.clear();
  18737. this.onAfterRenderObservable.clear();
  18738. this.detachControl();
  18739. // Release sounds & sounds tracks
  18740. if (BABYLON.AudioEngine) {
  18741. this.disposeSounds();
  18742. }
  18743. // Detach cameras
  18744. var canvas = this._engine.getRenderingCanvas();
  18745. var index;
  18746. for (index = 0; index < this.cameras.length; index++) {
  18747. this.cameras[index].detachControl(canvas);
  18748. }
  18749. // Release lights
  18750. while (this.lights.length) {
  18751. this.lights[0].dispose();
  18752. }
  18753. // Release meshes
  18754. while (this.meshes.length) {
  18755. this.meshes[0].dispose(true);
  18756. }
  18757. // Release cameras
  18758. while (this.cameras.length) {
  18759. this.cameras[0].dispose();
  18760. }
  18761. // Release materials
  18762. while (this.materials.length) {
  18763. this.materials[0].dispose();
  18764. }
  18765. // Release particles
  18766. while (this.particleSystems.length) {
  18767. this.particleSystems[0].dispose();
  18768. }
  18769. // Release sprites
  18770. while (this.spriteManagers.length) {
  18771. this.spriteManagers[0].dispose();
  18772. }
  18773. // Release layers
  18774. while (this.layers.length) {
  18775. this.layers[0].dispose();
  18776. }
  18777. while (this.highlightLayers.length) {
  18778. this.highlightLayers[0].dispose();
  18779. }
  18780. // Release textures
  18781. while (this.textures.length) {
  18782. this.textures[0].dispose();
  18783. }
  18784. // Post-processes
  18785. this.postProcessManager.dispose();
  18786. // Physics
  18787. if (this._physicsEngine) {
  18788. this.disablePhysicsEngine();
  18789. }
  18790. // Remove from engine
  18791. index = this._engine.scenes.indexOf(this);
  18792. if (index > -1) {
  18793. this._engine.scenes.splice(index, 1);
  18794. }
  18795. this._engine.wipeCaches();
  18796. };
  18797. // Release sounds & sounds tracks
  18798. Scene.prototype.disposeSounds = function () {
  18799. this.mainSoundTrack.dispose();
  18800. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18801. this.soundTracks[scIndex].dispose();
  18802. }
  18803. };
  18804. // Octrees
  18805. Scene.prototype.getWorldExtends = function () {
  18806. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18807. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18808. for (var index = 0; index < this.meshes.length; index++) {
  18809. var mesh = this.meshes[index];
  18810. mesh.computeWorldMatrix(true);
  18811. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18812. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18813. BABYLON.Tools.CheckExtends(minBox, min, max);
  18814. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18815. }
  18816. return {
  18817. min: min,
  18818. max: max
  18819. };
  18820. };
  18821. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18822. if (maxCapacity === void 0) { maxCapacity = 64; }
  18823. if (maxDepth === void 0) { maxDepth = 2; }
  18824. if (!this._selectionOctree) {
  18825. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18826. }
  18827. var worldExtends = this.getWorldExtends();
  18828. // Update octree
  18829. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18830. return this._selectionOctree;
  18831. };
  18832. // Picking
  18833. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18834. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18835. var engine = this._engine;
  18836. if (!camera) {
  18837. if (!this.activeCamera)
  18838. throw new Error("Active camera not set");
  18839. camera = this.activeCamera;
  18840. }
  18841. var cameraViewport = camera.viewport;
  18842. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18843. // Moving coordinates to local viewport world
  18844. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18845. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18846. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18847. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18848. };
  18849. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18850. var engine = this._engine;
  18851. if (!camera) {
  18852. if (!this.activeCamera)
  18853. throw new Error("Active camera not set");
  18854. camera = this.activeCamera;
  18855. }
  18856. var cameraViewport = camera.viewport;
  18857. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18858. var identity = BABYLON.Matrix.Identity();
  18859. // Moving coordinates to local viewport world
  18860. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18861. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18862. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18863. };
  18864. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18865. var pickingInfo = null;
  18866. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18867. var mesh = this.meshes[meshIndex];
  18868. if (predicate) {
  18869. if (!predicate(mesh)) {
  18870. continue;
  18871. }
  18872. }
  18873. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18874. continue;
  18875. }
  18876. var world = mesh.getWorldMatrix();
  18877. var ray = rayFunction(world);
  18878. var result = mesh.intersects(ray, fastCheck);
  18879. if (!result || !result.hit)
  18880. continue;
  18881. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18882. continue;
  18883. pickingInfo = result;
  18884. if (fastCheck) {
  18885. break;
  18886. }
  18887. }
  18888. return pickingInfo || new BABYLON.PickingInfo();
  18889. };
  18890. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18891. var pickingInfos = new Array();
  18892. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18893. var mesh = this.meshes[meshIndex];
  18894. if (predicate) {
  18895. if (!predicate(mesh)) {
  18896. continue;
  18897. }
  18898. }
  18899. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18900. continue;
  18901. }
  18902. var world = mesh.getWorldMatrix();
  18903. var ray = rayFunction(world);
  18904. var result = mesh.intersects(ray, false);
  18905. if (!result || !result.hit)
  18906. continue;
  18907. pickingInfos.push(result);
  18908. }
  18909. return pickingInfos;
  18910. };
  18911. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18912. var pickingInfo = null;
  18913. camera = camera || this.activeCamera;
  18914. if (this.spriteManagers.length > 0) {
  18915. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18916. var spriteManager = this.spriteManagers[spriteIndex];
  18917. if (!spriteManager.isPickable) {
  18918. continue;
  18919. }
  18920. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18921. if (!result || !result.hit)
  18922. continue;
  18923. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18924. continue;
  18925. pickingInfo = result;
  18926. if (fastCheck) {
  18927. break;
  18928. }
  18929. }
  18930. }
  18931. return pickingInfo || new BABYLON.PickingInfo();
  18932. };
  18933. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18934. /// <param name="x">X position on screen</param>
  18935. /// <param name="y">Y position on screen</param>
  18936. /// <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>
  18937. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18938. /// <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>
  18939. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18940. var _this = this;
  18941. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18942. };
  18943. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18944. /// <param name="x">X position on screen</param>
  18945. /// <param name="y">Y position on screen</param>
  18946. /// <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>
  18947. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18948. /// <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>
  18949. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18950. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18951. };
  18952. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18953. var _this = this;
  18954. return this._internalPick(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, fastCheck);
  18961. };
  18962. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18963. /// <param name="x">X position on screen</param>
  18964. /// <param name="y">Y position on screen</param>
  18965. /// <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>
  18966. /// <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>
  18967. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18968. var _this = this;
  18969. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18970. };
  18971. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18972. /// <param name="ray">Ray to use</param>
  18973. /// <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>
  18974. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18975. var _this = this;
  18976. return this._internalMultiPick(function (world) {
  18977. if (!_this._pickWithRayInverseMatrix) {
  18978. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18979. }
  18980. world.invertToRef(_this._pickWithRayInverseMatrix);
  18981. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18982. }, predicate);
  18983. };
  18984. Scene.prototype.setPointerOverMesh = function (mesh) {
  18985. if (this._pointerOverMesh === mesh) {
  18986. return;
  18987. }
  18988. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18989. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18990. }
  18991. this._pointerOverMesh = mesh;
  18992. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18993. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18994. }
  18995. };
  18996. Scene.prototype.getPointerOverMesh = function () {
  18997. return this._pointerOverMesh;
  18998. };
  18999. Scene.prototype.setPointerOverSprite = function (sprite) {
  19000. if (this._pointerOverSprite === sprite) {
  19001. return;
  19002. }
  19003. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19004. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19005. }
  19006. this._pointerOverSprite = sprite;
  19007. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19008. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19009. }
  19010. };
  19011. Scene.prototype.getPointerOverSprite = function () {
  19012. return this._pointerOverSprite;
  19013. };
  19014. // Physics
  19015. Scene.prototype.getPhysicsEngine = function () {
  19016. return this._physicsEngine;
  19017. };
  19018. /**
  19019. * Enables physics to the current scene
  19020. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19021. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19022. * @return {boolean} was the physics engine initialized
  19023. */
  19024. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19025. if (this._physicsEngine) {
  19026. return true;
  19027. }
  19028. try {
  19029. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19030. return true;
  19031. }
  19032. catch (e) {
  19033. BABYLON.Tools.Error(e.message);
  19034. return false;
  19035. }
  19036. };
  19037. Scene.prototype.disablePhysicsEngine = function () {
  19038. if (!this._physicsEngine) {
  19039. return;
  19040. }
  19041. this._physicsEngine.dispose();
  19042. this._physicsEngine = undefined;
  19043. };
  19044. Scene.prototype.isPhysicsEnabled = function () {
  19045. return this._physicsEngine !== undefined;
  19046. };
  19047. /**
  19048. *
  19049. * Sets the gravity of the physics engine (and NOT of the scene)
  19050. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19051. */
  19052. Scene.prototype.setGravity = function (gravity) {
  19053. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19054. if (!this._physicsEngine) {
  19055. return;
  19056. }
  19057. this._physicsEngine.setGravity(gravity);
  19058. };
  19059. /**
  19060. * Legacy support, using the new API
  19061. * @Deprecated
  19062. */
  19063. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19064. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19065. if (parts.parts) {
  19066. options = parts;
  19067. parts = parts.parts;
  19068. }
  19069. var mainMesh = parts[0].mesh;
  19070. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19071. for (var index = 1; index < parts.length; index++) {
  19072. var mesh = parts[index].mesh;
  19073. if (mesh.parent !== mainMesh) {
  19074. mesh.position = mesh.position.subtract(mainMesh.position);
  19075. mesh.parent = mainMesh;
  19076. }
  19077. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19078. }
  19079. mainMesh.physicsImpostor.forceUpdate();
  19080. };
  19081. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19082. var mesh = compound.parts[0].mesh;
  19083. mesh.physicsImpostor.dispose();
  19084. mesh.physicsImpostor = null;
  19085. };
  19086. // Misc.
  19087. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19088. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19089. // Light
  19090. if (this.lights.length === 0) {
  19091. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19092. }
  19093. // Camera
  19094. if (!this.activeCamera) {
  19095. // Compute position
  19096. var worldExtends = this.getWorldExtends();
  19097. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19098. var camera;
  19099. if (createArcRotateCamera) {
  19100. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19101. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19102. camera.setTarget(worldCenter);
  19103. }
  19104. else {
  19105. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19106. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19107. camera.setTarget(worldCenter);
  19108. }
  19109. this.activeCamera = camera;
  19110. }
  19111. };
  19112. // Tags
  19113. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19114. if (tagsQuery === undefined) {
  19115. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19116. return list;
  19117. }
  19118. var listByTags = [];
  19119. forEach = forEach || (function (item) { return; });
  19120. for (var i in list) {
  19121. var item = list[i];
  19122. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19123. listByTags.push(item);
  19124. forEach(item);
  19125. }
  19126. }
  19127. return listByTags;
  19128. };
  19129. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19130. return this._getByTags(this.meshes, tagsQuery, forEach);
  19131. };
  19132. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19133. return this._getByTags(this.cameras, tagsQuery, forEach);
  19134. };
  19135. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19136. return this._getByTags(this.lights, tagsQuery, forEach);
  19137. };
  19138. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19139. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19140. };
  19141. /**
  19142. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19143. * This allowed control for front to back rendering or reversly depending of the special needs.
  19144. *
  19145. * @param renderingGroupId The rendering group id corresponding to its index
  19146. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19147. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19148. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19149. */
  19150. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19151. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19152. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19153. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19154. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19155. };
  19156. /**
  19157. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19158. *
  19159. * @param renderingGroupId The rendering group id corresponding to its index
  19160. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19161. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19162. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19163. */
  19164. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19165. if (depth === void 0) { depth = true; }
  19166. if (stencil === void 0) { stencil = true; }
  19167. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19168. };
  19169. return Scene;
  19170. }());
  19171. // Statics
  19172. Scene._FOGMODE_NONE = 0;
  19173. Scene._FOGMODE_EXP = 1;
  19174. Scene._FOGMODE_EXP2 = 2;
  19175. Scene._FOGMODE_LINEAR = 3;
  19176. Scene.MinDeltaTime = 1.0;
  19177. Scene.MaxDeltaTime = 1000.0;
  19178. BABYLON.Scene = Scene;
  19179. })(BABYLON || (BABYLON = {}));
  19180. //# sourceMappingURL=babylon.scene.js.map
  19181. var BABYLON;
  19182. (function (BABYLON) {
  19183. var Buffer = (function () {
  19184. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19185. if (engine instanceof BABYLON.Mesh) {
  19186. this._engine = engine.getScene().getEngine();
  19187. }
  19188. else {
  19189. this._engine = engine;
  19190. }
  19191. this._updatable = updatable;
  19192. this._data = data;
  19193. this._strideSize = stride;
  19194. if (!postponeInternalCreation) {
  19195. this.create();
  19196. }
  19197. this._instanced = instanced;
  19198. }
  19199. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19200. // a lot of these parameters are ignored as they are overriden by the buffer
  19201. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19202. };
  19203. // Properties
  19204. Buffer.prototype.isUpdatable = function () {
  19205. return this._updatable;
  19206. };
  19207. Buffer.prototype.getData = function () {
  19208. return this._data;
  19209. };
  19210. Buffer.prototype.getBuffer = function () {
  19211. return this._buffer;
  19212. };
  19213. Buffer.prototype.getStrideSize = function () {
  19214. return this._strideSize;
  19215. };
  19216. Buffer.prototype.getIsInstanced = function () {
  19217. return this._instanced;
  19218. };
  19219. // Methods
  19220. Buffer.prototype.create = function (data) {
  19221. if (!data && this._buffer) {
  19222. return; // nothing to do
  19223. }
  19224. data = data || this._data;
  19225. if (!this._buffer) {
  19226. if (this._updatable) {
  19227. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19228. this._data = data;
  19229. }
  19230. else {
  19231. this._buffer = this._engine.createVertexBuffer(data);
  19232. }
  19233. }
  19234. else if (this._updatable) {
  19235. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19236. this._data = data;
  19237. }
  19238. };
  19239. Buffer.prototype.update = function (data) {
  19240. this.create(data);
  19241. };
  19242. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19243. if (!this._buffer) {
  19244. return;
  19245. }
  19246. if (this._updatable) {
  19247. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19248. this._data = null;
  19249. }
  19250. };
  19251. Buffer.prototype.dispose = function () {
  19252. if (!this._buffer) {
  19253. return;
  19254. }
  19255. if (this._engine._releaseBuffer(this._buffer)) {
  19256. this._buffer = null;
  19257. }
  19258. };
  19259. return Buffer;
  19260. }());
  19261. BABYLON.Buffer = Buffer;
  19262. })(BABYLON || (BABYLON = {}));
  19263. //# sourceMappingURL=babylon.buffer.js.map
  19264. var BABYLON;
  19265. (function (BABYLON) {
  19266. var VertexBuffer = (function () {
  19267. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19268. if (!stride) {
  19269. // Deduce stride from kind
  19270. switch (kind) {
  19271. case VertexBuffer.PositionKind:
  19272. stride = 3;
  19273. break;
  19274. case VertexBuffer.NormalKind:
  19275. stride = 3;
  19276. break;
  19277. case VertexBuffer.UVKind:
  19278. case VertexBuffer.UV2Kind:
  19279. case VertexBuffer.UV3Kind:
  19280. case VertexBuffer.UV4Kind:
  19281. case VertexBuffer.UV5Kind:
  19282. case VertexBuffer.UV6Kind:
  19283. stride = 2;
  19284. break;
  19285. case VertexBuffer.ColorKind:
  19286. stride = 4;
  19287. break;
  19288. case VertexBuffer.MatricesIndicesKind:
  19289. case VertexBuffer.MatricesIndicesExtraKind:
  19290. stride = 4;
  19291. break;
  19292. case VertexBuffer.MatricesWeightsKind:
  19293. case VertexBuffer.MatricesWeightsExtraKind:
  19294. stride = 4;
  19295. break;
  19296. }
  19297. }
  19298. if (data instanceof BABYLON.Buffer) {
  19299. if (!stride) {
  19300. stride = data.getStrideSize();
  19301. }
  19302. this._buffer = data;
  19303. this._ownsBuffer = false;
  19304. }
  19305. else {
  19306. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19307. this._ownsBuffer = true;
  19308. }
  19309. this._stride = stride;
  19310. this._offset = offset ? offset : 0;
  19311. this._size = size ? size : stride;
  19312. this._kind = kind;
  19313. }
  19314. VertexBuffer.prototype.getKind = function () {
  19315. return this._kind;
  19316. };
  19317. // Properties
  19318. VertexBuffer.prototype.isUpdatable = function () {
  19319. return this._buffer.isUpdatable();
  19320. };
  19321. VertexBuffer.prototype.getData = function () {
  19322. return this._buffer.getData();
  19323. };
  19324. VertexBuffer.prototype.getBuffer = function () {
  19325. return this._buffer.getBuffer();
  19326. };
  19327. VertexBuffer.prototype.getStrideSize = function () {
  19328. return this._stride;
  19329. };
  19330. VertexBuffer.prototype.getOffset = function () {
  19331. return this._offset;
  19332. };
  19333. VertexBuffer.prototype.getSize = function () {
  19334. return this._size;
  19335. };
  19336. VertexBuffer.prototype.getIsInstanced = function () {
  19337. return this._buffer.getIsInstanced();
  19338. };
  19339. // Methods
  19340. VertexBuffer.prototype.create = function (data) {
  19341. return this._buffer.create(data);
  19342. };
  19343. VertexBuffer.prototype.update = function (data) {
  19344. return this._buffer.update(data);
  19345. };
  19346. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19347. return this._buffer.updateDirectly(data, offset);
  19348. };
  19349. VertexBuffer.prototype.dispose = function () {
  19350. if (this._ownsBuffer) {
  19351. this._buffer.dispose();
  19352. }
  19353. };
  19354. Object.defineProperty(VertexBuffer, "PositionKind", {
  19355. get: function () {
  19356. return VertexBuffer._PositionKind;
  19357. },
  19358. enumerable: true,
  19359. configurable: true
  19360. });
  19361. Object.defineProperty(VertexBuffer, "NormalKind", {
  19362. get: function () {
  19363. return VertexBuffer._NormalKind;
  19364. },
  19365. enumerable: true,
  19366. configurable: true
  19367. });
  19368. Object.defineProperty(VertexBuffer, "UVKind", {
  19369. get: function () {
  19370. return VertexBuffer._UVKind;
  19371. },
  19372. enumerable: true,
  19373. configurable: true
  19374. });
  19375. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19376. get: function () {
  19377. return VertexBuffer._UV2Kind;
  19378. },
  19379. enumerable: true,
  19380. configurable: true
  19381. });
  19382. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19383. get: function () {
  19384. return VertexBuffer._UV3Kind;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19390. get: function () {
  19391. return VertexBuffer._UV4Kind;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19397. get: function () {
  19398. return VertexBuffer._UV5Kind;
  19399. },
  19400. enumerable: true,
  19401. configurable: true
  19402. });
  19403. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19404. get: function () {
  19405. return VertexBuffer._UV6Kind;
  19406. },
  19407. enumerable: true,
  19408. configurable: true
  19409. });
  19410. Object.defineProperty(VertexBuffer, "ColorKind", {
  19411. get: function () {
  19412. return VertexBuffer._ColorKind;
  19413. },
  19414. enumerable: true,
  19415. configurable: true
  19416. });
  19417. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19418. get: function () {
  19419. return VertexBuffer._MatricesIndicesKind;
  19420. },
  19421. enumerable: true,
  19422. configurable: true
  19423. });
  19424. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19425. get: function () {
  19426. return VertexBuffer._MatricesWeightsKind;
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19432. get: function () {
  19433. return VertexBuffer._MatricesIndicesExtraKind;
  19434. },
  19435. enumerable: true,
  19436. configurable: true
  19437. });
  19438. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19439. get: function () {
  19440. return VertexBuffer._MatricesWeightsExtraKind;
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. return VertexBuffer;
  19446. }());
  19447. // Enums
  19448. VertexBuffer._PositionKind = "position";
  19449. VertexBuffer._NormalKind = "normal";
  19450. VertexBuffer._UVKind = "uv";
  19451. VertexBuffer._UV2Kind = "uv2";
  19452. VertexBuffer._UV3Kind = "uv3";
  19453. VertexBuffer._UV4Kind = "uv4";
  19454. VertexBuffer._UV5Kind = "uv5";
  19455. VertexBuffer._UV6Kind = "uv6";
  19456. VertexBuffer._ColorKind = "color";
  19457. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19458. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19459. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19460. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19461. BABYLON.VertexBuffer = VertexBuffer;
  19462. })(BABYLON || (BABYLON = {}));
  19463. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19464. var BABYLON;
  19465. (function (BABYLON) {
  19466. /**
  19467. * Creates an instance based on a source mesh.
  19468. */
  19469. var InstancedMesh = (function (_super) {
  19470. __extends(InstancedMesh, _super);
  19471. function InstancedMesh(name, source) {
  19472. var _this = _super.call(this, name, source.getScene()) || this;
  19473. source.instances.push(_this);
  19474. _this._sourceMesh = source;
  19475. _this.position.copyFrom(source.position);
  19476. _this.rotation.copyFrom(source.rotation);
  19477. _this.scaling.copyFrom(source.scaling);
  19478. if (source.rotationQuaternion) {
  19479. _this.rotationQuaternion = source.rotationQuaternion.clone();
  19480. }
  19481. _this.infiniteDistance = source.infiniteDistance;
  19482. _this.setPivotMatrix(source.getPivotMatrix());
  19483. _this.refreshBoundingInfo();
  19484. _this._syncSubMeshes();
  19485. return _this;
  19486. }
  19487. InstancedMesh.prototype.getClassName = function () {
  19488. return "InstancedMesh";
  19489. };
  19490. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19491. // Methods
  19492. get: function () {
  19493. return this._sourceMesh.receiveShadows;
  19494. },
  19495. enumerable: true,
  19496. configurable: true
  19497. });
  19498. Object.defineProperty(InstancedMesh.prototype, "material", {
  19499. get: function () {
  19500. return this._sourceMesh.material;
  19501. },
  19502. enumerable: true,
  19503. configurable: true
  19504. });
  19505. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19506. get: function () {
  19507. return this._sourceMesh.visibility;
  19508. },
  19509. enumerable: true,
  19510. configurable: true
  19511. });
  19512. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19513. get: function () {
  19514. return this._sourceMesh.skeleton;
  19515. },
  19516. enumerable: true,
  19517. configurable: true
  19518. });
  19519. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19520. get: function () {
  19521. return this._sourceMesh.renderingGroupId;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. InstancedMesh.prototype.getTotalVertices = function () {
  19527. return this._sourceMesh.getTotalVertices();
  19528. };
  19529. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19530. get: function () {
  19531. return this._sourceMesh;
  19532. },
  19533. enumerable: true,
  19534. configurable: true
  19535. });
  19536. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19537. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19538. };
  19539. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19540. return this._sourceMesh.isVerticesDataPresent(kind);
  19541. };
  19542. InstancedMesh.prototype.getIndices = function () {
  19543. return this._sourceMesh.getIndices();
  19544. };
  19545. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19546. get: function () {
  19547. return this._sourceMesh._positions;
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19553. var meshBB = this._sourceMesh.getBoundingInfo();
  19554. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19555. this._updateBoundingInfo();
  19556. };
  19557. InstancedMesh.prototype._preActivate = function () {
  19558. if (this._currentLOD) {
  19559. this._currentLOD._preActivate();
  19560. }
  19561. };
  19562. InstancedMesh.prototype._activate = function (renderId) {
  19563. if (this._currentLOD) {
  19564. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19565. }
  19566. };
  19567. InstancedMesh.prototype.getLOD = function (camera) {
  19568. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19569. if (this._currentLOD === this.sourceMesh) {
  19570. return this;
  19571. }
  19572. return this._currentLOD;
  19573. };
  19574. InstancedMesh.prototype._syncSubMeshes = function () {
  19575. this.releaseSubMeshes();
  19576. if (this._sourceMesh.subMeshes) {
  19577. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19578. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19579. }
  19580. }
  19581. };
  19582. InstancedMesh.prototype._generatePointsArray = function () {
  19583. return this._sourceMesh._generatePointsArray();
  19584. };
  19585. // Clone
  19586. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19587. var result = this._sourceMesh.createInstance(name);
  19588. // Deep copy
  19589. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19590. // Bounding info
  19591. this.refreshBoundingInfo();
  19592. // Parent
  19593. if (newParent) {
  19594. result.parent = newParent;
  19595. }
  19596. if (!doNotCloneChildren) {
  19597. // Children
  19598. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19599. var mesh = this.getScene().meshes[index];
  19600. if (mesh.parent === this) {
  19601. mesh.clone(mesh.name, result);
  19602. }
  19603. }
  19604. }
  19605. result.computeWorldMatrix(true);
  19606. return result;
  19607. };
  19608. // Dispoe
  19609. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19610. // Remove from mesh
  19611. var index = this._sourceMesh.instances.indexOf(this);
  19612. this._sourceMesh.instances.splice(index, 1);
  19613. _super.prototype.dispose.call(this, doNotRecurse);
  19614. };
  19615. return InstancedMesh;
  19616. }(BABYLON.AbstractMesh));
  19617. BABYLON.InstancedMesh = InstancedMesh;
  19618. })(BABYLON || (BABYLON = {}));
  19619. //# sourceMappingURL=babylon.instancedMesh.js.map
  19620. var BABYLON;
  19621. (function (BABYLON) {
  19622. var _InstancesBatch = (function () {
  19623. function _InstancesBatch() {
  19624. this.mustReturn = false;
  19625. this.visibleInstances = new Array();
  19626. this.renderSelf = new Array();
  19627. }
  19628. return _InstancesBatch;
  19629. }());
  19630. BABYLON._InstancesBatch = _InstancesBatch;
  19631. var Mesh = (function (_super) {
  19632. __extends(Mesh, _super);
  19633. /**
  19634. * @constructor
  19635. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19636. * @param {Scene} scene The scene to add this mesh to.
  19637. * @param {Node} parent The parent of this mesh, if it has one
  19638. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19639. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19640. * When false, achieved by calling a clone(), also passing False.
  19641. * This will make creation of children, recursive.
  19642. */
  19643. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19644. if (parent === void 0) { parent = null; }
  19645. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19646. var _this = _super.call(this, name, scene) || this;
  19647. // Events
  19648. /**
  19649. * An event triggered before rendering the mesh
  19650. * @type {BABYLON.Observable}
  19651. */
  19652. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19653. /**
  19654. * An event triggered after rendering the mesh
  19655. * @type {BABYLON.Observable}
  19656. */
  19657. _this.onAfterRenderObservable = new BABYLON.Observable();
  19658. /**
  19659. * An event triggered before drawing the mesh
  19660. * @type {BABYLON.Observable}
  19661. */
  19662. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19663. // Members
  19664. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19665. _this.instances = new Array();
  19666. _this._LODLevels = new Array();
  19667. _this._visibleInstances = {};
  19668. _this._renderIdForInstances = new Array();
  19669. _this._batchCache = new _InstancesBatch();
  19670. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19671. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19672. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19673. if (source) {
  19674. // Geometry
  19675. if (source._geometry) {
  19676. source._geometry.applyToMesh(_this);
  19677. }
  19678. // Deep copy
  19679. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  19680. // Parent
  19681. _this.parent = source.parent;
  19682. // Pivot
  19683. _this.setPivotMatrix(source.getPivotMatrix());
  19684. _this.id = name + "." + source.id;
  19685. // Material
  19686. _this.material = source.material;
  19687. var index;
  19688. if (!doNotCloneChildren) {
  19689. // Children
  19690. for (index = 0; index < scene.meshes.length; index++) {
  19691. var mesh = scene.meshes[index];
  19692. if (mesh.parent === source) {
  19693. // doNotCloneChildren is always going to be False
  19694. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19695. }
  19696. }
  19697. }
  19698. // Physics clone
  19699. var physicsEngine = _this.getScene().getPhysicsEngine();
  19700. if (clonePhysicsImpostor && physicsEngine) {
  19701. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19702. if (impostor) {
  19703. _this.physicsImpostor = impostor.clone(_this);
  19704. }
  19705. }
  19706. // Particles
  19707. for (index = 0; index < scene.particleSystems.length; index++) {
  19708. var system = scene.particleSystems[index];
  19709. if (system.emitter === source) {
  19710. system.clone(system.name, _this);
  19711. }
  19712. }
  19713. _this.computeWorldMatrix(true);
  19714. }
  19715. // Parent
  19716. if (parent !== null) {
  19717. _this.parent = parent;
  19718. }
  19719. return _this;
  19720. }
  19721. Object.defineProperty(Mesh, "FRONTSIDE", {
  19722. /**
  19723. * Mesh side orientation : usually the external or front surface
  19724. */
  19725. get: function () {
  19726. return Mesh._FRONTSIDE;
  19727. },
  19728. enumerable: true,
  19729. configurable: true
  19730. });
  19731. Object.defineProperty(Mesh, "BACKSIDE", {
  19732. /**
  19733. * Mesh side orientation : usually the internal or back surface
  19734. */
  19735. get: function () {
  19736. return Mesh._BACKSIDE;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19742. /**
  19743. * Mesh side orientation : both internal and external or front and back surfaces
  19744. */
  19745. get: function () {
  19746. return Mesh._DOUBLESIDE;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19752. /**
  19753. * Mesh side orientation : by default, `FRONTSIDE`
  19754. */
  19755. get: function () {
  19756. return Mesh._DEFAULTSIDE;
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(Mesh, "NO_CAP", {
  19762. /**
  19763. * Mesh cap setting : no cap
  19764. */
  19765. get: function () {
  19766. return Mesh._NO_CAP;
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. Object.defineProperty(Mesh, "CAP_START", {
  19772. /**
  19773. * Mesh cap setting : one cap at the beginning of the mesh
  19774. */
  19775. get: function () {
  19776. return Mesh._CAP_START;
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(Mesh, "CAP_END", {
  19782. /**
  19783. * Mesh cap setting : one cap at the end of the mesh
  19784. */
  19785. get: function () {
  19786. return Mesh._CAP_END;
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(Mesh, "CAP_ALL", {
  19792. /**
  19793. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19794. */
  19795. get: function () {
  19796. return Mesh._CAP_ALL;
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19802. set: function (callback) {
  19803. if (this._onBeforeDrawObserver) {
  19804. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19805. }
  19806. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. // Methods
  19812. Mesh.prototype.getClassName = function () {
  19813. return "Mesh";
  19814. };
  19815. /**
  19816. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19817. */
  19818. Mesh.prototype.toString = function (fullDetails) {
  19819. var ret = _super.prototype.toString.call(this, fullDetails);
  19820. ret += ", n vertices: " + this.getTotalVertices();
  19821. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19822. if (this.animations) {
  19823. for (var i = 0; i < this.animations.length; i++) {
  19824. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19825. }
  19826. }
  19827. if (fullDetails) {
  19828. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19829. }
  19830. return ret;
  19831. };
  19832. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19833. get: function () {
  19834. return this._LODLevels.length > 0;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Mesh.prototype._sortLODLevels = function () {
  19840. this._LODLevels.sort(function (a, b) {
  19841. if (a.distance < b.distance) {
  19842. return 1;
  19843. }
  19844. if (a.distance > b.distance) {
  19845. return -1;
  19846. }
  19847. return 0;
  19848. });
  19849. };
  19850. /**
  19851. * Add a mesh as LOD level triggered at the given distance.
  19852. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19853. * @param {number} distance The distance from the center of the object to show this level
  19854. * @param {Mesh} mesh The mesh to be added as LOD level
  19855. * @return {Mesh} This mesh (for chaining)
  19856. */
  19857. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19858. if (mesh && mesh._masterMesh) {
  19859. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19860. return this;
  19861. }
  19862. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19863. this._LODLevels.push(level);
  19864. if (mesh) {
  19865. mesh._masterMesh = this;
  19866. }
  19867. this._sortLODLevels();
  19868. return this;
  19869. };
  19870. /**
  19871. * Returns the LOD level mesh at the passed distance or null if not found.
  19872. * It is related to the method `addLODLevel(distance, mesh)`.
  19873. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19874. */
  19875. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19876. for (var index = 0; index < this._LODLevels.length; index++) {
  19877. var level = this._LODLevels[index];
  19878. if (level.distance === distance) {
  19879. return level.mesh;
  19880. }
  19881. }
  19882. return null;
  19883. };
  19884. /**
  19885. * Remove a mesh from the LOD array
  19886. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19887. * @param {Mesh} mesh The mesh to be removed.
  19888. * @return {Mesh} This mesh (for chaining)
  19889. */
  19890. Mesh.prototype.removeLODLevel = function (mesh) {
  19891. for (var index = 0; index < this._LODLevels.length; index++) {
  19892. if (this._LODLevels[index].mesh === mesh) {
  19893. this._LODLevels.splice(index, 1);
  19894. if (mesh) {
  19895. mesh._masterMesh = null;
  19896. }
  19897. }
  19898. }
  19899. this._sortLODLevels();
  19900. return this;
  19901. };
  19902. /**
  19903. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19904. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19905. */
  19906. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19907. if (!this._LODLevels || this._LODLevels.length === 0) {
  19908. return this;
  19909. }
  19910. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19911. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19912. if (this.onLODLevelSelection) {
  19913. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19914. }
  19915. return this;
  19916. }
  19917. for (var index = 0; index < this._LODLevels.length; index++) {
  19918. var level = this._LODLevels[index];
  19919. if (level.distance < distanceToCamera) {
  19920. if (level.mesh) {
  19921. level.mesh._preActivate();
  19922. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19923. }
  19924. if (this.onLODLevelSelection) {
  19925. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19926. }
  19927. return level.mesh;
  19928. }
  19929. }
  19930. if (this.onLODLevelSelection) {
  19931. this.onLODLevelSelection(distanceToCamera, this, this);
  19932. }
  19933. return this;
  19934. };
  19935. Object.defineProperty(Mesh.prototype, "geometry", {
  19936. /**
  19937. * Returns the mesh internal Geometry object.
  19938. */
  19939. get: function () {
  19940. return this._geometry;
  19941. },
  19942. enumerable: true,
  19943. configurable: true
  19944. });
  19945. /**
  19946. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19947. */
  19948. Mesh.prototype.getTotalVertices = function () {
  19949. if (!this._geometry) {
  19950. return 0;
  19951. }
  19952. return this._geometry.getTotalVertices();
  19953. };
  19954. /**
  19955. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19956. * 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.
  19957. * Returns null if the mesh has no geometry or no vertex buffer.
  19958. * Possible `kind` values :
  19959. * - BABYLON.VertexBuffer.PositionKind
  19960. * - BABYLON.VertexBuffer.UVKind
  19961. * - BABYLON.VertexBuffer.UV2Kind
  19962. * - BABYLON.VertexBuffer.UV3Kind
  19963. * - BABYLON.VertexBuffer.UV4Kind
  19964. * - BABYLON.VertexBuffer.UV5Kind
  19965. * - BABYLON.VertexBuffer.UV6Kind
  19966. * - BABYLON.VertexBuffer.ColorKind
  19967. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19968. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19969. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19970. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19971. */
  19972. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19973. if (!this._geometry) {
  19974. return null;
  19975. }
  19976. return this._geometry.getVerticesData(kind, copyWhenShared);
  19977. };
  19978. /**
  19979. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19980. * Returns `undefined` if the mesh has no geometry.
  19981. * Possible `kind` values :
  19982. * - BABYLON.VertexBuffer.PositionKind
  19983. * - BABYLON.VertexBuffer.UVKind
  19984. * - BABYLON.VertexBuffer.UV2Kind
  19985. * - BABYLON.VertexBuffer.UV3Kind
  19986. * - BABYLON.VertexBuffer.UV4Kind
  19987. * - BABYLON.VertexBuffer.UV5Kind
  19988. * - BABYLON.VertexBuffer.UV6Kind
  19989. * - BABYLON.VertexBuffer.ColorKind
  19990. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19991. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19992. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19993. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19994. */
  19995. Mesh.prototype.getVertexBuffer = function (kind) {
  19996. if (!this._geometry) {
  19997. return undefined;
  19998. }
  19999. return this._geometry.getVertexBuffer(kind);
  20000. };
  20001. /**
  20002. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20003. * Possible `kind` values :
  20004. * - BABYLON.VertexBuffer.PositionKind
  20005. * - BABYLON.VertexBuffer.UVKind
  20006. * - BABYLON.VertexBuffer.UV2Kind
  20007. * - BABYLON.VertexBuffer.UV3Kind
  20008. * - BABYLON.VertexBuffer.UV4Kind
  20009. * - BABYLON.VertexBuffer.UV5Kind
  20010. * - BABYLON.VertexBuffer.UV6Kind
  20011. * - BABYLON.VertexBuffer.ColorKind
  20012. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20013. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20014. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20015. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20016. */
  20017. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20018. if (!this._geometry) {
  20019. if (this._delayInfo) {
  20020. return this._delayInfo.indexOf(kind) !== -1;
  20021. }
  20022. return false;
  20023. }
  20024. return this._geometry.isVerticesDataPresent(kind);
  20025. };
  20026. /**
  20027. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20028. * Possible `kind` values :
  20029. * - BABYLON.VertexBuffer.PositionKind
  20030. * - BABYLON.VertexBuffer.UVKind
  20031. * - BABYLON.VertexBuffer.UV2Kind
  20032. * - BABYLON.VertexBuffer.UV3Kind
  20033. * - BABYLON.VertexBuffer.UV4Kind
  20034. * - BABYLON.VertexBuffer.UV5Kind
  20035. * - BABYLON.VertexBuffer.UV6Kind
  20036. * - BABYLON.VertexBuffer.ColorKind
  20037. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20038. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20039. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20040. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20041. */
  20042. Mesh.prototype.getVerticesDataKinds = function () {
  20043. if (!this._geometry) {
  20044. var result = [];
  20045. if (this._delayInfo) {
  20046. this._delayInfo.forEach(function (kind, index, array) {
  20047. result.push(kind);
  20048. });
  20049. }
  20050. return result;
  20051. }
  20052. return this._geometry.getVerticesDataKinds();
  20053. };
  20054. /**
  20055. * Returns a positive integer : the total number of indices in this mesh geometry.
  20056. * Returns zero if the mesh has no geometry.
  20057. */
  20058. Mesh.prototype.getTotalIndices = function () {
  20059. if (!this._geometry) {
  20060. return 0;
  20061. }
  20062. return this._geometry.getTotalIndices();
  20063. };
  20064. /**
  20065. * Returns an array of integers or a Int32Array populated with the mesh indices.
  20066. * 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.
  20067. * Returns an empty array if the mesh has no geometry.
  20068. */
  20069. Mesh.prototype.getIndices = function (copyWhenShared) {
  20070. if (!this._geometry) {
  20071. return [];
  20072. }
  20073. return this._geometry.getIndices(copyWhenShared);
  20074. };
  20075. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20076. get: function () {
  20077. return this._masterMesh !== null && this._masterMesh !== undefined;
  20078. },
  20079. enumerable: true,
  20080. configurable: true
  20081. });
  20082. /**
  20083. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20084. */
  20085. Mesh.prototype.isReady = function () {
  20086. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20087. return false;
  20088. }
  20089. return _super.prototype.isReady.call(this);
  20090. };
  20091. /**
  20092. * Boolean : true if the mesh has been disposed.
  20093. */
  20094. Mesh.prototype.isDisposed = function () {
  20095. return this._isDisposed;
  20096. };
  20097. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20098. get: function () {
  20099. return this._sideOrientation;
  20100. },
  20101. /**
  20102. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20103. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20104. */
  20105. set: function (sideO) {
  20106. this._sideOrientation = sideO;
  20107. },
  20108. enumerable: true,
  20109. configurable: true
  20110. });
  20111. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20112. /**
  20113. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20114. * This property is pertinent only for updatable parametric shapes.
  20115. */
  20116. get: function () {
  20117. return this._areNormalsFrozen;
  20118. },
  20119. enumerable: true,
  20120. configurable: true
  20121. });
  20122. /**
  20123. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20124. * It has no effect at all on other shapes.
  20125. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20126. */
  20127. Mesh.prototype.freezeNormals = function () {
  20128. this._areNormalsFrozen = true;
  20129. };
  20130. /**
  20131. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20132. * It has no effect at all on other shapes.
  20133. * It reactivates the mesh normals computation if it was previously frozen.
  20134. */
  20135. Mesh.prototype.unfreezeNormals = function () {
  20136. this._areNormalsFrozen = false;
  20137. };
  20138. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20139. /**
  20140. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20141. */
  20142. set: function (count) {
  20143. this._overridenInstanceCount = count;
  20144. },
  20145. enumerable: true,
  20146. configurable: true
  20147. });
  20148. // Methods
  20149. Mesh.prototype._preActivate = function () {
  20150. var sceneRenderId = this.getScene().getRenderId();
  20151. if (this._preActivateId === sceneRenderId) {
  20152. return;
  20153. }
  20154. this._preActivateId = sceneRenderId;
  20155. this._visibleInstances = null;
  20156. };
  20157. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20158. if (this._visibleInstances) {
  20159. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20160. }
  20161. };
  20162. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20163. if (!this._visibleInstances) {
  20164. this._visibleInstances = {};
  20165. this._visibleInstances.defaultRenderId = renderId;
  20166. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20167. }
  20168. if (!this._visibleInstances[renderId]) {
  20169. this._visibleInstances[renderId] = new Array();
  20170. }
  20171. this._visibleInstances[renderId].push(instance);
  20172. };
  20173. /**
  20174. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20175. * This means the mesh underlying bounding box and sphere are recomputed.
  20176. */
  20177. Mesh.prototype.refreshBoundingInfo = function () {
  20178. if (this._boundingInfo.isLocked) {
  20179. return;
  20180. }
  20181. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20182. if (data) {
  20183. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20184. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20185. }
  20186. if (this.subMeshes) {
  20187. for (var index = 0; index < this.subMeshes.length; index++) {
  20188. this.subMeshes[index].refreshBoundingInfo();
  20189. }
  20190. }
  20191. this._updateBoundingInfo();
  20192. };
  20193. Mesh.prototype._createGlobalSubMesh = function () {
  20194. var totalVertices = this.getTotalVertices();
  20195. if (!totalVertices || !this.getIndices()) {
  20196. return null;
  20197. }
  20198. this.releaseSubMeshes();
  20199. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20200. };
  20201. Mesh.prototype.subdivide = function (count) {
  20202. if (count < 1) {
  20203. return;
  20204. }
  20205. var totalIndices = this.getTotalIndices();
  20206. var subdivisionSize = (totalIndices / count) | 0;
  20207. var offset = 0;
  20208. // Ensure that subdivisionSize is a multiple of 3
  20209. while (subdivisionSize % 3 !== 0) {
  20210. subdivisionSize++;
  20211. }
  20212. this.releaseSubMeshes();
  20213. for (var index = 0; index < count; index++) {
  20214. if (offset >= totalIndices) {
  20215. break;
  20216. }
  20217. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20218. offset += subdivisionSize;
  20219. }
  20220. this.synchronizeInstances();
  20221. };
  20222. /**
  20223. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20224. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20225. * The `data` are either a numeric array either a Float32Array.
  20226. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20227. * 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).
  20228. * Note that a new underlying VertexBuffer object is created each call.
  20229. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20230. *
  20231. * Possible `kind` values :
  20232. * - BABYLON.VertexBuffer.PositionKind
  20233. * - BABYLON.VertexBuffer.UVKind
  20234. * - BABYLON.VertexBuffer.UV2Kind
  20235. * - BABYLON.VertexBuffer.UV3Kind
  20236. * - BABYLON.VertexBuffer.UV4Kind
  20237. * - BABYLON.VertexBuffer.UV5Kind
  20238. * - BABYLON.VertexBuffer.UV6Kind
  20239. * - BABYLON.VertexBuffer.ColorKind
  20240. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20241. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20242. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20243. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20244. */
  20245. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20246. if (!this._geometry) {
  20247. var vertexData = new BABYLON.VertexData();
  20248. vertexData.set(data, kind);
  20249. var scene = this.getScene();
  20250. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20251. }
  20252. else {
  20253. this._geometry.setVerticesData(kind, data, updatable, stride);
  20254. }
  20255. };
  20256. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20257. if (!this._geometry) {
  20258. var scene = this.getScene();
  20259. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20260. }
  20261. this._geometry.setVerticesBuffer(buffer);
  20262. };
  20263. /**
  20264. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20265. * If the mesh has no geometry, it is simply returned as it is.
  20266. * The `data` are either a numeric array either a Float32Array.
  20267. * No new underlying VertexBuffer object is created.
  20268. * 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.
  20269. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20270. *
  20271. * Possible `kind` values :
  20272. * - BABYLON.VertexBuffer.PositionKind
  20273. * - BABYLON.VertexBuffer.UVKind
  20274. * - BABYLON.VertexBuffer.UV2Kind
  20275. * - BABYLON.VertexBuffer.UV3Kind
  20276. * - BABYLON.VertexBuffer.UV4Kind
  20277. * - BABYLON.VertexBuffer.UV5Kind
  20278. * - BABYLON.VertexBuffer.UV6Kind
  20279. * - BABYLON.VertexBuffer.ColorKind
  20280. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20281. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20282. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20283. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20284. */
  20285. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20286. if (!this._geometry) {
  20287. return;
  20288. }
  20289. if (!makeItUnique) {
  20290. this._geometry.updateVerticesData(kind, data, updateExtends);
  20291. }
  20292. else {
  20293. this.makeGeometryUnique();
  20294. this.updateVerticesData(kind, data, updateExtends, false);
  20295. }
  20296. };
  20297. /**
  20298. * Deprecated since BabylonJS v2.3
  20299. */
  20300. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20301. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20302. if (!this._geometry) {
  20303. return;
  20304. }
  20305. if (!makeItUnique) {
  20306. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20307. }
  20308. else {
  20309. this.makeGeometryUnique();
  20310. this.updateVerticesDataDirectly(kind, data, offset, false);
  20311. }
  20312. };
  20313. /**
  20314. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20315. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20316. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20317. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20318. */
  20319. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20320. if (computeNormals === void 0) { computeNormals = true; }
  20321. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20322. positionFunction(positions);
  20323. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20324. if (computeNormals) {
  20325. var indices = this.getIndices();
  20326. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20327. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20328. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20329. }
  20330. };
  20331. Mesh.prototype.makeGeometryUnique = function () {
  20332. if (!this._geometry) {
  20333. return;
  20334. }
  20335. var oldGeometry = this._geometry;
  20336. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20337. oldGeometry.releaseForMesh(this, true);
  20338. geometry.applyToMesh(this);
  20339. };
  20340. /**
  20341. * Sets the mesh indices.
  20342. * Expects an array populated with integers or a Int32Array.
  20343. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20344. * This method creates a new index buffer each call.
  20345. */
  20346. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20347. if (!this._geometry) {
  20348. var vertexData = new BABYLON.VertexData();
  20349. vertexData.indices = indices;
  20350. var scene = this.getScene();
  20351. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20352. }
  20353. else {
  20354. this._geometry.setIndices(indices, totalVertices);
  20355. }
  20356. };
  20357. /**
  20358. * Invert the geometry to move from a right handed system to a left handed one.
  20359. */
  20360. Mesh.prototype.toLeftHanded = function () {
  20361. if (!this._geometry) {
  20362. return;
  20363. }
  20364. this._geometry.toLeftHanded();
  20365. };
  20366. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20367. var engine = this.getScene().getEngine();
  20368. // Wireframe
  20369. var indexToBind;
  20370. if (this._unIndexed) {
  20371. indexToBind = null;
  20372. }
  20373. else {
  20374. switch (fillMode) {
  20375. case BABYLON.Material.PointFillMode:
  20376. indexToBind = null;
  20377. break;
  20378. case BABYLON.Material.WireFrameFillMode:
  20379. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20380. break;
  20381. default:
  20382. case BABYLON.Material.TriangleFillMode:
  20383. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20384. break;
  20385. }
  20386. }
  20387. // VBOs
  20388. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  20389. };
  20390. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20391. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20392. return;
  20393. }
  20394. this.onBeforeDrawObservable.notifyObservers(this);
  20395. var engine = this.getScene().getEngine();
  20396. // Draw order
  20397. switch (fillMode) {
  20398. case BABYLON.Material.PointFillMode:
  20399. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20400. break;
  20401. case BABYLON.Material.WireFrameFillMode:
  20402. if (this._unIndexed) {
  20403. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20404. }
  20405. else {
  20406. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20407. }
  20408. break;
  20409. default:
  20410. if (this._unIndexed) {
  20411. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20412. }
  20413. else {
  20414. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20415. }
  20416. }
  20417. };
  20418. /**
  20419. * Registers for this mesh a javascript function called just before the rendering process.
  20420. * This function is passed the current mesh and doesn't return anything.
  20421. */
  20422. Mesh.prototype.registerBeforeRender = function (func) {
  20423. this.onBeforeRenderObservable.add(func);
  20424. };
  20425. /**
  20426. * Disposes a previously registered javascript function called before the rendering.
  20427. * This function is passed the current mesh and doesn't return anything.
  20428. */
  20429. Mesh.prototype.unregisterBeforeRender = function (func) {
  20430. this.onBeforeRenderObservable.removeCallback(func);
  20431. };
  20432. /**
  20433. * Registers for this mesh a javascript function called just after the rendering is complete.
  20434. * This function is passed the current mesh and doesn't return anything.
  20435. */
  20436. Mesh.prototype.registerAfterRender = function (func) {
  20437. this.onAfterRenderObservable.add(func);
  20438. };
  20439. /**
  20440. * Disposes a previously registered javascript function called after the rendering.
  20441. * This function is passed the current mesh and doesn't return anything.
  20442. */
  20443. Mesh.prototype.unregisterAfterRender = function (func) {
  20444. this.onAfterRenderObservable.removeCallback(func);
  20445. };
  20446. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20447. var scene = this.getScene();
  20448. this._batchCache.mustReturn = false;
  20449. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20450. this._batchCache.visibleInstances[subMeshId] = null;
  20451. if (this._visibleInstances) {
  20452. var currentRenderId = scene.getRenderId();
  20453. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20454. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20455. var selfRenderId = this._renderId;
  20456. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20457. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20458. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20459. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20460. }
  20461. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20462. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20463. this._batchCache.mustReturn = true;
  20464. return this._batchCache;
  20465. }
  20466. if (currentRenderId !== selfRenderId) {
  20467. this._batchCache.renderSelf[subMeshId] = false;
  20468. }
  20469. }
  20470. this._renderIdForInstances[subMeshId] = currentRenderId;
  20471. }
  20472. return this._batchCache;
  20473. };
  20474. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20475. var visibleInstances = batch.visibleInstances[subMesh._id];
  20476. var matricesCount = visibleInstances.length + 1;
  20477. var bufferSize = matricesCount * 16 * 4;
  20478. var currentInstancesBufferSize = this._instancesBufferSize;
  20479. var instancesBuffer = this._instancesBuffer;
  20480. while (this._instancesBufferSize < bufferSize) {
  20481. this._instancesBufferSize *= 2;
  20482. }
  20483. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20484. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20485. }
  20486. var offset = 0;
  20487. var instancesCount = 0;
  20488. var world = this.getWorldMatrix();
  20489. if (batch.renderSelf[subMesh._id]) {
  20490. world.copyToArray(this._instancesData, offset);
  20491. offset += 16;
  20492. instancesCount++;
  20493. }
  20494. if (visibleInstances) {
  20495. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20496. var instance = visibleInstances[instanceIndex];
  20497. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20498. offset += 16;
  20499. instancesCount++;
  20500. }
  20501. }
  20502. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20503. if (instancesBuffer) {
  20504. instancesBuffer.dispose();
  20505. }
  20506. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20507. this._instancesBuffer = instancesBuffer;
  20508. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20509. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20510. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20511. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20512. }
  20513. else {
  20514. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20515. }
  20516. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20517. this._draw(subMesh, fillMode, instancesCount);
  20518. engine.unbindInstanceAttributes();
  20519. };
  20520. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20521. var scene = this.getScene();
  20522. var engine = scene.getEngine();
  20523. if (hardwareInstancedRendering) {
  20524. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20525. }
  20526. else {
  20527. if (batch.renderSelf[subMesh._id]) {
  20528. // Draw
  20529. if (onBeforeDraw) {
  20530. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20531. }
  20532. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20533. }
  20534. if (batch.visibleInstances[subMesh._id]) {
  20535. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20536. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20537. // World
  20538. var world = instance.getWorldMatrix();
  20539. if (onBeforeDraw) {
  20540. onBeforeDraw(true, world, effectiveMaterial);
  20541. }
  20542. // Draw
  20543. this._draw(subMesh, fillMode);
  20544. }
  20545. }
  20546. }
  20547. };
  20548. /**
  20549. * Triggers the draw call for the mesh.
  20550. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20551. */
  20552. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20553. var scene = this.getScene();
  20554. // Managing instances
  20555. var batch = this._getInstancesRenderList(subMesh._id);
  20556. if (batch.mustReturn) {
  20557. return;
  20558. }
  20559. // Checking geometry state
  20560. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20561. return;
  20562. }
  20563. var callbackIndex;
  20564. this.onBeforeRenderObservable.notifyObservers(this);
  20565. var engine = scene.getEngine();
  20566. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20567. // Material
  20568. var effectiveMaterial = subMesh.getMaterial();
  20569. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20570. return;
  20571. }
  20572. // Outline - step 1
  20573. var savedDepthWrite = engine.getDepthWrite();
  20574. if (this.renderOutline) {
  20575. engine.setDepthWrite(false);
  20576. scene.getOutlineRenderer().render(subMesh, batch);
  20577. engine.setDepthWrite(savedDepthWrite);
  20578. }
  20579. effectiveMaterial._preBind();
  20580. var effect = effectiveMaterial.getEffect();
  20581. // Bind
  20582. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20583. this._bind(subMesh, effect, fillMode);
  20584. var world = this.getWorldMatrix();
  20585. effectiveMaterial.bind(world, this);
  20586. // Alpha mode
  20587. if (enableAlphaMode) {
  20588. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20589. }
  20590. // Draw
  20591. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20592. // Unbind
  20593. effectiveMaterial.unbind();
  20594. // Outline - step 2
  20595. if (this.renderOutline && savedDepthWrite) {
  20596. engine.setDepthWrite(true);
  20597. engine.setColorWrite(false);
  20598. scene.getOutlineRenderer().render(subMesh, batch);
  20599. engine.setColorWrite(true);
  20600. }
  20601. // Overlay
  20602. if (this.renderOverlay) {
  20603. var currentMode = engine.getAlphaMode();
  20604. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20605. scene.getOutlineRenderer().render(subMesh, batch, true);
  20606. engine.setAlphaMode(currentMode);
  20607. }
  20608. this.onAfterRenderObservable.notifyObservers(this);
  20609. };
  20610. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20611. if (isInstance) {
  20612. effectiveMaterial.bindOnlyWorldMatrix(world);
  20613. }
  20614. };
  20615. /**
  20616. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20617. */
  20618. Mesh.prototype.getEmittedParticleSystems = function () {
  20619. var results = new Array();
  20620. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20621. var particleSystem = this.getScene().particleSystems[index];
  20622. if (particleSystem.emitter === this) {
  20623. results.push(particleSystem);
  20624. }
  20625. }
  20626. return results;
  20627. };
  20628. /**
  20629. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20630. */
  20631. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20632. var results = new Array();
  20633. var descendants = this.getDescendants();
  20634. descendants.push(this);
  20635. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20636. var particleSystem = this.getScene().particleSystems[index];
  20637. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20638. results.push(particleSystem);
  20639. }
  20640. }
  20641. return results;
  20642. };
  20643. Mesh.prototype._checkDelayState = function () {
  20644. var scene = this.getScene();
  20645. if (this._geometry) {
  20646. this._geometry.load(scene);
  20647. }
  20648. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20649. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20650. this._queueLoad(this, scene);
  20651. }
  20652. };
  20653. Mesh.prototype._queueLoad = function (mesh, scene) {
  20654. var _this = this;
  20655. scene._addPendingData(mesh);
  20656. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20657. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20658. if (data instanceof ArrayBuffer) {
  20659. _this._delayLoadingFunction(data, _this);
  20660. }
  20661. else {
  20662. _this._delayLoadingFunction(JSON.parse(data), _this);
  20663. }
  20664. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20665. scene._removePendingData(_this);
  20666. }, function () { }, scene.database, getBinaryData);
  20667. };
  20668. /**
  20669. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20670. */
  20671. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20672. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20673. return false;
  20674. }
  20675. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20676. return false;
  20677. }
  20678. this._checkDelayState();
  20679. return true;
  20680. };
  20681. /**
  20682. * Sets the mesh material by the material or multiMaterial `id` property.
  20683. * The material `id` is a string identifying the material or the multiMaterial.
  20684. * This method returns nothing.
  20685. */
  20686. Mesh.prototype.setMaterialByID = function (id) {
  20687. var materials = this.getScene().materials;
  20688. var index;
  20689. for (index = 0; index < materials.length; index++) {
  20690. if (materials[index].id === id) {
  20691. this.material = materials[index];
  20692. return;
  20693. }
  20694. }
  20695. // Multi
  20696. var multiMaterials = this.getScene().multiMaterials;
  20697. for (index = 0; index < multiMaterials.length; index++) {
  20698. if (multiMaterials[index].id === id) {
  20699. this.material = multiMaterials[index];
  20700. return;
  20701. }
  20702. }
  20703. };
  20704. /**
  20705. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20706. */
  20707. Mesh.prototype.getAnimatables = function () {
  20708. var results = [];
  20709. if (this.material) {
  20710. results.push(this.material);
  20711. }
  20712. if (this.skeleton) {
  20713. results.push(this.skeleton);
  20714. }
  20715. return results;
  20716. };
  20717. /**
  20718. * Modifies the mesh geometry according to the passed transformation matrix.
  20719. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20720. * The mesh normals are modified accordingly the same transformation.
  20721. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20722. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20723. */
  20724. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20725. // Position
  20726. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20727. return;
  20728. }
  20729. var submeshes = this.subMeshes.splice(0);
  20730. this._resetPointsArrayCache();
  20731. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20732. var temp = [];
  20733. var index;
  20734. for (index = 0; index < data.length; index += 3) {
  20735. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20736. }
  20737. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20738. // Normals
  20739. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20740. return;
  20741. }
  20742. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20743. temp = [];
  20744. for (index = 0; index < data.length; index += 3) {
  20745. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20746. }
  20747. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20748. // flip faces?
  20749. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20750. this.flipFaces();
  20751. }
  20752. // Restore submeshes
  20753. this.releaseSubMeshes();
  20754. this.subMeshes = submeshes;
  20755. };
  20756. /**
  20757. * Modifies the mesh geometry according to its own current World Matrix.
  20758. * The mesh World Matrix is then reset.
  20759. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20760. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20761. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20762. */
  20763. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20764. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20765. this.scaling.copyFromFloats(1, 1, 1);
  20766. this.position.copyFromFloats(0, 0, 0);
  20767. this.rotation.copyFromFloats(0, 0, 0);
  20768. //only if quaternion is already set
  20769. if (this.rotationQuaternion) {
  20770. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20771. }
  20772. this._worldMatrix = BABYLON.Matrix.Identity();
  20773. };
  20774. // Cache
  20775. Mesh.prototype._resetPointsArrayCache = function () {
  20776. this._positions = null;
  20777. };
  20778. Mesh.prototype._generatePointsArray = function () {
  20779. if (this._positions)
  20780. return true;
  20781. this._positions = [];
  20782. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20783. if (!data) {
  20784. return false;
  20785. }
  20786. for (var index = 0; index < data.length; index += 3) {
  20787. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20788. }
  20789. return true;
  20790. };
  20791. /**
  20792. * Returns a new Mesh object generated from the current mesh properties.
  20793. * This method must not get confused with createInstance().
  20794. * The parameter `name` is a string, the name given to the new mesh.
  20795. * The optional parameter `newParent` can be any Node object (default `null`).
  20796. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20797. * 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.
  20798. */
  20799. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20800. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20801. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20802. };
  20803. /**
  20804. * Disposes the mesh.
  20805. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20806. */
  20807. Mesh.prototype.dispose = function (doNotRecurse) {
  20808. if (this._geometry) {
  20809. this._geometry.releaseForMesh(this, true);
  20810. }
  20811. // Instances
  20812. if (this._instancesBuffer) {
  20813. this._instancesBuffer.dispose();
  20814. this._instancesBuffer = null;
  20815. }
  20816. while (this.instances.length) {
  20817. this.instances[0].dispose();
  20818. }
  20819. // Highlight layers.
  20820. var highlightLayers = this.getScene().highlightLayers;
  20821. for (var i = 0; i < highlightLayers.length; i++) {
  20822. var highlightLayer = highlightLayers[i];
  20823. if (highlightLayer) {
  20824. highlightLayer.removeMesh(this);
  20825. highlightLayer.removeExcludedMesh(this);
  20826. }
  20827. }
  20828. _super.prototype.dispose.call(this, doNotRecurse);
  20829. };
  20830. /**
  20831. * Modifies the mesh geometry according to a displacement map.
  20832. * 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.
  20833. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20834. * This method returns nothing.
  20835. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20836. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20837. * 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.
  20838. */
  20839. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20840. var _this = this;
  20841. var scene = this.getScene();
  20842. var onload = function (img) {
  20843. // Getting height map data
  20844. var canvas = document.createElement("canvas");
  20845. var context = canvas.getContext("2d");
  20846. var heightMapWidth = img.width;
  20847. var heightMapHeight = img.height;
  20848. canvas.width = heightMapWidth;
  20849. canvas.height = heightMapHeight;
  20850. context.drawImage(img, 0, 0);
  20851. // Create VertexData from map data
  20852. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20853. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20854. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20855. //execute success callback, if set
  20856. if (onSuccess) {
  20857. onSuccess(_this);
  20858. }
  20859. };
  20860. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20861. };
  20862. /**
  20863. * Modifies the mesh geometry according to a displacementMap buffer.
  20864. * 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.
  20865. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20866. * This method returns nothing.
  20867. * 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.
  20868. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20869. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20870. */
  20871. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20872. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20873. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20874. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20875. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20876. return;
  20877. }
  20878. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20879. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20880. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20881. var position = BABYLON.Vector3.Zero();
  20882. var normal = BABYLON.Vector3.Zero();
  20883. var uv = BABYLON.Vector2.Zero();
  20884. for (var index = 0; index < positions.length; index += 3) {
  20885. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20886. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20887. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20888. // Compute height
  20889. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20890. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20891. var pos = (u + v * heightMapWidth) * 4;
  20892. var r = buffer[pos] / 255.0;
  20893. var g = buffer[pos + 1] / 255.0;
  20894. var b = buffer[pos + 2] / 255.0;
  20895. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20896. normal.normalize();
  20897. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20898. position = position.add(normal);
  20899. position.toArray(positions, index);
  20900. }
  20901. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20902. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20903. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20904. };
  20905. /**
  20906. * Modify the mesh to get a flat shading rendering.
  20907. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20908. * This method returns nothing.
  20909. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20910. */
  20911. Mesh.prototype.convertToFlatShadedMesh = function () {
  20912. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20913. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20914. var kinds = this.getVerticesDataKinds();
  20915. var vbs = [];
  20916. var data = [];
  20917. var newdata = [];
  20918. var updatableNormals = false;
  20919. var kindIndex;
  20920. var kind;
  20921. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20922. kind = kinds[kindIndex];
  20923. var vertexBuffer = this.getVertexBuffer(kind);
  20924. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20925. updatableNormals = vertexBuffer.isUpdatable();
  20926. kinds.splice(kindIndex, 1);
  20927. kindIndex--;
  20928. continue;
  20929. }
  20930. vbs[kind] = vertexBuffer;
  20931. data[kind] = vbs[kind].getData();
  20932. newdata[kind] = [];
  20933. }
  20934. // Save previous submeshes
  20935. var previousSubmeshes = this.subMeshes.slice(0);
  20936. var indices = this.getIndices();
  20937. var totalIndices = this.getTotalIndices();
  20938. // Generating unique vertices per face
  20939. var index;
  20940. for (index = 0; index < totalIndices; index++) {
  20941. var vertexIndex = indices[index];
  20942. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20943. kind = kinds[kindIndex];
  20944. var stride = vbs[kind].getStrideSize();
  20945. for (var offset = 0; offset < stride; offset++) {
  20946. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20947. }
  20948. }
  20949. }
  20950. // Updating faces & normal
  20951. var normals = [];
  20952. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20953. for (index = 0; index < totalIndices; index += 3) {
  20954. indices[index] = index;
  20955. indices[index + 1] = index + 1;
  20956. indices[index + 2] = index + 2;
  20957. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20958. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20959. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20960. var p1p2 = p1.subtract(p2);
  20961. var p3p2 = p3.subtract(p2);
  20962. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20963. // Store same normals for every vertex
  20964. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20965. normals.push(normal.x);
  20966. normals.push(normal.y);
  20967. normals.push(normal.z);
  20968. }
  20969. }
  20970. this.setIndices(indices);
  20971. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20972. // Updating vertex buffers
  20973. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20974. kind = kinds[kindIndex];
  20975. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20976. }
  20977. // Updating submeshes
  20978. this.releaseSubMeshes();
  20979. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20980. var previousOne = previousSubmeshes[submeshIndex];
  20981. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20982. }
  20983. this.synchronizeInstances();
  20984. };
  20985. /**
  20986. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20987. * In other words, more vertices, no more indices and a single bigger VBO.
  20988. * This method returns nothing.
  20989. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20990. *
  20991. */
  20992. Mesh.prototype.convertToUnIndexedMesh = function () {
  20993. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20994. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20995. var kinds = this.getVerticesDataKinds();
  20996. var vbs = [];
  20997. var data = [];
  20998. var newdata = [];
  20999. var updatableNormals = false;
  21000. var kindIndex;
  21001. var kind;
  21002. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21003. kind = kinds[kindIndex];
  21004. var vertexBuffer = this.getVertexBuffer(kind);
  21005. vbs[kind] = vertexBuffer;
  21006. data[kind] = vbs[kind].getData();
  21007. newdata[kind] = [];
  21008. }
  21009. // Save previous submeshes
  21010. var previousSubmeshes = this.subMeshes.slice(0);
  21011. var indices = this.getIndices();
  21012. var totalIndices = this.getTotalIndices();
  21013. // Generating unique vertices per face
  21014. var index;
  21015. for (index = 0; index < totalIndices; index++) {
  21016. var vertexIndex = indices[index];
  21017. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21018. kind = kinds[kindIndex];
  21019. var stride = vbs[kind].getStrideSize();
  21020. for (var offset = 0; offset < stride; offset++) {
  21021. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21022. }
  21023. }
  21024. }
  21025. // Updating indices
  21026. for (index = 0; index < totalIndices; index += 3) {
  21027. indices[index] = index;
  21028. indices[index + 1] = index + 1;
  21029. indices[index + 2] = index + 2;
  21030. }
  21031. this.setIndices(indices);
  21032. // Updating vertex buffers
  21033. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21034. kind = kinds[kindIndex];
  21035. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21036. }
  21037. // Updating submeshes
  21038. this.releaseSubMeshes();
  21039. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21040. var previousOne = previousSubmeshes[submeshIndex];
  21041. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21042. }
  21043. this._unIndexed = true;
  21044. this.synchronizeInstances();
  21045. };
  21046. /**
  21047. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21048. * This method returns nothing.
  21049. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21050. */
  21051. Mesh.prototype.flipFaces = function (flipNormals) {
  21052. if (flipNormals === void 0) { flipNormals = false; }
  21053. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21054. var i;
  21055. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21056. for (i = 0; i < vertex_data.normals.length; i++) {
  21057. vertex_data.normals[i] *= -1;
  21058. }
  21059. }
  21060. var temp;
  21061. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21062. // reassign indices
  21063. temp = vertex_data.indices[i + 1];
  21064. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21065. vertex_data.indices[i + 2] = temp;
  21066. }
  21067. vertex_data.applyToMesh(this);
  21068. };
  21069. // Instances
  21070. /**
  21071. * Creates a new InstancedMesh object from the mesh model.
  21072. * An instance shares the same properties and the same material than its model.
  21073. * Only these properties of each instance can then be set individually :
  21074. * - position
  21075. * - rotation
  21076. * - rotationQuaternion
  21077. * - setPivotMatrix
  21078. * - scaling
  21079. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21080. * Warning : this method is not supported for Line mesh and LineSystem
  21081. */
  21082. Mesh.prototype.createInstance = function (name) {
  21083. return new BABYLON.InstancedMesh(name, this);
  21084. };
  21085. /**
  21086. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21087. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21088. * This method returns nothing.
  21089. */
  21090. Mesh.prototype.synchronizeInstances = function () {
  21091. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21092. var instance = this.instances[instanceIndex];
  21093. instance._syncSubMeshes();
  21094. }
  21095. };
  21096. /**
  21097. * Simplify the mesh according to the given array of settings.
  21098. * Function will return immediately and will simplify async. It returns nothing.
  21099. * @param settings a collection of simplification settings.
  21100. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21101. * @param type the type of simplification to run.
  21102. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21103. */
  21104. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21105. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21106. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21107. this.getScene().simplificationQueue.addTask({
  21108. settings: settings,
  21109. parallelProcessing: parallelProcessing,
  21110. mesh: this,
  21111. simplificationType: simplificationType,
  21112. successCallback: successCallback
  21113. });
  21114. };
  21115. /**
  21116. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21117. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21118. * This should be used together with the simplification to avoid disappearing triangles.
  21119. * @param successCallback an optional success callback to be called after the optimization finished.
  21120. */
  21121. Mesh.prototype.optimizeIndices = function (successCallback) {
  21122. var _this = this;
  21123. var indices = this.getIndices();
  21124. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21125. var vectorPositions = [];
  21126. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21127. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21128. }
  21129. var dupes = [];
  21130. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21131. var realPos = vectorPositions.length - 1 - iteration;
  21132. var testedPosition = vectorPositions[realPos];
  21133. for (var j = 0; j < realPos; ++j) {
  21134. var againstPosition = vectorPositions[j];
  21135. if (testedPosition.equals(againstPosition)) {
  21136. dupes[realPos] = j;
  21137. break;
  21138. }
  21139. }
  21140. }, function () {
  21141. for (var i = 0; i < indices.length; ++i) {
  21142. indices[i] = dupes[indices[i]] || indices[i];
  21143. }
  21144. //indices are now reordered
  21145. var originalSubMeshes = _this.subMeshes.slice(0);
  21146. _this.setIndices(indices);
  21147. _this.subMeshes = originalSubMeshes;
  21148. if (successCallback) {
  21149. successCallback(_this);
  21150. }
  21151. });
  21152. };
  21153. // Statics
  21154. /**
  21155. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21156. * The parameter `parsedMesh` is the mesh to be copied.
  21157. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21158. */
  21159. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21160. var mesh = new Mesh(parsedMesh.name, scene);
  21161. mesh.id = parsedMesh.id;
  21162. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21163. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21164. if (parsedMesh.metadata !== undefined) {
  21165. mesh.metadata = parsedMesh.metadata;
  21166. }
  21167. if (parsedMesh.rotationQuaternion) {
  21168. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21169. }
  21170. else if (parsedMesh.rotation) {
  21171. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21172. }
  21173. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21174. if (parsedMesh.localMatrix) {
  21175. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21176. }
  21177. else if (parsedMesh.pivotMatrix) {
  21178. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21179. }
  21180. mesh.setEnabled(parsedMesh.isEnabled);
  21181. mesh.isVisible = parsedMesh.isVisible;
  21182. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21183. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21184. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21185. if (parsedMesh.applyFog !== undefined) {
  21186. mesh.applyFog = parsedMesh.applyFog;
  21187. }
  21188. if (parsedMesh.pickable !== undefined) {
  21189. mesh.isPickable = parsedMesh.pickable;
  21190. }
  21191. if (parsedMesh.alphaIndex !== undefined) {
  21192. mesh.alphaIndex = parsedMesh.alphaIndex;
  21193. }
  21194. mesh.receiveShadows = parsedMesh.receiveShadows;
  21195. mesh.billboardMode = parsedMesh.billboardMode;
  21196. if (parsedMesh.visibility !== undefined) {
  21197. mesh.visibility = parsedMesh.visibility;
  21198. }
  21199. mesh.checkCollisions = parsedMesh.checkCollisions;
  21200. if (parsedMesh.isBlocker !== undefined) {
  21201. mesh.isBlocker = parsedMesh.isBlocker;
  21202. }
  21203. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21204. // freezeWorldMatrix
  21205. if (parsedMesh.freezeWorldMatrix) {
  21206. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21207. }
  21208. // Parent
  21209. if (parsedMesh.parentId) {
  21210. mesh._waitingParentId = parsedMesh.parentId;
  21211. }
  21212. // Actions
  21213. if (parsedMesh.actions !== undefined) {
  21214. mesh._waitingActions = parsedMesh.actions;
  21215. }
  21216. // Overlay
  21217. if (parsedMesh.overlayAlpha !== undefined) {
  21218. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21219. }
  21220. if (parsedMesh.overlayColor !== undefined) {
  21221. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21222. }
  21223. if (parsedMesh.renderOverlay !== undefined) {
  21224. mesh.renderOverlay = parsedMesh.renderOverlay;
  21225. }
  21226. // Geometry
  21227. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21228. if (parsedMesh.delayLoadingFile) {
  21229. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21230. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21231. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21232. if (parsedMesh._binaryInfo) {
  21233. mesh._binaryInfo = parsedMesh._binaryInfo;
  21234. }
  21235. mesh._delayInfo = [];
  21236. if (parsedMesh.hasUVs) {
  21237. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21238. }
  21239. if (parsedMesh.hasUVs2) {
  21240. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21241. }
  21242. if (parsedMesh.hasUVs3) {
  21243. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21244. }
  21245. if (parsedMesh.hasUVs4) {
  21246. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21247. }
  21248. if (parsedMesh.hasUVs5) {
  21249. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21250. }
  21251. if (parsedMesh.hasUVs6) {
  21252. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21253. }
  21254. if (parsedMesh.hasColors) {
  21255. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21256. }
  21257. if (parsedMesh.hasMatricesIndices) {
  21258. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21259. }
  21260. if (parsedMesh.hasMatricesWeights) {
  21261. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21262. }
  21263. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21264. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21265. mesh._checkDelayState();
  21266. }
  21267. }
  21268. else {
  21269. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21270. }
  21271. // Material
  21272. if (parsedMesh.materialId) {
  21273. mesh.setMaterialByID(parsedMesh.materialId);
  21274. }
  21275. else {
  21276. mesh.material = null;
  21277. }
  21278. // Skeleton
  21279. if (parsedMesh.skeletonId > -1) {
  21280. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21281. if (parsedMesh.numBoneInfluencers) {
  21282. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21283. }
  21284. }
  21285. // Animations
  21286. if (parsedMesh.animations) {
  21287. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21288. var parsedAnimation = parsedMesh.animations[animationIndex];
  21289. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21290. }
  21291. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21292. }
  21293. if (parsedMesh.autoAnimate) {
  21294. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21295. }
  21296. // Layer Mask
  21297. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21298. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21299. }
  21300. else {
  21301. mesh.layerMask = 0x0FFFFFFF;
  21302. }
  21303. //(Deprecated) physics
  21304. if (parsedMesh.physicsImpostor) {
  21305. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21306. mass: parsedMesh.physicsMass,
  21307. friction: parsedMesh.physicsFriction,
  21308. restitution: parsedMesh.physicsRestitution
  21309. }, scene);
  21310. }
  21311. // Instances
  21312. if (parsedMesh.instances) {
  21313. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21314. var parsedInstance = parsedMesh.instances[index];
  21315. var instance = mesh.createInstance(parsedInstance.name);
  21316. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21317. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21318. if (parsedInstance.parentId) {
  21319. instance._waitingParentId = parsedInstance.parentId;
  21320. }
  21321. if (parsedInstance.rotationQuaternion) {
  21322. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21323. }
  21324. else if (parsedInstance.rotation) {
  21325. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21326. }
  21327. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21328. instance.checkCollisions = mesh.checkCollisions;
  21329. if (parsedMesh.animations) {
  21330. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21331. parsedAnimation = parsedMesh.animations[animationIndex];
  21332. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21333. }
  21334. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21335. }
  21336. }
  21337. }
  21338. return mesh;
  21339. };
  21340. /**
  21341. * Creates a ribbon mesh.
  21342. * Please consider using the same method from the MeshBuilder class instead.
  21343. * 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.
  21344. *
  21345. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21346. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21347. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21348. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21349. * 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.
  21350. * 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.
  21351. * 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
  21352. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21353. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21354. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21355. */
  21356. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21357. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21358. pathArray: pathArray,
  21359. closeArray: closeArray,
  21360. closePath: closePath,
  21361. offset: offset,
  21362. updatable: updatable,
  21363. sideOrientation: sideOrientation,
  21364. instance: instance
  21365. }, scene);
  21366. };
  21367. /**
  21368. * Creates a plane polygonal mesh. By default, this is a disc.
  21369. * Please consider using the same method from the MeshBuilder class instead.
  21370. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21371. * 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.
  21372. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21373. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21375. */
  21376. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21377. var options = {
  21378. radius: radius,
  21379. tessellation: tessellation,
  21380. sideOrientation: sideOrientation,
  21381. updatable: updatable
  21382. };
  21383. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21384. };
  21385. /**
  21386. * Creates a box mesh.
  21387. * Please consider using the same method from the MeshBuilder class instead.
  21388. * The parameter `size` sets the size (float) of each box side (default 1).
  21389. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21390. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21392. */
  21393. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21394. var options = {
  21395. size: size,
  21396. sideOrientation: sideOrientation,
  21397. updatable: updatable
  21398. };
  21399. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21400. };
  21401. /**
  21402. * Creates a sphere mesh.
  21403. * Please consider using the same method from the MeshBuilder class instead.
  21404. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21405. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21406. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21407. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21408. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21409. */
  21410. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21411. var options = {
  21412. segments: segments,
  21413. diameterX: diameter,
  21414. diameterY: diameter,
  21415. diameterZ: diameter,
  21416. sideOrientation: sideOrientation,
  21417. updatable: updatable
  21418. };
  21419. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21420. };
  21421. /**
  21422. * Creates a cylinder or a cone mesh.
  21423. * Please consider using the same method from the MeshBuilder class instead.
  21424. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21425. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21426. * 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.
  21427. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21428. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21430. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21432. */
  21433. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21434. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21435. if (scene !== undefined) {
  21436. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21437. updatable = scene;
  21438. }
  21439. scene = subdivisions;
  21440. subdivisions = 1;
  21441. }
  21442. var options = {
  21443. height: height,
  21444. diameterTop: diameterTop,
  21445. diameterBottom: diameterBottom,
  21446. tessellation: tessellation,
  21447. subdivisions: subdivisions,
  21448. sideOrientation: sideOrientation,
  21449. updatable: updatable
  21450. };
  21451. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21452. };
  21453. // Torus (Code from SharpDX.org)
  21454. /**
  21455. * Creates a torus mesh.
  21456. * Please consider using the same method from the MeshBuilder class instead.
  21457. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21458. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21459. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21460. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21461. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21463. */
  21464. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21465. var options = {
  21466. diameter: diameter,
  21467. thickness: thickness,
  21468. tessellation: tessellation,
  21469. sideOrientation: sideOrientation,
  21470. updatable: updatable
  21471. };
  21472. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21473. };
  21474. /**
  21475. * Creates a torus knot mesh.
  21476. * Please consider using the same method from the MeshBuilder class instead.
  21477. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21478. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21479. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21480. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21481. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21482. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21484. */
  21485. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21486. var options = {
  21487. radius: radius,
  21488. tube: tube,
  21489. radialSegments: radialSegments,
  21490. tubularSegments: tubularSegments,
  21491. p: p,
  21492. q: q,
  21493. sideOrientation: sideOrientation,
  21494. updatable: updatable
  21495. };
  21496. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21497. };
  21498. /**
  21499. * Creates a line mesh.
  21500. * Please consider using the same method from the MeshBuilder class instead.
  21501. * 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.
  21502. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21503. * The parameter `points` is an array successive Vector3.
  21504. * 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
  21505. * When updating an instance, remember that only point positions can change, not the number of points.
  21506. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21507. */
  21508. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21509. var options = {
  21510. points: points,
  21511. updatable: updatable,
  21512. instance: instance
  21513. };
  21514. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21515. };
  21516. /**
  21517. * Creates a dashed line mesh.
  21518. * Please consider using the same method from the MeshBuilder class instead.
  21519. * 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.
  21520. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21521. * The parameter `points` is an array successive Vector3.
  21522. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21523. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21524. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21525. * 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
  21526. * When updating an instance, remember that only point positions can change, not the number of points.
  21527. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21528. */
  21529. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21530. var options = {
  21531. points: points,
  21532. dashSize: dashSize,
  21533. gapSize: gapSize,
  21534. dashNb: dashNb,
  21535. updatable: updatable,
  21536. instance: instance
  21537. };
  21538. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21539. };
  21540. /**
  21541. * Creates an extruded shape mesh.
  21542. * 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.
  21543. * Please consider using the same method from the MeshBuilder class instead.
  21544. *
  21545. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21546. * 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
  21547. * extruded along the Z axis.
  21548. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21549. * 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.
  21550. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21551. * 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
  21552. * 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
  21553. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21554. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21555. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21557. */
  21558. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21559. var options = {
  21560. shape: shape,
  21561. path: path,
  21562. scale: scale,
  21563. rotation: rotation,
  21564. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21565. sideOrientation: sideOrientation,
  21566. instance: instance,
  21567. updatable: updatable
  21568. };
  21569. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21570. };
  21571. /**
  21572. * Creates an custom extruded shape mesh.
  21573. * 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.
  21574. * Please consider using the same method from the MeshBuilder class instead.
  21575. *
  21576. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21577. * 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
  21578. * extruded along the Z axis.
  21579. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21580. * 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
  21581. * and the distance of this point from the begining of the path :
  21582. * ```javascript
  21583. * var rotationFunction = function(i, distance) {
  21584. * // do things
  21585. * return rotationValue; }
  21586. * ```
  21587. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21588. * 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
  21589. * and the distance of this point from the begining of the path :
  21590. * ```javascript
  21591. * var scaleFunction = function(i, distance) {
  21592. * // do things
  21593. * return scaleValue;}
  21594. * ```
  21595. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21596. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21597. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21598. * 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
  21599. * 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
  21600. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21601. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21602. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21603. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21604. */
  21605. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21606. var options = {
  21607. shape: shape,
  21608. path: path,
  21609. scaleFunction: scaleFunction,
  21610. rotationFunction: rotationFunction,
  21611. ribbonCloseArray: ribbonCloseArray,
  21612. ribbonClosePath: ribbonClosePath,
  21613. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21614. sideOrientation: sideOrientation,
  21615. instance: instance,
  21616. updatable: updatable
  21617. };
  21618. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21619. };
  21620. /**
  21621. * Creates lathe mesh.
  21622. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21623. * Please consider using the same method from the MeshBuilder class instead.
  21624. * 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
  21625. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21626. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21627. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21628. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21629. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21630. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21631. */
  21632. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21633. var options = {
  21634. shape: shape,
  21635. radius: radius,
  21636. tessellation: tessellation,
  21637. sideOrientation: sideOrientation,
  21638. updatable: updatable
  21639. };
  21640. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21641. };
  21642. /**
  21643. * Creates a plane mesh.
  21644. * Please consider using the same method from the MeshBuilder class instead.
  21645. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21647. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21649. */
  21650. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21651. var options = {
  21652. size: size,
  21653. width: size,
  21654. height: size,
  21655. sideOrientation: sideOrientation,
  21656. updatable: updatable
  21657. };
  21658. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21659. };
  21660. /**
  21661. * Creates a ground mesh.
  21662. * Please consider using the same method from the MeshBuilder class instead.
  21663. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21664. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21666. */
  21667. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21668. var options = {
  21669. width: width,
  21670. height: height,
  21671. subdivisions: subdivisions,
  21672. updatable: updatable
  21673. };
  21674. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21675. };
  21676. /**
  21677. * Creates a tiled ground mesh.
  21678. * Please consider using the same method from the MeshBuilder class instead.
  21679. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21680. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21681. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21682. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21683. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21684. * numbers of subdivisions on the ground width and height of each tile.
  21685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21686. */
  21687. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21688. var options = {
  21689. xmin: xmin,
  21690. zmin: zmin,
  21691. xmax: xmax,
  21692. zmax: zmax,
  21693. subdivisions: subdivisions,
  21694. precision: precision,
  21695. updatable: updatable
  21696. };
  21697. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21698. };
  21699. /**
  21700. * Creates a ground mesh from a height map.
  21701. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21702. * Please consider using the same method from the MeshBuilder class instead.
  21703. * The parameter `url` sets the URL of the height map image resource.
  21704. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21705. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21706. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21707. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21708. * 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).
  21709. * This function is passed the newly built mesh :
  21710. * ```javascript
  21711. * function(mesh) { // do things
  21712. * return; }
  21713. * ```
  21714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21715. */
  21716. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21717. var options = {
  21718. width: width,
  21719. height: height,
  21720. subdivisions: subdivisions,
  21721. minHeight: minHeight,
  21722. maxHeight: maxHeight,
  21723. updatable: updatable,
  21724. onReady: onReady
  21725. };
  21726. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21727. };
  21728. /**
  21729. * Creates a tube mesh.
  21730. * 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.
  21731. * Please consider using the same method from the MeshBuilder class instead.
  21732. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21733. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21734. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21735. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21736. * 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.
  21737. * It must return a radius value (positive float) :
  21738. * ```javascript
  21739. * var radiusFunction = function(i, distance) {
  21740. * // do things
  21741. * return radius; }
  21742. * ```
  21743. * 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
  21744. * 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
  21745. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21746. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21748. */
  21749. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21750. var options = {
  21751. path: path,
  21752. radius: radius,
  21753. tessellation: tessellation,
  21754. radiusFunction: radiusFunction,
  21755. arc: 1,
  21756. cap: cap,
  21757. updatable: updatable,
  21758. sideOrientation: sideOrientation,
  21759. instance: instance
  21760. };
  21761. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21762. };
  21763. /**
  21764. * Creates a polyhedron mesh.
  21765. * Please consider using the same method from the MeshBuilder class instead.
  21766. * 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
  21767. * to choose the wanted type.
  21768. * The parameter `size` (positive float, default 1) sets the polygon size.
  21769. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21770. * 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`.
  21771. * 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
  21772. * 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)`).
  21773. * 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
  21774. * 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.
  21775. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21776. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21778. */
  21779. Mesh.CreatePolyhedron = function (name, options, scene) {
  21780. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21781. };
  21782. /**
  21783. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21784. * Please consider using the same method from the MeshBuilder class instead.
  21785. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21786. * 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`).
  21787. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21788. * 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.
  21789. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21790. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21792. */
  21793. Mesh.CreateIcoSphere = function (name, options, scene) {
  21794. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21795. };
  21796. /**
  21797. * Creates a decal mesh.
  21798. * Please consider using the same method from the MeshBuilder class instead.
  21799. * 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.
  21800. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21801. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21802. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21803. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21804. */
  21805. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21806. var options = {
  21807. position: position,
  21808. normal: normal,
  21809. size: size,
  21810. angle: angle
  21811. };
  21812. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21813. };
  21814. // Skeletons
  21815. /**
  21816. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21817. */
  21818. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21819. var source;
  21820. if (!this._sourcePositions) {
  21821. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21822. this._sourcePositions = new Float32Array(source);
  21823. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21824. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21825. }
  21826. }
  21827. return this._sourcePositions;
  21828. };
  21829. /**
  21830. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21831. */
  21832. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21833. var source;
  21834. if (!this._sourceNormals) {
  21835. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21836. this._sourceNormals = new Float32Array(source);
  21837. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21838. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21839. }
  21840. }
  21841. return this._sourceNormals;
  21842. };
  21843. /**
  21844. * Update the vertex buffers by applying transformation from the bones
  21845. * @param {skeleton} skeleton to apply
  21846. */
  21847. Mesh.prototype.applySkeleton = function (skeleton) {
  21848. if (!this.geometry) {
  21849. return;
  21850. }
  21851. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21852. return;
  21853. }
  21854. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21855. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21856. return this;
  21857. }
  21858. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21859. return this;
  21860. }
  21861. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21862. return this;
  21863. }
  21864. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21865. return this;
  21866. }
  21867. if (!this._sourcePositions) {
  21868. var submeshes = this.subMeshes.slice();
  21869. this.setPositionsForCPUSkinning();
  21870. this.subMeshes = submeshes;
  21871. }
  21872. if (!this._sourceNormals) {
  21873. this.setNormalsForCPUSkinning();
  21874. }
  21875. // positionsData checks for not being Float32Array will only pass at most once
  21876. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21877. if (!(positionsData instanceof Float32Array)) {
  21878. positionsData = new Float32Array(positionsData);
  21879. }
  21880. // normalsData checks for not being Float32Array will only pass at most once
  21881. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21882. if (!(normalsData instanceof Float32Array)) {
  21883. normalsData = new Float32Array(normalsData);
  21884. }
  21885. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21886. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21887. var needExtras = this.numBoneInfluencers > 4;
  21888. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21889. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21890. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21891. var tempVector3 = BABYLON.Vector3.Zero();
  21892. var finalMatrix = new BABYLON.Matrix();
  21893. var tempMatrix = new BABYLON.Matrix();
  21894. var matWeightIdx = 0;
  21895. var inf;
  21896. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21897. var weight;
  21898. for (inf = 0; inf < 4; inf++) {
  21899. weight = matricesWeightsData[matWeightIdx + inf];
  21900. if (weight > 0) {
  21901. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21902. finalMatrix.addToSelf(tempMatrix);
  21903. }
  21904. else
  21905. break;
  21906. }
  21907. if (needExtras) {
  21908. for (inf = 0; inf < 4; inf++) {
  21909. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21910. if (weight > 0) {
  21911. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21912. finalMatrix.addToSelf(tempMatrix);
  21913. }
  21914. else
  21915. break;
  21916. }
  21917. }
  21918. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21919. tempVector3.toArray(positionsData, index);
  21920. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21921. tempVector3.toArray(normalsData, index);
  21922. finalMatrix.reset();
  21923. }
  21924. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21925. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21926. return this;
  21927. };
  21928. // Tools
  21929. /**
  21930. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21931. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21932. */
  21933. Mesh.MinMax = function (meshes) {
  21934. var minVector = null;
  21935. var maxVector = null;
  21936. meshes.forEach(function (mesh, index, array) {
  21937. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21938. if (!minVector) {
  21939. minVector = boundingBox.minimumWorld;
  21940. maxVector = boundingBox.maximumWorld;
  21941. }
  21942. else {
  21943. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21944. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21945. }
  21946. });
  21947. return {
  21948. min: minVector,
  21949. max: maxVector
  21950. };
  21951. };
  21952. /**
  21953. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21954. */
  21955. Mesh.Center = function (meshesOrMinMaxVector) {
  21956. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21957. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21958. };
  21959. /**
  21960. * Merge the array of meshes into a single mesh for performance reasons.
  21961. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21962. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21963. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21964. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21965. */
  21966. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21967. if (disposeSource === void 0) { disposeSource = true; }
  21968. var index;
  21969. if (!allow32BitsIndices) {
  21970. var totalVertices = 0;
  21971. // Counting vertices
  21972. for (index = 0; index < meshes.length; index++) {
  21973. if (meshes[index]) {
  21974. totalVertices += meshes[index].getTotalVertices();
  21975. if (totalVertices > 65536) {
  21976. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21977. return null;
  21978. }
  21979. }
  21980. }
  21981. }
  21982. // Merge
  21983. var vertexData;
  21984. var otherVertexData;
  21985. var source;
  21986. for (index = 0; index < meshes.length; index++) {
  21987. if (meshes[index]) {
  21988. meshes[index].computeWorldMatrix(true);
  21989. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21990. otherVertexData.transform(meshes[index].getWorldMatrix());
  21991. if (vertexData) {
  21992. vertexData.merge(otherVertexData);
  21993. }
  21994. else {
  21995. vertexData = otherVertexData;
  21996. source = meshes[index];
  21997. }
  21998. }
  21999. }
  22000. if (!meshSubclass) {
  22001. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22002. }
  22003. vertexData.applyToMesh(meshSubclass);
  22004. // Setting properties
  22005. meshSubclass.material = source.material;
  22006. meshSubclass.checkCollisions = source.checkCollisions;
  22007. // Cleaning
  22008. if (disposeSource) {
  22009. for (index = 0; index < meshes.length; index++) {
  22010. if (meshes[index]) {
  22011. meshes[index].dispose();
  22012. }
  22013. }
  22014. }
  22015. return meshSubclass;
  22016. };
  22017. return Mesh;
  22018. }(BABYLON.AbstractMesh));
  22019. // Consts
  22020. Mesh._FRONTSIDE = 0;
  22021. Mesh._BACKSIDE = 1;
  22022. Mesh._DOUBLESIDE = 2;
  22023. Mesh._DEFAULTSIDE = 0;
  22024. Mesh._NO_CAP = 0;
  22025. Mesh._CAP_START = 1;
  22026. Mesh._CAP_END = 2;
  22027. Mesh._CAP_ALL = 3;
  22028. BABYLON.Mesh = Mesh;
  22029. })(BABYLON || (BABYLON = {}));
  22030. //# sourceMappingURL=babylon.mesh.js.map
  22031. var BABYLON;
  22032. (function (BABYLON) {
  22033. var SubMesh = (function () {
  22034. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22035. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22036. this.materialIndex = materialIndex;
  22037. this.verticesStart = verticesStart;
  22038. this.verticesCount = verticesCount;
  22039. this.indexStart = indexStart;
  22040. this.indexCount = indexCount;
  22041. this._renderId = 0;
  22042. this._mesh = mesh;
  22043. this._renderingMesh = renderingMesh || mesh;
  22044. mesh.subMeshes.push(this);
  22045. this._trianglePlanes = [];
  22046. this._id = mesh.subMeshes.length - 1;
  22047. if (createBoundingBox) {
  22048. this.refreshBoundingInfo();
  22049. mesh.computeWorldMatrix(true);
  22050. }
  22051. }
  22052. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22053. get: function () {
  22054. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22055. },
  22056. enumerable: true,
  22057. configurable: true
  22058. });
  22059. SubMesh.prototype.getBoundingInfo = function () {
  22060. if (this.IsGlobal) {
  22061. return this._mesh.getBoundingInfo();
  22062. }
  22063. return this._boundingInfo;
  22064. };
  22065. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22066. this._boundingInfo = boundingInfo;
  22067. };
  22068. SubMesh.prototype.getMesh = function () {
  22069. return this._mesh;
  22070. };
  22071. SubMesh.prototype.getRenderingMesh = function () {
  22072. return this._renderingMesh;
  22073. };
  22074. SubMesh.prototype.getMaterial = function () {
  22075. var rootMaterial = this._renderingMesh.material;
  22076. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22077. var multiMaterial = rootMaterial;
  22078. return multiMaterial.getSubMaterial(this.materialIndex);
  22079. }
  22080. if (!rootMaterial) {
  22081. return this._mesh.getScene().defaultMaterial;
  22082. }
  22083. return rootMaterial;
  22084. };
  22085. // Methods
  22086. SubMesh.prototype.refreshBoundingInfo = function () {
  22087. this._lastColliderWorldVertices = null;
  22088. if (this.IsGlobal) {
  22089. return;
  22090. }
  22091. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22092. if (!data) {
  22093. this._boundingInfo = this._mesh._boundingInfo;
  22094. return;
  22095. }
  22096. var indices = this._renderingMesh.getIndices();
  22097. var extend;
  22098. //is this the only submesh?
  22099. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22100. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22101. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22102. }
  22103. else {
  22104. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22105. }
  22106. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22107. };
  22108. SubMesh.prototype._checkCollision = function (collider) {
  22109. return this.getBoundingInfo()._checkCollision(collider);
  22110. };
  22111. SubMesh.prototype.updateBoundingInfo = function (world) {
  22112. if (!this.getBoundingInfo()) {
  22113. this.refreshBoundingInfo();
  22114. }
  22115. this.getBoundingInfo().update(world);
  22116. };
  22117. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22118. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22119. };
  22120. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22121. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22122. };
  22123. SubMesh.prototype.render = function (enableAlphaMode) {
  22124. this._renderingMesh.render(this, enableAlphaMode);
  22125. };
  22126. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22127. if (!this._linesIndexBuffer) {
  22128. var linesIndices = [];
  22129. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22130. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22131. }
  22132. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22133. this.linesIndexCount = linesIndices.length;
  22134. }
  22135. return this._linesIndexBuffer;
  22136. };
  22137. SubMesh.prototype.canIntersects = function (ray) {
  22138. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22139. };
  22140. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22141. var intersectInfo = null;
  22142. // LineMesh first as it's also a Mesh...
  22143. if (this._mesh instanceof BABYLON.LinesMesh) {
  22144. var lineMesh = this._mesh;
  22145. // Line test
  22146. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22147. var p0 = positions[indices[index]];
  22148. var p1 = positions[indices[index + 1]];
  22149. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22150. if (length < 0) {
  22151. continue;
  22152. }
  22153. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22154. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22155. if (fastCheck) {
  22156. break;
  22157. }
  22158. }
  22159. }
  22160. }
  22161. else {
  22162. // Triangles test
  22163. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22164. var p0 = positions[indices[index]];
  22165. var p1 = positions[indices[index + 1]];
  22166. var p2 = positions[indices[index + 2]];
  22167. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22168. if (currentIntersectInfo) {
  22169. if (currentIntersectInfo.distance < 0) {
  22170. continue;
  22171. }
  22172. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22173. intersectInfo = currentIntersectInfo;
  22174. intersectInfo.faceId = index / 3;
  22175. if (fastCheck) {
  22176. break;
  22177. }
  22178. }
  22179. }
  22180. }
  22181. }
  22182. return intersectInfo;
  22183. };
  22184. // Clone
  22185. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22186. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22187. if (!this.IsGlobal) {
  22188. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22189. }
  22190. return result;
  22191. };
  22192. // Dispose
  22193. SubMesh.prototype.dispose = function () {
  22194. if (this._linesIndexBuffer) {
  22195. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22196. this._linesIndexBuffer = null;
  22197. }
  22198. // Remove from mesh
  22199. var index = this._mesh.subMeshes.indexOf(this);
  22200. this._mesh.subMeshes.splice(index, 1);
  22201. };
  22202. // Statics
  22203. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22204. var minVertexIndex = Number.MAX_VALUE;
  22205. var maxVertexIndex = -Number.MAX_VALUE;
  22206. renderingMesh = renderingMesh || mesh;
  22207. var indices = renderingMesh.getIndices();
  22208. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22209. var vertexIndex = indices[index];
  22210. if (vertexIndex < minVertexIndex)
  22211. minVertexIndex = vertexIndex;
  22212. if (vertexIndex > maxVertexIndex)
  22213. maxVertexIndex = vertexIndex;
  22214. }
  22215. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22216. };
  22217. return SubMesh;
  22218. }());
  22219. BABYLON.SubMesh = SubMesh;
  22220. })(BABYLON || (BABYLON = {}));
  22221. //# sourceMappingURL=babylon.subMesh.js.map
  22222. var BABYLON;
  22223. (function (BABYLON) {
  22224. var MeshBuilder = (function () {
  22225. function MeshBuilder() {
  22226. }
  22227. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22228. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22229. return BABYLON.Mesh.DOUBLESIDE;
  22230. }
  22231. if (orientation === undefined || orientation === null) {
  22232. return BABYLON.Mesh.FRONTSIDE;
  22233. }
  22234. return orientation;
  22235. };
  22236. /**
  22237. * Creates a box mesh.
  22238. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22239. * The parameter `size` sets the size (float) of each box side (default 1).
  22240. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22241. * 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).
  22242. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22243. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22244. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22246. */
  22247. MeshBuilder.CreateBox = function (name, options, scene) {
  22248. var box = new BABYLON.Mesh(name, scene);
  22249. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22250. box.sideOrientation = options.sideOrientation;
  22251. var vertexData = BABYLON.VertexData.CreateBox(options);
  22252. vertexData.applyToMesh(box, options.updatable);
  22253. return box;
  22254. };
  22255. /**
  22256. * Creates a sphere mesh.
  22257. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22258. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22259. * 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`).
  22260. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22261. * 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
  22262. * 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).
  22263. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22264. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22266. */
  22267. MeshBuilder.CreateSphere = function (name, options, scene) {
  22268. var sphere = new BABYLON.Mesh(name, scene);
  22269. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22270. sphere.sideOrientation = options.sideOrientation;
  22271. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22272. vertexData.applyToMesh(sphere, options.updatable);
  22273. return sphere;
  22274. };
  22275. /**
  22276. * Creates a plane polygonal mesh. By default, this is a disc.
  22277. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22278. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22279. * 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.
  22280. * 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
  22281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22282. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22284. */
  22285. MeshBuilder.CreateDisc = function (name, options, scene) {
  22286. var disc = new BABYLON.Mesh(name, scene);
  22287. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22288. disc.sideOrientation = options.sideOrientation;
  22289. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22290. vertexData.applyToMesh(disc, options.updatable);
  22291. return disc;
  22292. };
  22293. /**
  22294. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22295. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22296. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22297. * 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`).
  22298. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22299. * 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.
  22300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22303. */
  22304. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22305. var sphere = new BABYLON.Mesh(name, scene);
  22306. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22307. sphere.sideOrientation = options.sideOrientation;
  22308. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22309. vertexData.applyToMesh(sphere, options.updatable);
  22310. return sphere;
  22311. };
  22312. ;
  22313. /**
  22314. * Creates a ribbon mesh.
  22315. * 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.
  22316. *
  22317. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22318. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22319. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22320. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22321. * 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.
  22322. * 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.
  22323. * 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
  22324. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22326. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22328. */
  22329. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22330. var pathArray = options.pathArray;
  22331. var closeArray = options.closeArray;
  22332. var closePath = options.closePath;
  22333. var offset = options.offset;
  22334. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22335. var instance = options.instance;
  22336. var updatable = options.updatable;
  22337. if (instance) {
  22338. // positionFunction : ribbon case
  22339. // only pathArray and sideOrientation parameters are taken into account for positions update
  22340. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22341. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22342. var positionFunction = function (positions) {
  22343. var minlg = pathArray[0].length;
  22344. var i = 0;
  22345. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22346. for (var si = 1; si <= ns; si++) {
  22347. for (var p = 0; p < pathArray.length; p++) {
  22348. var path = pathArray[p];
  22349. var l = path.length;
  22350. minlg = (minlg < l) ? minlg : l;
  22351. var j = 0;
  22352. while (j < minlg) {
  22353. positions[i] = path[j].x;
  22354. positions[i + 1] = path[j].y;
  22355. positions[i + 2] = path[j].z;
  22356. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22357. BABYLON.Tmp.Vector3[0].x = path[j].x;
  22358. }
  22359. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  22360. BABYLON.Tmp.Vector3[1].x = path[j].x;
  22361. }
  22362. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  22363. BABYLON.Tmp.Vector3[0].y = path[j].y;
  22364. }
  22365. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  22366. BABYLON.Tmp.Vector3[1].y = path[j].y;
  22367. }
  22368. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  22369. BABYLON.Tmp.Vector3[0].z = path[j].z;
  22370. }
  22371. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  22372. BABYLON.Tmp.Vector3[1].z = path[j].z;
  22373. }
  22374. j++;
  22375. i += 3;
  22376. }
  22377. if (instance._closePath) {
  22378. positions[i] = path[0].x;
  22379. positions[i + 1] = path[0].y;
  22380. positions[i + 2] = path[0].z;
  22381. i += 3;
  22382. }
  22383. }
  22384. }
  22385. };
  22386. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22387. positionFunction(positions);
  22388. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  22389. instance._boundingInfo.update(instance._worldMatrix);
  22390. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22391. if (!(instance.areNormalsFrozen)) {
  22392. var indices = instance.getIndices();
  22393. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22394. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22395. if (instance._closePath) {
  22396. var indexFirst = 0;
  22397. var indexLast = 0;
  22398. for (var p = 0; p < pathArray.length; p++) {
  22399. indexFirst = instance._idx[p] * 3;
  22400. if (p + 1 < pathArray.length) {
  22401. indexLast = (instance._idx[p + 1] - 1) * 3;
  22402. }
  22403. else {
  22404. indexLast = normals.length - 3;
  22405. }
  22406. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  22407. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  22408. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  22409. normals[indexLast] = normals[indexFirst];
  22410. normals[indexLast + 1] = normals[indexFirst + 1];
  22411. normals[indexLast + 2] = normals[indexFirst + 2];
  22412. }
  22413. }
  22414. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22415. }
  22416. return instance;
  22417. }
  22418. else {
  22419. var ribbon = new BABYLON.Mesh(name, scene);
  22420. ribbon.sideOrientation = sideOrientation;
  22421. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  22422. if (closePath) {
  22423. ribbon._idx = vertexData._idx;
  22424. }
  22425. ribbon._closePath = closePath;
  22426. ribbon._closeArray = closeArray;
  22427. vertexData.applyToMesh(ribbon, updatable);
  22428. return ribbon;
  22429. }
  22430. };
  22431. /**
  22432. * Creates a cylinder or a cone mesh.
  22433. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  22434. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22435. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22436. * 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.
  22437. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22438. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22439. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  22440. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  22441. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  22442. * 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).
  22443. * 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
  22444. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  22445. * 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
  22446. * 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.
  22447. * If `enclose` is false, a ring surface is one element.
  22448. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  22449. * 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
  22450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22451. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22453. */
  22454. MeshBuilder.CreateCylinder = function (name, options, scene) {
  22455. var cylinder = new BABYLON.Mesh(name, scene);
  22456. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22457. cylinder.sideOrientation = options.sideOrientation;
  22458. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  22459. vertexData.applyToMesh(cylinder, options.updatable);
  22460. return cylinder;
  22461. };
  22462. /**
  22463. * Creates a torus mesh.
  22464. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  22465. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22466. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22467. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22468. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22469. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22470. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22471. */
  22472. MeshBuilder.CreateTorus = function (name, options, scene) {
  22473. var torus = new BABYLON.Mesh(name, scene);
  22474. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22475. torus.sideOrientation = options.sideOrientation;
  22476. var vertexData = BABYLON.VertexData.CreateTorus(options);
  22477. vertexData.applyToMesh(torus, options.updatable);
  22478. return torus;
  22479. };
  22480. /**
  22481. * Creates a torus knot mesh.
  22482. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  22483. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22484. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22485. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22486. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22490. */
  22491. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  22492. var torusKnot = new BABYLON.Mesh(name, scene);
  22493. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22494. torusKnot.sideOrientation = options.sideOrientation;
  22495. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  22496. vertexData.applyToMesh(torusKnot, options.updatable);
  22497. return torusKnot;
  22498. };
  22499. /**
  22500. * Creates a line system mesh.
  22501. * A line system is a pool of many lines gathered in a single mesh.
  22502. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22503. * 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.
  22504. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22505. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22506. * 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
  22507. * 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
  22508. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22509. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22510. */
  22511. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22512. var instance = options.instance;
  22513. var lines = options.lines;
  22514. if (instance) {
  22515. var positionFunction = function (positions) {
  22516. var i = 0;
  22517. for (var l = 0; l < lines.length; l++) {
  22518. var points = lines[l];
  22519. for (var p = 0; p < points.length; p++) {
  22520. positions[i] = points[p].x;
  22521. positions[i + 1] = points[p].y;
  22522. positions[i + 2] = points[p].z;
  22523. i += 3;
  22524. }
  22525. }
  22526. };
  22527. instance.updateMeshPositions(positionFunction, false);
  22528. return instance;
  22529. }
  22530. // line system creation
  22531. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22532. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22533. vertexData.applyToMesh(lineSystem, options.updatable);
  22534. return lineSystem;
  22535. };
  22536. /**
  22537. * Creates a line mesh.
  22538. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22539. * 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.
  22540. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22541. * The parameter `points` is an array successive Vector3.
  22542. * 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
  22543. * When updating an instance, remember that only point positions can change, not the number of points.
  22544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22545. */
  22546. MeshBuilder.CreateLines = function (name, options, scene) {
  22547. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22548. return lines;
  22549. };
  22550. /**
  22551. * Creates a dashed line mesh.
  22552. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22553. * 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.
  22554. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22555. * The parameter `points` is an array successive Vector3.
  22556. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22557. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22558. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22559. * 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
  22560. * When updating an instance, remember that only point positions can change, not the number of points.
  22561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22562. */
  22563. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22564. var points = options.points;
  22565. var instance = options.instance;
  22566. var gapSize = options.gapSize;
  22567. var dashNb = options.dashNb;
  22568. var dashSize = options.dashSize;
  22569. if (instance) {
  22570. var positionFunction = function (positions) {
  22571. var curvect = BABYLON.Vector3.Zero();
  22572. var nbSeg = positions.length / 6;
  22573. var lg = 0;
  22574. var nb = 0;
  22575. var shft = 0;
  22576. var dashshft = 0;
  22577. var curshft = 0;
  22578. var p = 0;
  22579. var i = 0;
  22580. var j = 0;
  22581. for (i = 0; i < points.length - 1; i++) {
  22582. points[i + 1].subtractToRef(points[i], curvect);
  22583. lg += curvect.length();
  22584. }
  22585. shft = lg / nbSeg;
  22586. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22587. for (i = 0; i < points.length - 1; i++) {
  22588. points[i + 1].subtractToRef(points[i], curvect);
  22589. nb = Math.floor(curvect.length() / shft);
  22590. curvect.normalize();
  22591. j = 0;
  22592. while (j < nb && p < positions.length) {
  22593. curshft = shft * j;
  22594. positions[p] = points[i].x + curshft * curvect.x;
  22595. positions[p + 1] = points[i].y + curshft * curvect.y;
  22596. positions[p + 2] = points[i].z + curshft * curvect.z;
  22597. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22598. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22599. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22600. p += 6;
  22601. j++;
  22602. }
  22603. }
  22604. while (p < positions.length) {
  22605. positions[p] = points[i].x;
  22606. positions[p + 1] = points[i].y;
  22607. positions[p + 2] = points[i].z;
  22608. p += 3;
  22609. }
  22610. };
  22611. instance.updateMeshPositions(positionFunction, false);
  22612. return instance;
  22613. }
  22614. // dashed lines creation
  22615. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22616. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22617. vertexData.applyToMesh(dashedLines, options.updatable);
  22618. dashedLines.dashSize = dashSize;
  22619. dashedLines.gapSize = gapSize;
  22620. return dashedLines;
  22621. };
  22622. /**
  22623. * Creates an extruded shape mesh.
  22624. * 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.
  22625. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22626. *
  22627. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22628. * 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
  22629. * extruded along the Z axis.
  22630. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22631. * 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.
  22632. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22633. * 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
  22634. * 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
  22635. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22638. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22640. */
  22641. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22642. var path = options.path;
  22643. var shape = options.shape;
  22644. var scale = options.scale || 1;
  22645. var rotation = options.rotation || 0;
  22646. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22647. var updatable = options.updatable;
  22648. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22649. var instance = options.instance;
  22650. var invertUV = options.invertUV || false;
  22651. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22652. };
  22653. /**
  22654. * Creates an custom extruded shape mesh.
  22655. * 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.
  22656. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22657. *
  22658. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22659. * 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
  22660. * extruded along the Z axis.
  22661. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22662. * 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
  22663. * and the distance of this point from the begining of the path :
  22664. * ```javascript
  22665. * var rotationFunction = function(i, distance) {
  22666. * // do things
  22667. * return rotationValue; }
  22668. * ```
  22669. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22670. * 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
  22671. * and the distance of this point from the begining of the path :
  22672. * ```javascript
  22673. * var scaleFunction = function(i, distance) {
  22674. * // do things
  22675. * return scaleValue;}
  22676. * ```
  22677. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22678. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22679. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22680. * 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
  22681. * 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
  22682. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22685. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22687. */
  22688. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22689. var path = options.path;
  22690. var shape = options.shape;
  22691. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22692. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22693. var ribbonCloseArray = options.ribbonCloseArray || false;
  22694. var ribbonClosePath = options.ribbonClosePath || false;
  22695. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22696. var updatable = options.updatable;
  22697. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22698. var instance = options.instance;
  22699. var invertUV = options.invertUV || false;
  22700. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22701. };
  22702. /**
  22703. * Creates lathe mesh.
  22704. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22705. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22706. *
  22707. * 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
  22708. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22709. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22710. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22711. * 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.
  22712. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22713. * 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
  22714. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22715. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22716. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22717. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22718. */
  22719. MeshBuilder.CreateLathe = function (name, options, scene) {
  22720. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22721. var closed = (options.closed === undefined) ? true : options.closed;
  22722. var shape = options.shape;
  22723. var radius = options.radius || 1;
  22724. var tessellation = options.tessellation || 64;
  22725. var updatable = options.updatable;
  22726. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22727. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22728. var pi2 = Math.PI * 2;
  22729. var paths = new Array();
  22730. var invertUV = options.invertUV || false;
  22731. var i = 0;
  22732. var p = 0;
  22733. var step = pi2 / tessellation * arc;
  22734. var rotated;
  22735. var path = new Array();
  22736. ;
  22737. for (i = 0; i <= tessellation; i++) {
  22738. var path = [];
  22739. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22740. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22741. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22742. }
  22743. for (p = 0; p < shape.length; p++) {
  22744. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22745. path.push(rotated);
  22746. }
  22747. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22748. 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));
  22749. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22750. }
  22751. paths.push(path);
  22752. }
  22753. // lathe ribbon
  22754. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22755. return lathe;
  22756. };
  22757. /**
  22758. * Creates a plane mesh.
  22759. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22760. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22761. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22762. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22763. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22764. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22766. */
  22767. MeshBuilder.CreatePlane = function (name, options, scene) {
  22768. var plane = new BABYLON.Mesh(name, scene);
  22769. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22770. plane.sideOrientation = options.sideOrientation;
  22771. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22772. vertexData.applyToMesh(plane, options.updatable);
  22773. if (options.sourcePlane) {
  22774. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22775. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22776. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22777. plane.rotate(vectorProduct, product);
  22778. }
  22779. return plane;
  22780. };
  22781. /**
  22782. * Creates a ground mesh.
  22783. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22784. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22785. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22786. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22787. */
  22788. MeshBuilder.CreateGround = function (name, options, scene) {
  22789. var ground = new BABYLON.GroundMesh(name, scene);
  22790. ground._setReady(false);
  22791. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22792. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22793. ground._width = options.width || 1;
  22794. ground._height = options.height || 1;
  22795. ground._maxX = ground._width / 2;
  22796. ground._maxZ = ground._height / 2;
  22797. ground._minX = -ground._maxX;
  22798. ground._minZ = -ground._maxZ;
  22799. var vertexData = BABYLON.VertexData.CreateGround(options);
  22800. vertexData.applyToMesh(ground, options.updatable);
  22801. ground._setReady(true);
  22802. return ground;
  22803. };
  22804. /**
  22805. * Creates a tiled ground mesh.
  22806. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22807. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22808. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22809. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22810. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22811. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22812. * numbers of subdivisions on the ground width and height of each tile.
  22813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22814. */
  22815. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22816. var tiledGround = new BABYLON.Mesh(name, scene);
  22817. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22818. vertexData.applyToMesh(tiledGround, options.updatable);
  22819. return tiledGround;
  22820. };
  22821. /**
  22822. * Creates a ground mesh from a height map.
  22823. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22824. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22825. * The parameter `url` sets the URL of the height map image resource.
  22826. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22827. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22828. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22829. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22830. * 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).
  22831. * This function is passed the newly built mesh :
  22832. * ```javascript
  22833. * function(mesh) { // do things
  22834. * return; }
  22835. * ```
  22836. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22837. */
  22838. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22839. var width = options.width || 10.0;
  22840. var height = options.height || 10.0;
  22841. var subdivisions = options.subdivisions || 1 | 0;
  22842. var minHeight = options.minHeight || 0.0;
  22843. var maxHeight = options.maxHeight || 10.0;
  22844. var updatable = options.updatable;
  22845. var onReady = options.onReady;
  22846. var ground = new BABYLON.GroundMesh(name, scene);
  22847. ground._subdivisionsX = subdivisions;
  22848. ground._subdivisionsY = subdivisions;
  22849. ground._width = width;
  22850. ground._height = height;
  22851. ground._maxX = ground._width / 2.0;
  22852. ground._maxZ = ground._height / 2.0;
  22853. ground._minX = -ground._maxX;
  22854. ground._minZ = -ground._maxZ;
  22855. ground._setReady(false);
  22856. var onload = function (img) {
  22857. // Getting height map data
  22858. var canvas = document.createElement("canvas");
  22859. var context = canvas.getContext("2d");
  22860. var bufferWidth = img.width;
  22861. var bufferHeight = img.height;
  22862. canvas.width = bufferWidth;
  22863. canvas.height = bufferHeight;
  22864. context.drawImage(img, 0, 0);
  22865. // Create VertexData from map data
  22866. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22867. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22868. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22869. width: width, height: height,
  22870. subdivisions: subdivisions,
  22871. minHeight: minHeight, maxHeight: maxHeight,
  22872. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22873. });
  22874. vertexData.applyToMesh(ground, updatable);
  22875. ground._setReady(true);
  22876. //execute ready callback, if set
  22877. if (onReady) {
  22878. onReady(ground);
  22879. }
  22880. };
  22881. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22882. return ground;
  22883. };
  22884. /**
  22885. * Creates a tube mesh.
  22886. * 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.
  22887. *
  22888. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22889. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22890. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22891. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22892. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22893. * 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.
  22894. * It must return a radius value (positive float) :
  22895. * ```javascript
  22896. * var radiusFunction = function(i, distance) {
  22897. * // do things
  22898. * return radius; }
  22899. * ```
  22900. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22901. * 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
  22902. * 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
  22903. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22904. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22905. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22906. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22907. */
  22908. MeshBuilder.CreateTube = function (name, options, scene) {
  22909. var path = options.path;
  22910. var radius = options.radius || 1.0;
  22911. var tessellation = options.tessellation || 64 | 0;
  22912. var radiusFunction = options.radiusFunction;
  22913. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22914. var invertUV = options.invertUV || false;
  22915. var updatable = options.updatable;
  22916. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22917. var instance = options.instance;
  22918. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22919. // tube geometry
  22920. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22921. var tangents = path3D.getTangents();
  22922. var normals = path3D.getNormals();
  22923. var distances = path3D.getDistances();
  22924. var pi2 = Math.PI * 2;
  22925. var step = pi2 / tessellation * arc;
  22926. var returnRadius = function () { return radius; };
  22927. var radiusFunctionFinal = radiusFunction || returnRadius;
  22928. var circlePath;
  22929. var rad;
  22930. var normal;
  22931. var rotated;
  22932. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22933. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22934. for (var i = 0; i < path.length; i++) {
  22935. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22936. circlePath = Array(); // current circle array
  22937. normal = normals[i]; // current normal
  22938. for (var t = 0; t < tessellation; t++) {
  22939. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22940. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22941. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22942. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22943. circlePath[t] = rotated;
  22944. }
  22945. circlePaths[index] = circlePath;
  22946. index++;
  22947. }
  22948. // cap
  22949. var capPath = function (nbPoints, pathIndex) {
  22950. var pointCap = Array();
  22951. for (var i = 0; i < nbPoints; i++) {
  22952. pointCap.push(path[pathIndex]);
  22953. }
  22954. return pointCap;
  22955. };
  22956. switch (cap) {
  22957. case BABYLON.Mesh.NO_CAP:
  22958. break;
  22959. case BABYLON.Mesh.CAP_START:
  22960. circlePaths[0] = capPath(tessellation, 0);
  22961. circlePaths[1] = circlePaths[2].slice(0);
  22962. break;
  22963. case BABYLON.Mesh.CAP_END:
  22964. circlePaths[index] = circlePaths[index - 1].slice(0);
  22965. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22966. break;
  22967. case BABYLON.Mesh.CAP_ALL:
  22968. circlePaths[0] = capPath(tessellation, 0);
  22969. circlePaths[1] = circlePaths[2].slice(0);
  22970. circlePaths[index] = circlePaths[index - 1].slice(0);
  22971. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22972. break;
  22973. default:
  22974. break;
  22975. }
  22976. return circlePaths;
  22977. };
  22978. var path3D;
  22979. var pathArray;
  22980. if (instance) {
  22981. var arc = options.arc || instance.arc;
  22982. path3D = (instance.path3D).update(path);
  22983. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22984. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22985. instance.path3D = path3D;
  22986. instance.pathArray = pathArray;
  22987. instance.arc = arc;
  22988. return instance;
  22989. }
  22990. // tube creation
  22991. path3D = new BABYLON.Path3D(path);
  22992. var newPathArray = new Array();
  22993. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22994. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22995. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22996. tube.pathArray = pathArray;
  22997. tube.path3D = path3D;
  22998. tube.tessellation = tessellation;
  22999. tube.cap = cap;
  23000. tube.arc = options.arc;
  23001. return tube;
  23002. };
  23003. /**
  23004. * Creates a polyhedron mesh.
  23005. *
  23006. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  23007. * 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
  23008. * to choose the wanted type.
  23009. * The parameter `size` (positive float, default 1) sets the polygon size.
  23010. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23011. * 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`.
  23012. * 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
  23013. * 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)`).
  23014. * 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
  23015. * 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.
  23016. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23017. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23019. */
  23020. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  23021. var polyhedron = new BABYLON.Mesh(name, scene);
  23022. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  23023. polyhedron.sideOrientation = options.sideOrientation;
  23024. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  23025. vertexData.applyToMesh(polyhedron, options.updatable);
  23026. return polyhedron;
  23027. };
  23028. /**
  23029. * Creates a decal mesh.
  23030. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23031. * 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.
  23032. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23033. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23034. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23035. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23036. */
  23037. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23038. var indices = sourceMesh.getIndices();
  23039. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23040. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23041. var position = options.position || BABYLON.Vector3.Zero();
  23042. var normal = options.normal || BABYLON.Vector3.Up();
  23043. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23044. var angle = options.angle || 0;
  23045. // Getting correct rotation
  23046. if (!normal) {
  23047. var target = new BABYLON.Vector3(0, 0, 1);
  23048. var camera = sourceMesh.getScene().activeCamera;
  23049. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23050. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23051. }
  23052. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23053. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23054. var pitch = Math.atan2(normal.y, len);
  23055. // Matrix
  23056. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23057. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23058. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23059. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23060. var vertexData = new BABYLON.VertexData();
  23061. vertexData.indices = [];
  23062. vertexData.positions = [];
  23063. vertexData.normals = [];
  23064. vertexData.uvs = [];
  23065. var currentVertexDataIndex = 0;
  23066. var extractDecalVector3 = function (indexId) {
  23067. var vertexId = indices[indexId];
  23068. var result = new BABYLON.PositionNormalVertex();
  23069. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23070. // Send vector to decal local world
  23071. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23072. // Get normal
  23073. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23074. return result;
  23075. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23076. var clip = function (vertices, axis) {
  23077. if (vertices.length === 0) {
  23078. return vertices;
  23079. }
  23080. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23081. var clipVertices = function (v0, v1) {
  23082. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23083. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23084. };
  23085. var result = new Array();
  23086. for (var index = 0; index < vertices.length; index += 3) {
  23087. var v1Out;
  23088. var v2Out;
  23089. var v3Out;
  23090. var total = 0;
  23091. var nV1, nV2, nV3, nV4;
  23092. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23093. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23094. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23095. v1Out = d1 > 0;
  23096. v2Out = d2 > 0;
  23097. v3Out = d3 > 0;
  23098. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23099. switch (total) {
  23100. case 0:
  23101. result.push(vertices[index]);
  23102. result.push(vertices[index + 1]);
  23103. result.push(vertices[index + 2]);
  23104. break;
  23105. case 1:
  23106. if (v1Out) {
  23107. nV1 = vertices[index + 1];
  23108. nV2 = vertices[index + 2];
  23109. nV3 = clipVertices(vertices[index], nV1);
  23110. nV4 = clipVertices(vertices[index], nV2);
  23111. }
  23112. if (v2Out) {
  23113. nV1 = vertices[index];
  23114. nV2 = vertices[index + 2];
  23115. nV3 = clipVertices(vertices[index + 1], nV1);
  23116. nV4 = clipVertices(vertices[index + 1], nV2);
  23117. result.push(nV3);
  23118. result.push(nV2.clone());
  23119. result.push(nV1.clone());
  23120. result.push(nV2.clone());
  23121. result.push(nV3.clone());
  23122. result.push(nV4);
  23123. break;
  23124. }
  23125. if (v3Out) {
  23126. nV1 = vertices[index];
  23127. nV2 = vertices[index + 1];
  23128. nV3 = clipVertices(vertices[index + 2], nV1);
  23129. nV4 = clipVertices(vertices[index + 2], nV2);
  23130. }
  23131. result.push(nV1.clone());
  23132. result.push(nV2.clone());
  23133. result.push(nV3);
  23134. result.push(nV4);
  23135. result.push(nV3.clone());
  23136. result.push(nV2.clone());
  23137. break;
  23138. case 2:
  23139. if (!v1Out) {
  23140. nV1 = vertices[index].clone();
  23141. nV2 = clipVertices(nV1, vertices[index + 1]);
  23142. nV3 = clipVertices(nV1, vertices[index + 2]);
  23143. result.push(nV1);
  23144. result.push(nV2);
  23145. result.push(nV3);
  23146. }
  23147. if (!v2Out) {
  23148. nV1 = vertices[index + 1].clone();
  23149. nV2 = clipVertices(nV1, vertices[index + 2]);
  23150. nV3 = clipVertices(nV1, vertices[index]);
  23151. result.push(nV1);
  23152. result.push(nV2);
  23153. result.push(nV3);
  23154. }
  23155. if (!v3Out) {
  23156. nV1 = vertices[index + 2].clone();
  23157. nV2 = clipVertices(nV1, vertices[index]);
  23158. nV3 = clipVertices(nV1, vertices[index + 1]);
  23159. result.push(nV1);
  23160. result.push(nV2);
  23161. result.push(nV3);
  23162. }
  23163. break;
  23164. case 3:
  23165. break;
  23166. }
  23167. }
  23168. return result;
  23169. };
  23170. for (var index = 0; index < indices.length; index += 3) {
  23171. var faceVertices = new Array();
  23172. faceVertices.push(extractDecalVector3(index));
  23173. faceVertices.push(extractDecalVector3(index + 1));
  23174. faceVertices.push(extractDecalVector3(index + 2));
  23175. // Clip
  23176. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23177. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23178. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23179. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23180. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23181. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23182. if (faceVertices.length === 0) {
  23183. continue;
  23184. }
  23185. // Add UVs and get back to world
  23186. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23187. var vertex = faceVertices[vIndex];
  23188. //TODO check for Int32Array
  23189. vertexData.indices.push(currentVertexDataIndex);
  23190. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23191. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23192. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23193. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23194. currentVertexDataIndex++;
  23195. }
  23196. }
  23197. // Return mesh
  23198. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23199. vertexData.applyToMesh(decal);
  23200. decal.position = position.clone();
  23201. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23202. return decal;
  23203. };
  23204. // Privates
  23205. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23206. // extrusion geometry
  23207. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23208. var tangents = path3D.getTangents();
  23209. var normals = path3D.getNormals();
  23210. var binormals = path3D.getBinormals();
  23211. var distances = path3D.getDistances();
  23212. var angle = 0;
  23213. var returnScale = function () { return scale; };
  23214. var returnRotation = function () { return rotation; };
  23215. var rotate = custom ? rotateFunction : returnRotation;
  23216. var scl = custom ? scaleFunction : returnScale;
  23217. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23218. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23219. for (var i = 0; i < curve.length; i++) {
  23220. var shapePath = new Array();
  23221. var angleStep = rotate(i, distances[i]);
  23222. var scaleRatio = scl(i, distances[i]);
  23223. for (var p = 0; p < shape.length; p++) {
  23224. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23225. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23226. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23227. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23228. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23229. shapePath[p] = rotated;
  23230. }
  23231. shapePaths[index] = shapePath;
  23232. angle += angleStep;
  23233. index++;
  23234. }
  23235. // cap
  23236. var capPath = function (shapePath) {
  23237. var pointCap = Array();
  23238. var barycenter = BABYLON.Vector3.Zero();
  23239. var i;
  23240. for (i = 0; i < shapePath.length; i++) {
  23241. barycenter.addInPlace(shapePath[i]);
  23242. }
  23243. barycenter.scaleInPlace(1 / shapePath.length);
  23244. for (i = 0; i < shapePath.length; i++) {
  23245. pointCap.push(barycenter);
  23246. }
  23247. return pointCap;
  23248. };
  23249. switch (cap) {
  23250. case BABYLON.Mesh.NO_CAP:
  23251. break;
  23252. case BABYLON.Mesh.CAP_START:
  23253. shapePaths[0] = capPath(shapePaths[2]);
  23254. shapePaths[1] = shapePaths[2].slice(0);
  23255. break;
  23256. case BABYLON.Mesh.CAP_END:
  23257. shapePaths[index] = shapePaths[index - 1];
  23258. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23259. break;
  23260. case BABYLON.Mesh.CAP_ALL:
  23261. shapePaths[0] = capPath(shapePaths[2]);
  23262. shapePaths[1] = shapePaths[2].slice(0);
  23263. shapePaths[index] = shapePaths[index - 1];
  23264. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23265. break;
  23266. default:
  23267. break;
  23268. }
  23269. return shapePaths;
  23270. };
  23271. var path3D;
  23272. var pathArray;
  23273. if (instance) {
  23274. path3D = (instance.path3D).update(curve);
  23275. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23276. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23277. return instance;
  23278. }
  23279. // extruded shape creation
  23280. path3D = new BABYLON.Path3D(curve);
  23281. var newShapePaths = new Array();
  23282. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23283. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23284. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23285. extrudedGeneric.pathArray = pathArray;
  23286. extrudedGeneric.path3D = path3D;
  23287. extrudedGeneric.cap = cap;
  23288. return extrudedGeneric;
  23289. };
  23290. return MeshBuilder;
  23291. }());
  23292. BABYLON.MeshBuilder = MeshBuilder;
  23293. })(BABYLON || (BABYLON = {}));
  23294. //# sourceMappingURL=babylon.meshBuilder.js.map
  23295. var BABYLON;
  23296. (function (BABYLON) {
  23297. var BaseTexture = (function () {
  23298. function BaseTexture(scene) {
  23299. this.hasAlpha = false;
  23300. this.getAlphaFromRGB = false;
  23301. this.level = 1;
  23302. this.coordinatesIndex = 0;
  23303. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23304. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23305. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23306. this.anisotropicFilteringLevel = 4;
  23307. this.isCube = false;
  23308. this.isRenderTarget = false;
  23309. this.animations = new Array();
  23310. /**
  23311. * An event triggered when the texture is disposed.
  23312. * @type {BABYLON.Observable}
  23313. */
  23314. this.onDisposeObservable = new BABYLON.Observable();
  23315. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23316. this._scene = scene;
  23317. this._scene.textures.push(this);
  23318. this._uid = null;
  23319. }
  23320. Object.defineProperty(BaseTexture.prototype, "uid", {
  23321. get: function () {
  23322. if (!this._uid) {
  23323. this._uid = BABYLON.Tools.RandomId();
  23324. }
  23325. return this._uid;
  23326. },
  23327. enumerable: true,
  23328. configurable: true
  23329. });
  23330. BaseTexture.prototype.toString = function () {
  23331. return this.name;
  23332. };
  23333. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23334. set: function (callback) {
  23335. if (this._onDisposeObserver) {
  23336. this.onDisposeObservable.remove(this._onDisposeObserver);
  23337. }
  23338. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23339. },
  23340. enumerable: true,
  23341. configurable: true
  23342. });
  23343. BaseTexture.prototype.getScene = function () {
  23344. return this._scene;
  23345. };
  23346. BaseTexture.prototype.getTextureMatrix = function () {
  23347. return null;
  23348. };
  23349. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23350. return null;
  23351. };
  23352. BaseTexture.prototype.getInternalTexture = function () {
  23353. return this._texture;
  23354. };
  23355. BaseTexture.prototype.isReady = function () {
  23356. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23357. return true;
  23358. }
  23359. if (this._texture) {
  23360. return this._texture.isReady;
  23361. }
  23362. return false;
  23363. };
  23364. BaseTexture.prototype.getSize = function () {
  23365. if (this._texture._width) {
  23366. return new BABYLON.Size(this._texture._width, this._texture._height);
  23367. }
  23368. if (this._texture._size) {
  23369. return new BABYLON.Size(this._texture._size, this._texture._size);
  23370. }
  23371. return BABYLON.Size.Zero();
  23372. };
  23373. BaseTexture.prototype.getBaseSize = function () {
  23374. if (!this.isReady() || !this._texture)
  23375. return BABYLON.Size.Zero();
  23376. if (this._texture._size) {
  23377. return new BABYLON.Size(this._texture._size, this._texture._size);
  23378. }
  23379. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  23380. };
  23381. BaseTexture.prototype.scale = function (ratio) {
  23382. };
  23383. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23384. get: function () {
  23385. return false;
  23386. },
  23387. enumerable: true,
  23388. configurable: true
  23389. });
  23390. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  23391. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23392. for (var index = 0; index < texturesCache.length; index++) {
  23393. var texturesCacheEntry = texturesCache[index];
  23394. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23395. texturesCache.splice(index, 1);
  23396. return;
  23397. }
  23398. }
  23399. };
  23400. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23401. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23402. for (var index = 0; index < texturesCache.length; index++) {
  23403. var texturesCacheEntry = texturesCache[index];
  23404. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23405. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23406. texturesCacheEntry.references++;
  23407. return texturesCacheEntry;
  23408. }
  23409. }
  23410. }
  23411. return null;
  23412. };
  23413. BaseTexture.prototype.delayLoad = function () {
  23414. };
  23415. BaseTexture.prototype.clone = function () {
  23416. return null;
  23417. };
  23418. BaseTexture.prototype.releaseInternalTexture = function () {
  23419. if (this._texture) {
  23420. this._scene.getEngine().releaseInternalTexture(this._texture);
  23421. delete this._texture;
  23422. }
  23423. };
  23424. BaseTexture.prototype.dispose = function () {
  23425. // Animations
  23426. this.getScene().stopAnimation(this);
  23427. // Remove from scene
  23428. var index = this._scene.textures.indexOf(this);
  23429. if (index >= 0) {
  23430. this._scene.textures.splice(index, 1);
  23431. }
  23432. if (this._texture === undefined) {
  23433. return;
  23434. }
  23435. // Release
  23436. this.releaseInternalTexture();
  23437. // Callback
  23438. this.onDisposeObservable.notifyObservers(this);
  23439. this.onDisposeObservable.clear();
  23440. };
  23441. BaseTexture.prototype.serialize = function () {
  23442. if (!this.name) {
  23443. return null;
  23444. }
  23445. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23446. // Animations
  23447. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23448. return serializationObject;
  23449. };
  23450. return BaseTexture;
  23451. }());
  23452. __decorate([
  23453. BABYLON.serialize()
  23454. ], BaseTexture.prototype, "name", void 0);
  23455. __decorate([
  23456. BABYLON.serialize()
  23457. ], BaseTexture.prototype, "hasAlpha", void 0);
  23458. __decorate([
  23459. BABYLON.serialize()
  23460. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23461. __decorate([
  23462. BABYLON.serialize()
  23463. ], BaseTexture.prototype, "level", void 0);
  23464. __decorate([
  23465. BABYLON.serialize()
  23466. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23467. __decorate([
  23468. BABYLON.serialize()
  23469. ], BaseTexture.prototype, "coordinatesMode", void 0);
  23470. __decorate([
  23471. BABYLON.serialize()
  23472. ], BaseTexture.prototype, "wrapU", void 0);
  23473. __decorate([
  23474. BABYLON.serialize()
  23475. ], BaseTexture.prototype, "wrapV", void 0);
  23476. __decorate([
  23477. BABYLON.serialize()
  23478. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23479. __decorate([
  23480. BABYLON.serialize()
  23481. ], BaseTexture.prototype, "isCube", void 0);
  23482. __decorate([
  23483. BABYLON.serialize()
  23484. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23485. BABYLON.BaseTexture = BaseTexture;
  23486. })(BABYLON || (BABYLON = {}));
  23487. //# sourceMappingURL=babylon.baseTexture.js.map
  23488. var BABYLON;
  23489. (function (BABYLON) {
  23490. var Texture = (function (_super) {
  23491. __extends(Texture, _super);
  23492. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  23493. if (noMipmap === void 0) { noMipmap = false; }
  23494. if (invertY === void 0) { invertY = true; }
  23495. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23496. if (onLoad === void 0) { onLoad = null; }
  23497. if (onError === void 0) { onError = null; }
  23498. if (buffer === void 0) { buffer = null; }
  23499. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23500. var _this = _super.call(this, scene) || this;
  23501. _this.uOffset = 0;
  23502. _this.vOffset = 0;
  23503. _this.uScale = 1.0;
  23504. _this.vScale = 1.0;
  23505. _this.uAng = 0;
  23506. _this.vAng = 0;
  23507. _this.wAng = 0;
  23508. _this.name = url;
  23509. _this.url = url;
  23510. _this._noMipmap = noMipmap;
  23511. _this._invertY = invertY;
  23512. _this._samplingMode = samplingMode;
  23513. _this._buffer = buffer;
  23514. _this._deleteBuffer = deleteBuffer;
  23515. if (!url) {
  23516. return _this;
  23517. }
  23518. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  23519. var load = function () {
  23520. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23521. _this.onLoadObservable.notifyObservers(true);
  23522. }
  23523. if (onLoad) {
  23524. onLoad();
  23525. }
  23526. };
  23527. if (!_this._texture) {
  23528. if (!scene.useDelayedTextureLoading) {
  23529. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer);
  23530. if (deleteBuffer) {
  23531. delete _this._buffer;
  23532. }
  23533. }
  23534. else {
  23535. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23536. _this._delayedOnLoad = load;
  23537. _this._delayedOnError = onError;
  23538. }
  23539. }
  23540. else {
  23541. if (_this._texture.isReady) {
  23542. BABYLON.Tools.SetImmediate(function () { return load(); });
  23543. }
  23544. else {
  23545. _this._texture.onLoadedCallbacks.push(load);
  23546. }
  23547. }
  23548. return _this;
  23549. }
  23550. Object.defineProperty(Texture.prototype, "noMipmap", {
  23551. get: function () {
  23552. return this._noMipmap;
  23553. },
  23554. enumerable: true,
  23555. configurable: true
  23556. });
  23557. Texture.prototype.delayLoad = function () {
  23558. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23559. return;
  23560. }
  23561. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23562. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23563. if (!this._texture) {
  23564. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23565. if (this._deleteBuffer) {
  23566. delete this._buffer;
  23567. }
  23568. }
  23569. };
  23570. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23571. if (!this._texture) {
  23572. return;
  23573. }
  23574. this._samplingMode = samplingMode;
  23575. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23576. };
  23577. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23578. x *= this.uScale;
  23579. y *= this.vScale;
  23580. x -= 0.5 * this.uScale;
  23581. y -= 0.5 * this.vScale;
  23582. z -= 0.5;
  23583. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23584. t.x += 0.5 * this.uScale + this.uOffset;
  23585. t.y += 0.5 * this.vScale + this.vOffset;
  23586. t.z += 0.5;
  23587. };
  23588. Texture.prototype.getTextureMatrix = function () {
  23589. if (this.uOffset === this._cachedUOffset &&
  23590. this.vOffset === this._cachedVOffset &&
  23591. this.uScale === this._cachedUScale &&
  23592. this.vScale === this._cachedVScale &&
  23593. this.uAng === this._cachedUAng &&
  23594. this.vAng === this._cachedVAng &&
  23595. this.wAng === this._cachedWAng) {
  23596. return this._cachedTextureMatrix;
  23597. }
  23598. this._cachedUOffset = this.uOffset;
  23599. this._cachedVOffset = this.vOffset;
  23600. this._cachedUScale = this.uScale;
  23601. this._cachedVScale = this.vScale;
  23602. this._cachedUAng = this.uAng;
  23603. this._cachedVAng = this.vAng;
  23604. this._cachedWAng = this.wAng;
  23605. if (!this._cachedTextureMatrix) {
  23606. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23607. this._rowGenerationMatrix = new BABYLON.Matrix();
  23608. this._t0 = BABYLON.Vector3.Zero();
  23609. this._t1 = BABYLON.Vector3.Zero();
  23610. this._t2 = BABYLON.Vector3.Zero();
  23611. }
  23612. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23613. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23614. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23615. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23616. this._t1.subtractInPlace(this._t0);
  23617. this._t2.subtractInPlace(this._t0);
  23618. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23619. this._cachedTextureMatrix.m[0] = this._t1.x;
  23620. this._cachedTextureMatrix.m[1] = this._t1.y;
  23621. this._cachedTextureMatrix.m[2] = this._t1.z;
  23622. this._cachedTextureMatrix.m[4] = this._t2.x;
  23623. this._cachedTextureMatrix.m[5] = this._t2.y;
  23624. this._cachedTextureMatrix.m[6] = this._t2.z;
  23625. this._cachedTextureMatrix.m[8] = this._t0.x;
  23626. this._cachedTextureMatrix.m[9] = this._t0.y;
  23627. this._cachedTextureMatrix.m[10] = this._t0.z;
  23628. return this._cachedTextureMatrix;
  23629. };
  23630. Texture.prototype.getReflectionTextureMatrix = function () {
  23631. if (this.uOffset === this._cachedUOffset &&
  23632. this.vOffset === this._cachedVOffset &&
  23633. this.uScale === this._cachedUScale &&
  23634. this.vScale === this._cachedVScale &&
  23635. this.coordinatesMode === this._cachedCoordinatesMode) {
  23636. return this._cachedTextureMatrix;
  23637. }
  23638. if (!this._cachedTextureMatrix) {
  23639. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23640. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23641. }
  23642. this._cachedCoordinatesMode = this.coordinatesMode;
  23643. switch (this.coordinatesMode) {
  23644. case Texture.PLANAR_MODE:
  23645. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23646. this._cachedTextureMatrix[0] = this.uScale;
  23647. this._cachedTextureMatrix[5] = this.vScale;
  23648. this._cachedTextureMatrix[12] = this.uOffset;
  23649. this._cachedTextureMatrix[13] = this.vOffset;
  23650. break;
  23651. case Texture.PROJECTION_MODE:
  23652. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23653. this._projectionModeMatrix.m[0] = 0.5;
  23654. this._projectionModeMatrix.m[5] = -0.5;
  23655. this._projectionModeMatrix.m[10] = 0.0;
  23656. this._projectionModeMatrix.m[12] = 0.5;
  23657. this._projectionModeMatrix.m[13] = 0.5;
  23658. this._projectionModeMatrix.m[14] = 1.0;
  23659. this._projectionModeMatrix.m[15] = 1.0;
  23660. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23661. break;
  23662. default:
  23663. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23664. break;
  23665. }
  23666. return this._cachedTextureMatrix;
  23667. };
  23668. Texture.prototype.clone = function () {
  23669. var _this = this;
  23670. return BABYLON.SerializationHelper.Clone(function () {
  23671. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23672. }, this);
  23673. };
  23674. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23675. get: function () {
  23676. if (!this._onLoadObservarble) {
  23677. this._onLoadObservarble = new BABYLON.Observable();
  23678. }
  23679. return this._onLoadObservarble;
  23680. },
  23681. enumerable: true,
  23682. configurable: true
  23683. });
  23684. // Statics
  23685. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23686. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23687. if (onLoad === void 0) { onLoad = null; }
  23688. if (onError === void 0) { onError = null; }
  23689. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23690. };
  23691. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23692. if (parsedTexture.customType) {
  23693. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23694. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23695. }
  23696. if (parsedTexture.isCube) {
  23697. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23698. }
  23699. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23700. return null;
  23701. }
  23702. var texture = BABYLON.SerializationHelper.Parse(function () {
  23703. if (parsedTexture.mirrorPlane) {
  23704. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23705. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23706. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23707. return mirrorTexture;
  23708. }
  23709. else if (parsedTexture.isRenderTarget) {
  23710. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23711. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23712. return renderTargetTexture;
  23713. }
  23714. else {
  23715. var texture;
  23716. if (parsedTexture.base64String) {
  23717. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23718. }
  23719. else {
  23720. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23721. }
  23722. return texture;
  23723. }
  23724. }, parsedTexture, scene);
  23725. // Animations
  23726. if (parsedTexture.animations) {
  23727. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23728. var parsedAnimation = parsedTexture.animations[animationIndex];
  23729. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23730. }
  23731. }
  23732. return texture;
  23733. };
  23734. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  23735. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23736. if (noMipmap === void 0) { noMipmap = false; }
  23737. if (invertY === void 0) { invertY = true; }
  23738. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23739. if (onLoad === void 0) { onLoad = null; }
  23740. if (onError === void 0) { onError = null; }
  23741. if (name.substr(0, 5) !== "data:") {
  23742. name = "data:" + name;
  23743. }
  23744. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  23745. };
  23746. return Texture;
  23747. }(BABYLON.BaseTexture));
  23748. // Constants
  23749. Texture.NEAREST_SAMPLINGMODE = 1;
  23750. Texture.BILINEAR_SAMPLINGMODE = 2;
  23751. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23752. Texture.EXPLICIT_MODE = 0;
  23753. Texture.SPHERICAL_MODE = 1;
  23754. Texture.PLANAR_MODE = 2;
  23755. Texture.CUBIC_MODE = 3;
  23756. Texture.PROJECTION_MODE = 4;
  23757. Texture.SKYBOX_MODE = 5;
  23758. Texture.INVCUBIC_MODE = 6;
  23759. Texture.EQUIRECTANGULAR_MODE = 7;
  23760. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23761. Texture.CLAMP_ADDRESSMODE = 0;
  23762. Texture.WRAP_ADDRESSMODE = 1;
  23763. Texture.MIRROR_ADDRESSMODE = 2;
  23764. __decorate([
  23765. BABYLON.serialize()
  23766. ], Texture.prototype, "url", void 0);
  23767. __decorate([
  23768. BABYLON.serialize()
  23769. ], Texture.prototype, "uOffset", void 0);
  23770. __decorate([
  23771. BABYLON.serialize()
  23772. ], Texture.prototype, "vOffset", void 0);
  23773. __decorate([
  23774. BABYLON.serialize()
  23775. ], Texture.prototype, "uScale", void 0);
  23776. __decorate([
  23777. BABYLON.serialize()
  23778. ], Texture.prototype, "vScale", void 0);
  23779. __decorate([
  23780. BABYLON.serialize()
  23781. ], Texture.prototype, "uAng", void 0);
  23782. __decorate([
  23783. BABYLON.serialize()
  23784. ], Texture.prototype, "vAng", void 0);
  23785. __decorate([
  23786. BABYLON.serialize()
  23787. ], Texture.prototype, "wAng", void 0);
  23788. BABYLON.Texture = Texture;
  23789. })(BABYLON || (BABYLON = {}));
  23790. //# sourceMappingURL=babylon.texture.js.map
  23791. var BABYLON;
  23792. (function (BABYLON) {
  23793. var CubeTexture = (function (_super) {
  23794. __extends(CubeTexture, _super);
  23795. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23796. if (onLoad === void 0) { onLoad = null; }
  23797. if (onError === void 0) { onError = null; }
  23798. var _this = _super.call(this, scene) || this;
  23799. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23800. _this.name = rootUrl;
  23801. _this.url = rootUrl;
  23802. _this._noMipmap = noMipmap;
  23803. _this.hasAlpha = false;
  23804. if (!rootUrl && !files) {
  23805. return _this;
  23806. }
  23807. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  23808. if (!files) {
  23809. if (!extensions) {
  23810. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23811. }
  23812. files = [];
  23813. for (var index = 0; index < extensions.length; index++) {
  23814. files.push(rootUrl + extensions[index]);
  23815. }
  23816. _this._extensions = extensions;
  23817. }
  23818. _this._files = files;
  23819. if (!_this._texture) {
  23820. if (!scene.useDelayedTextureLoading) {
  23821. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23822. }
  23823. else {
  23824. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23825. }
  23826. }
  23827. else if (onLoad) {
  23828. if (_this._texture.isReady) {
  23829. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23830. }
  23831. else {
  23832. _this._texture.onLoadedCallbacks.push(onLoad);
  23833. }
  23834. }
  23835. _this.isCube = true;
  23836. _this._textureMatrix = BABYLON.Matrix.Identity();
  23837. return _this;
  23838. }
  23839. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23840. return new CubeTexture("", scene, null, noMipmap, files);
  23841. };
  23842. // Methods
  23843. CubeTexture.prototype.delayLoad = function () {
  23844. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23845. return;
  23846. }
  23847. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23848. this._texture = this._getFromCache(this.url, this._noMipmap);
  23849. if (!this._texture) {
  23850. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23851. }
  23852. };
  23853. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23854. return this._textureMatrix;
  23855. };
  23856. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23857. var texture = BABYLON.SerializationHelper.Parse(function () {
  23858. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23859. }, parsedTexture, scene);
  23860. // Animations
  23861. if (parsedTexture.animations) {
  23862. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23863. var parsedAnimation = parsedTexture.animations[animationIndex];
  23864. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23865. }
  23866. }
  23867. return texture;
  23868. };
  23869. CubeTexture.prototype.clone = function () {
  23870. var _this = this;
  23871. return BABYLON.SerializationHelper.Clone(function () {
  23872. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23873. }, this);
  23874. };
  23875. return CubeTexture;
  23876. }(BABYLON.BaseTexture));
  23877. BABYLON.CubeTexture = CubeTexture;
  23878. })(BABYLON || (BABYLON = {}));
  23879. //# sourceMappingURL=babylon.cubeTexture.js.map
  23880. var BABYLON;
  23881. (function (BABYLON) {
  23882. var RenderTargetTexture = (function (_super) {
  23883. __extends(RenderTargetTexture, _super);
  23884. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23885. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23886. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23887. if (isCube === void 0) { isCube = false; }
  23888. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23889. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23890. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23891. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  23892. _this.isCube = isCube;
  23893. /**
  23894. * Use this list to define the list of mesh you want to render.
  23895. */
  23896. _this.renderList = new Array();
  23897. _this.renderParticles = true;
  23898. _this.renderSprites = false;
  23899. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23900. // Events
  23901. /**
  23902. * An event triggered when the texture is unbind.
  23903. * @type {BABYLON.Observable}
  23904. */
  23905. _this.onAfterUnbindObservable = new BABYLON.Observable();
  23906. /**
  23907. * An event triggered before rendering the texture
  23908. * @type {BABYLON.Observable}
  23909. */
  23910. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23911. /**
  23912. * An event triggered after rendering the texture
  23913. * @type {BABYLON.Observable}
  23914. */
  23915. _this.onAfterRenderObservable = new BABYLON.Observable();
  23916. /**
  23917. * An event triggered after the texture clear
  23918. * @type {BABYLON.Observable}
  23919. */
  23920. _this.onClearObservable = new BABYLON.Observable();
  23921. _this._currentRefreshId = -1;
  23922. _this._refreshRate = 1;
  23923. _this.name = name;
  23924. _this.isRenderTarget = true;
  23925. _this._size = size;
  23926. _this._generateMipMaps = generateMipMaps;
  23927. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23928. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23929. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23930. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23931. }
  23932. if (isCube) {
  23933. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23934. generateMipMaps: generateMipMaps,
  23935. samplingMode: samplingMode,
  23936. generateDepthBuffer: generateDepthBuffer,
  23937. generateStencilBuffer: generateStencilBuffer
  23938. });
  23939. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23940. _this._textureMatrix = BABYLON.Matrix.Identity();
  23941. }
  23942. else {
  23943. _this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23944. generateMipMaps: generateMipMaps,
  23945. type: type,
  23946. samplingMode: samplingMode,
  23947. generateDepthBuffer: generateDepthBuffer,
  23948. generateStencilBuffer: generateStencilBuffer
  23949. });
  23950. }
  23951. // Rendering groups
  23952. _this._renderingManager = new BABYLON.RenderingManager(scene);
  23953. return _this;
  23954. }
  23955. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23956. get: function () {
  23957. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23958. },
  23959. enumerable: true,
  23960. configurable: true
  23961. });
  23962. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23963. get: function () {
  23964. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23965. },
  23966. enumerable: true,
  23967. configurable: true
  23968. });
  23969. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23970. get: function () {
  23971. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23972. },
  23973. enumerable: true,
  23974. configurable: true
  23975. });
  23976. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23977. set: function (callback) {
  23978. if (this._onAfterUnbindObserver) {
  23979. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23980. }
  23981. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23982. },
  23983. enumerable: true,
  23984. configurable: true
  23985. });
  23986. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23987. set: function (callback) {
  23988. if (this._onBeforeRenderObserver) {
  23989. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23990. }
  23991. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23992. },
  23993. enumerable: true,
  23994. configurable: true
  23995. });
  23996. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23997. set: function (callback) {
  23998. if (this._onAfterRenderObserver) {
  23999. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24000. }
  24001. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24002. },
  24003. enumerable: true,
  24004. configurable: true
  24005. });
  24006. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  24007. set: function (callback) {
  24008. if (this._onClearObserver) {
  24009. this.onClearObservable.remove(this._onClearObserver);
  24010. }
  24011. this._onClearObserver = this.onClearObservable.add(callback);
  24012. },
  24013. enumerable: true,
  24014. configurable: true
  24015. });
  24016. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  24017. this._currentRefreshId = -1;
  24018. };
  24019. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  24020. get: function () {
  24021. return this._refreshRate;
  24022. },
  24023. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24024. set: function (value) {
  24025. this._refreshRate = value;
  24026. this.resetRefreshCounter();
  24027. },
  24028. enumerable: true,
  24029. configurable: true
  24030. });
  24031. RenderTargetTexture.prototype._shouldRender = function () {
  24032. if (this._currentRefreshId === -1) {
  24033. this._currentRefreshId = 1;
  24034. return true;
  24035. }
  24036. if (this.refreshRate === this._currentRefreshId) {
  24037. this._currentRefreshId = 1;
  24038. return true;
  24039. }
  24040. this._currentRefreshId++;
  24041. return false;
  24042. };
  24043. RenderTargetTexture.prototype.isReady = function () {
  24044. if (!this.getScene().renderTargetsEnabled) {
  24045. return false;
  24046. }
  24047. return _super.prototype.isReady.call(this);
  24048. };
  24049. RenderTargetTexture.prototype.getRenderSize = function () {
  24050. return this._size;
  24051. };
  24052. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24053. get: function () {
  24054. return true;
  24055. },
  24056. enumerable: true,
  24057. configurable: true
  24058. });
  24059. RenderTargetTexture.prototype.scale = function (ratio) {
  24060. var newSize = this._size * ratio;
  24061. this.resize(newSize, this._generateMipMaps);
  24062. };
  24063. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24064. if (this.isCube) {
  24065. return this._textureMatrix;
  24066. }
  24067. return _super.prototype.getReflectionTextureMatrix.call(this);
  24068. };
  24069. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  24070. this.releaseInternalTexture();
  24071. if (this.isCube) {
  24072. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  24073. }
  24074. else {
  24075. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24076. }
  24077. };
  24078. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24079. var scene = this.getScene();
  24080. var engine = scene.getEngine();
  24081. if (this.useCameraPostProcesses !== undefined) {
  24082. useCameraPostProcess = this.useCameraPostProcesses;
  24083. }
  24084. if (this._waitingRenderList) {
  24085. this.renderList = [];
  24086. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24087. var id = this._waitingRenderList[index];
  24088. this.renderList.push(scene.getMeshByID(id));
  24089. }
  24090. delete this._waitingRenderList;
  24091. }
  24092. // Is predicate defined?
  24093. if (this.renderListPredicate) {
  24094. this.renderList.splice(0); // Clear previous renderList
  24095. var sceneMeshes = this.getScene().meshes;
  24096. for (var index = 0; index < sceneMeshes.length; index++) {
  24097. var mesh = sceneMeshes[index];
  24098. if (this.renderListPredicate(mesh)) {
  24099. this.renderList.push(mesh);
  24100. }
  24101. }
  24102. }
  24103. if (this.renderList && this.renderList.length === 0) {
  24104. return;
  24105. }
  24106. // Set custom projection.
  24107. // Needs to be before binding to prevent changing the aspect ratio.
  24108. if (this.activeCamera) {
  24109. engine.setViewport(this.activeCamera.viewport);
  24110. if (this.activeCamera !== scene.activeCamera) {
  24111. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24112. }
  24113. }
  24114. else {
  24115. engine.setViewport(scene.activeCamera.viewport);
  24116. }
  24117. // Prepare renderingManager
  24118. this._renderingManager.reset();
  24119. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24120. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24121. var sceneRenderId = scene.getRenderId();
  24122. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24123. var mesh = currentRenderList[meshIndex];
  24124. if (mesh) {
  24125. if (!mesh.isReady()) {
  24126. // Reset _currentRefreshId
  24127. this.resetRefreshCounter();
  24128. continue;
  24129. }
  24130. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24131. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24132. mesh._activate(sceneRenderId);
  24133. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24134. var subMesh = mesh.subMeshes[subIndex];
  24135. scene._activeIndices.addCount(subMesh.indexCount, false);
  24136. this._renderingManager.dispatch(subMesh);
  24137. }
  24138. }
  24139. }
  24140. }
  24141. if (this.isCube) {
  24142. for (var face = 0; face < 6; face++) {
  24143. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24144. scene.incrementRenderId();
  24145. scene.resetCachedMaterial();
  24146. }
  24147. }
  24148. else {
  24149. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24150. }
  24151. this.onAfterUnbindObservable.notifyObservers(this);
  24152. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24153. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24154. }
  24155. engine.setViewport(scene.activeCamera.viewport);
  24156. scene.resetCachedMaterial();
  24157. };
  24158. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24159. var scene = this.getScene();
  24160. var engine = scene.getEngine();
  24161. // Bind
  24162. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24163. if (this.isCube) {
  24164. engine.bindFramebuffer(this._texture, faceIndex);
  24165. }
  24166. else {
  24167. engine.bindFramebuffer(this._texture);
  24168. }
  24169. }
  24170. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24171. // Clear
  24172. if (this.onClearObservable.hasObservers()) {
  24173. this.onClearObservable.notifyObservers(engine);
  24174. }
  24175. else {
  24176. engine.clear(scene.clearColor, true, true, true);
  24177. }
  24178. if (!this._doNotChangeAspectRatio) {
  24179. scene.updateTransformMatrix(true);
  24180. }
  24181. // Render
  24182. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24183. if (useCameraPostProcess) {
  24184. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24185. }
  24186. if (!this._doNotChangeAspectRatio) {
  24187. scene.updateTransformMatrix(true);
  24188. }
  24189. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24190. // Dump ?
  24191. if (dumpForDebug) {
  24192. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24193. }
  24194. // Unbind
  24195. if (!this.isCube || faceIndex === 5) {
  24196. if (this.isCube) {
  24197. if (faceIndex === 5) {
  24198. engine.generateMipMapsForCubemap(this._texture);
  24199. }
  24200. }
  24201. engine.unBindFramebuffer(this._texture, this.isCube);
  24202. }
  24203. };
  24204. /**
  24205. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24206. * This allowed control for front to back rendering or reversly depending of the special needs.
  24207. *
  24208. * @param renderingGroupId The rendering group id corresponding to its index
  24209. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24210. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24211. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24212. */
  24213. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24214. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24215. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24216. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24217. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24218. };
  24219. /**
  24220. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24221. *
  24222. * @param renderingGroupId The rendering group id corresponding to its index
  24223. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24224. */
  24225. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24226. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24227. };
  24228. RenderTargetTexture.prototype.clone = function () {
  24229. var textureSize = this.getSize();
  24230. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24231. // Base texture
  24232. newTexture.hasAlpha = this.hasAlpha;
  24233. newTexture.level = this.level;
  24234. // RenderTarget Texture
  24235. newTexture.coordinatesMode = this.coordinatesMode;
  24236. newTexture.renderList = this.renderList.slice(0);
  24237. return newTexture;
  24238. };
  24239. RenderTargetTexture.prototype.serialize = function () {
  24240. if (!this.name) {
  24241. return null;
  24242. }
  24243. var serializationObject = _super.prototype.serialize.call(this);
  24244. serializationObject.renderTargetSize = this.getRenderSize();
  24245. serializationObject.renderList = [];
  24246. for (var index = 0; index < this.renderList.length; index++) {
  24247. serializationObject.renderList.push(this.renderList[index].id);
  24248. }
  24249. return serializationObject;
  24250. };
  24251. return RenderTargetTexture;
  24252. }(BABYLON.Texture));
  24253. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24254. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24255. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24256. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24257. })(BABYLON || (BABYLON = {}));
  24258. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  24259. var BABYLON;
  24260. (function (BABYLON) {
  24261. var ProceduralTexture = (function (_super) {
  24262. __extends(ProceduralTexture, _super);
  24263. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24264. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24265. if (isCube === void 0) { isCube = false; }
  24266. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24267. _this.isCube = isCube;
  24268. _this.isEnabled = true;
  24269. _this._currentRefreshId = -1;
  24270. _this._refreshRate = 1;
  24271. _this._vertexBuffers = {};
  24272. _this._uniforms = new Array();
  24273. _this._samplers = new Array();
  24274. _this._textures = new Array();
  24275. _this._floats = new Array();
  24276. _this._floatsArrays = {};
  24277. _this._colors3 = new Array();
  24278. _this._colors4 = new Array();
  24279. _this._vectors2 = new Array();
  24280. _this._vectors3 = new Array();
  24281. _this._matrices = new Array();
  24282. _this._fallbackTextureUsed = false;
  24283. scene._proceduralTextures.push(_this);
  24284. _this.name = name;
  24285. _this.isRenderTarget = true;
  24286. _this._size = size;
  24287. _this._generateMipMaps = generateMipMaps;
  24288. _this.setFragment(fragment);
  24289. _this._fallbackTexture = fallbackTexture;
  24290. var engine = scene.getEngine();
  24291. if (isCube) {
  24292. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24293. _this.setFloat("face", 0);
  24294. }
  24295. else {
  24296. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24297. }
  24298. // VBO
  24299. var vertices = [];
  24300. vertices.push(1, 1);
  24301. vertices.push(-1, 1);
  24302. vertices.push(-1, -1);
  24303. vertices.push(1, -1);
  24304. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24305. // Indices
  24306. var indices = [];
  24307. indices.push(0);
  24308. indices.push(1);
  24309. indices.push(2);
  24310. indices.push(0);
  24311. indices.push(2);
  24312. indices.push(3);
  24313. _this._indexBuffer = engine.createIndexBuffer(indices);
  24314. return _this;
  24315. }
  24316. ProceduralTexture.prototype.reset = function () {
  24317. if (this._effect === undefined) {
  24318. return;
  24319. }
  24320. var engine = this.getScene().getEngine();
  24321. engine._releaseEffect(this._effect);
  24322. };
  24323. ProceduralTexture.prototype.isReady = function () {
  24324. var _this = this;
  24325. var engine = this.getScene().getEngine();
  24326. var shaders;
  24327. if (!this._fragment) {
  24328. return false;
  24329. }
  24330. if (this._fallbackTextureUsed) {
  24331. return true;
  24332. }
  24333. if (this._fragment.fragmentElement !== undefined) {
  24334. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24335. }
  24336. else {
  24337. shaders = { vertex: "procedural", fragment: this._fragment };
  24338. }
  24339. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24340. _this.releaseInternalTexture();
  24341. if (_this._fallbackTexture) {
  24342. _this._texture = _this._fallbackTexture._texture;
  24343. _this._texture.references++;
  24344. }
  24345. _this._fallbackTextureUsed = true;
  24346. });
  24347. return this._effect.isReady();
  24348. };
  24349. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24350. this._currentRefreshId = -1;
  24351. };
  24352. ProceduralTexture.prototype.setFragment = function (fragment) {
  24353. this._fragment = fragment;
  24354. };
  24355. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24356. get: function () {
  24357. return this._refreshRate;
  24358. },
  24359. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24360. set: function (value) {
  24361. this._refreshRate = value;
  24362. this.resetRefreshCounter();
  24363. },
  24364. enumerable: true,
  24365. configurable: true
  24366. });
  24367. ProceduralTexture.prototype._shouldRender = function () {
  24368. if (!this.isEnabled || !this.isReady() || !this._texture) {
  24369. return false;
  24370. }
  24371. if (this._fallbackTextureUsed) {
  24372. return false;
  24373. }
  24374. if (this._currentRefreshId === -1) {
  24375. this._currentRefreshId = 1;
  24376. return true;
  24377. }
  24378. if (this.refreshRate === this._currentRefreshId) {
  24379. this._currentRefreshId = 1;
  24380. return true;
  24381. }
  24382. this._currentRefreshId++;
  24383. return false;
  24384. };
  24385. ProceduralTexture.prototype.getRenderSize = function () {
  24386. return this._size;
  24387. };
  24388. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  24389. if (this._fallbackTextureUsed) {
  24390. return;
  24391. }
  24392. this.releaseInternalTexture();
  24393. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24394. };
  24395. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  24396. if (this._uniforms.indexOf(uniformName) === -1) {
  24397. this._uniforms.push(uniformName);
  24398. }
  24399. };
  24400. ProceduralTexture.prototype.setTexture = function (name, texture) {
  24401. if (this._samplers.indexOf(name) === -1) {
  24402. this._samplers.push(name);
  24403. }
  24404. this._textures[name] = texture;
  24405. return this;
  24406. };
  24407. ProceduralTexture.prototype.setFloat = function (name, value) {
  24408. this._checkUniform(name);
  24409. this._floats[name] = value;
  24410. return this;
  24411. };
  24412. ProceduralTexture.prototype.setFloats = function (name, value) {
  24413. this._checkUniform(name);
  24414. this._floatsArrays[name] = value;
  24415. return this;
  24416. };
  24417. ProceduralTexture.prototype.setColor3 = function (name, value) {
  24418. this._checkUniform(name);
  24419. this._colors3[name] = value;
  24420. return this;
  24421. };
  24422. ProceduralTexture.prototype.setColor4 = function (name, value) {
  24423. this._checkUniform(name);
  24424. this._colors4[name] = value;
  24425. return this;
  24426. };
  24427. ProceduralTexture.prototype.setVector2 = function (name, value) {
  24428. this._checkUniform(name);
  24429. this._vectors2[name] = value;
  24430. return this;
  24431. };
  24432. ProceduralTexture.prototype.setVector3 = function (name, value) {
  24433. this._checkUniform(name);
  24434. this._vectors3[name] = value;
  24435. return this;
  24436. };
  24437. ProceduralTexture.prototype.setMatrix = function (name, value) {
  24438. this._checkUniform(name);
  24439. this._matrices[name] = value;
  24440. return this;
  24441. };
  24442. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24443. var scene = this.getScene();
  24444. var engine = scene.getEngine();
  24445. // Render
  24446. engine.enableEffect(this._effect);
  24447. engine.setState(false);
  24448. // Texture
  24449. for (var name in this._textures) {
  24450. this._effect.setTexture(name, this._textures[name]);
  24451. }
  24452. // Float
  24453. for (name in this._floats) {
  24454. this._effect.setFloat(name, this._floats[name]);
  24455. }
  24456. // Floats
  24457. for (name in this._floatsArrays) {
  24458. this._effect.setArray(name, this._floatsArrays[name]);
  24459. }
  24460. // Color3
  24461. for (name in this._colors3) {
  24462. this._effect.setColor3(name, this._colors3[name]);
  24463. }
  24464. // Color4
  24465. for (name in this._colors4) {
  24466. var color = this._colors4[name];
  24467. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24468. }
  24469. // Vector2
  24470. for (name in this._vectors2) {
  24471. this._effect.setVector2(name, this._vectors2[name]);
  24472. }
  24473. // Vector3
  24474. for (name in this._vectors3) {
  24475. this._effect.setVector3(name, this._vectors3[name]);
  24476. }
  24477. // Matrix
  24478. for (name in this._matrices) {
  24479. this._effect.setMatrix(name, this._matrices[name]);
  24480. }
  24481. // VBOs
  24482. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  24483. if (this.isCube) {
  24484. for (var face = 0; face < 6; face++) {
  24485. engine.bindFramebuffer(this._texture, face);
  24486. this._effect.setFloat("face", face);
  24487. // Clear
  24488. engine.clear(scene.clearColor, true, true, true);
  24489. // Draw order
  24490. engine.draw(true, 0, 6);
  24491. // Mipmaps
  24492. if (face === 5) {
  24493. engine.generateMipMapsForCubemap(this._texture);
  24494. }
  24495. }
  24496. }
  24497. else {
  24498. engine.bindFramebuffer(this._texture);
  24499. // Clear
  24500. engine.clear(scene.clearColor, true, true, true);
  24501. // Draw order
  24502. engine.draw(true, 0, 6);
  24503. }
  24504. // Unbind
  24505. engine.unBindFramebuffer(this._texture, this.isCube);
  24506. if (this.onGenerated) {
  24507. this.onGenerated();
  24508. }
  24509. };
  24510. ProceduralTexture.prototype.clone = function () {
  24511. var textureSize = this.getSize();
  24512. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  24513. // Base texture
  24514. newTexture.hasAlpha = this.hasAlpha;
  24515. newTexture.level = this.level;
  24516. // RenderTarget Texture
  24517. newTexture.coordinatesMode = this.coordinatesMode;
  24518. return newTexture;
  24519. };
  24520. ProceduralTexture.prototype.dispose = function () {
  24521. var index = this.getScene()._proceduralTextures.indexOf(this);
  24522. if (index >= 0) {
  24523. this.getScene()._proceduralTextures.splice(index, 1);
  24524. }
  24525. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  24526. if (vertexBuffer) {
  24527. vertexBuffer.dispose();
  24528. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  24529. }
  24530. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  24531. this._indexBuffer = null;
  24532. }
  24533. _super.prototype.dispose.call(this);
  24534. };
  24535. return ProceduralTexture;
  24536. }(BABYLON.Texture));
  24537. BABYLON.ProceduralTexture = ProceduralTexture;
  24538. })(BABYLON || (BABYLON = {}));
  24539. //# sourceMappingURL=babylon.proceduralTexture.js.map
  24540. var BABYLON;
  24541. (function (BABYLON) {
  24542. var MirrorTexture = (function (_super) {
  24543. __extends(MirrorTexture, _super);
  24544. function MirrorTexture(name, size, scene, generateMipMaps) {
  24545. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  24546. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24547. _this._transformMatrix = BABYLON.Matrix.Zero();
  24548. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  24549. _this.onBeforeRenderObservable.add(function () {
  24550. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24551. _this._savedViewMatrix = scene.getViewMatrix();
  24552. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24553. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24554. scene.clipPlane = _this.mirrorPlane;
  24555. scene.getEngine().cullBackFaces = false;
  24556. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24557. });
  24558. _this.onAfterRenderObservable.add(function () {
  24559. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24560. scene.getEngine().cullBackFaces = true;
  24561. scene._mirroredCameraPosition = null;
  24562. delete scene.clipPlane;
  24563. });
  24564. return _this;
  24565. }
  24566. MirrorTexture.prototype.clone = function () {
  24567. var textureSize = this.getSize();
  24568. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24569. // Base texture
  24570. newTexture.hasAlpha = this.hasAlpha;
  24571. newTexture.level = this.level;
  24572. // Mirror Texture
  24573. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24574. newTexture.renderList = this.renderList.slice(0);
  24575. return newTexture;
  24576. };
  24577. MirrorTexture.prototype.serialize = function () {
  24578. if (!this.name) {
  24579. return null;
  24580. }
  24581. var serializationObject = _super.prototype.serialize.call(this);
  24582. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24583. return serializationObject;
  24584. };
  24585. return MirrorTexture;
  24586. }(BABYLON.RenderTargetTexture));
  24587. BABYLON.MirrorTexture = MirrorTexture;
  24588. })(BABYLON || (BABYLON = {}));
  24589. //# sourceMappingURL=babylon.mirrorTexture.js.map
  24590. var BABYLON;
  24591. (function (BABYLON) {
  24592. /**
  24593. * Creates a refraction texture used by refraction channel of the standard material.
  24594. * @param name the texture name
  24595. * @param size size of the underlying texture
  24596. * @param scene root scene
  24597. */
  24598. var RefractionTexture = (function (_super) {
  24599. __extends(RefractionTexture, _super);
  24600. function RefractionTexture(name, size, scene, generateMipMaps) {
  24601. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  24602. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24603. _this.depth = 2.0;
  24604. _this.onBeforeRenderObservable.add(function () {
  24605. scene.clipPlane = _this.refractionPlane;
  24606. });
  24607. _this.onAfterRenderObservable.add(function () {
  24608. delete scene.clipPlane;
  24609. });
  24610. return _this;
  24611. }
  24612. RefractionTexture.prototype.clone = function () {
  24613. var textureSize = this.getSize();
  24614. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24615. // Base texture
  24616. newTexture.hasAlpha = this.hasAlpha;
  24617. newTexture.level = this.level;
  24618. // Refraction Texture
  24619. newTexture.refractionPlane = this.refractionPlane.clone();
  24620. newTexture.renderList = this.renderList.slice(0);
  24621. newTexture.depth = this.depth;
  24622. return newTexture;
  24623. };
  24624. RefractionTexture.prototype.serialize = function () {
  24625. if (!this.name) {
  24626. return null;
  24627. }
  24628. var serializationObject = _super.prototype.serialize.call(this);
  24629. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24630. serializationObject.depth = this.depth;
  24631. return serializationObject;
  24632. };
  24633. return RefractionTexture;
  24634. }(BABYLON.RenderTargetTexture));
  24635. BABYLON.RefractionTexture = RefractionTexture;
  24636. })(BABYLON || (BABYLON = {}));
  24637. //# sourceMappingURL=babylon.refractionTexture.js.map
  24638. var BABYLON;
  24639. (function (BABYLON) {
  24640. var DynamicTexture = (function (_super) {
  24641. __extends(DynamicTexture, _super);
  24642. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24644. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24645. _this.name = name;
  24646. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24647. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24648. _this._generateMipMaps = generateMipMaps;
  24649. if (options.getContext) {
  24650. _this._canvas = options;
  24651. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24652. }
  24653. else {
  24654. _this._canvas = document.createElement("canvas");
  24655. if (options.width) {
  24656. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24657. }
  24658. else {
  24659. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24660. }
  24661. }
  24662. var textureSize = _this.getSize();
  24663. _this._canvas.width = textureSize.width;
  24664. _this._canvas.height = textureSize.height;
  24665. _this._context = _this._canvas.getContext("2d");
  24666. return _this;
  24667. }
  24668. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24669. get: function () {
  24670. return true;
  24671. },
  24672. enumerable: true,
  24673. configurable: true
  24674. });
  24675. DynamicTexture.prototype.scale = function (ratio) {
  24676. var textureSize = this.getSize();
  24677. textureSize.width *= ratio;
  24678. textureSize.height *= ratio;
  24679. this._canvas.width = textureSize.width;
  24680. this._canvas.height = textureSize.height;
  24681. this.releaseInternalTexture();
  24682. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24683. };
  24684. DynamicTexture.prototype.getContext = function () {
  24685. return this._context;
  24686. };
  24687. DynamicTexture.prototype.clear = function () {
  24688. var size = this.getSize();
  24689. this._context.fillRect(0, 0, size.width, size.height);
  24690. };
  24691. DynamicTexture.prototype.update = function (invertY) {
  24692. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24693. };
  24694. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24695. if (update === void 0) { update = true; }
  24696. var size = this.getSize();
  24697. if (clearColor) {
  24698. this._context.fillStyle = clearColor;
  24699. this._context.fillRect(0, 0, size.width, size.height);
  24700. }
  24701. this._context.font = font;
  24702. if (x === null) {
  24703. var textSize = this._context.measureText(text);
  24704. x = (size.width - textSize.width) / 2;
  24705. }
  24706. this._context.fillStyle = color;
  24707. this._context.fillText(text, x, y);
  24708. if (update) {
  24709. this.update(invertY);
  24710. }
  24711. };
  24712. DynamicTexture.prototype.clone = function () {
  24713. var textureSize = this.getSize();
  24714. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24715. // Base texture
  24716. newTexture.hasAlpha = this.hasAlpha;
  24717. newTexture.level = this.level;
  24718. // Dynamic Texture
  24719. newTexture.wrapU = this.wrapU;
  24720. newTexture.wrapV = this.wrapV;
  24721. return newTexture;
  24722. };
  24723. return DynamicTexture;
  24724. }(BABYLON.Texture));
  24725. BABYLON.DynamicTexture = DynamicTexture;
  24726. })(BABYLON || (BABYLON = {}));
  24727. //# sourceMappingURL=babylon.dynamicTexture.js.map
  24728. var BABYLON;
  24729. (function (BABYLON) {
  24730. var VideoTexture = (function (_super) {
  24731. __extends(VideoTexture, _super);
  24732. /**
  24733. * Creates a video texture.
  24734. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24735. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24736. * @param {BABYLON.Scene} scene is obviously the current scene.
  24737. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24738. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24739. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24740. */
  24741. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24742. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24743. if (invertY === void 0) { invertY = false; }
  24744. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24745. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  24746. _this._autoLaunch = true;
  24747. var urls;
  24748. _this.name = name;
  24749. if (urlsOrVideo instanceof HTMLVideoElement) {
  24750. _this.video = urlsOrVideo;
  24751. }
  24752. else {
  24753. urls = urlsOrVideo;
  24754. _this.video = document.createElement("video");
  24755. _this.video.autoplay = false;
  24756. _this.video.loop = true;
  24757. }
  24758. _this._generateMipMaps = generateMipMaps;
  24759. _this._samplingMode = samplingMode;
  24760. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  24761. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24762. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24763. }
  24764. else {
  24765. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24766. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24767. _this._generateMipMaps = false;
  24768. }
  24769. if (urls) {
  24770. _this.video.addEventListener("canplaythrough", function () {
  24771. _this._createTexture();
  24772. });
  24773. urls.forEach(function (url) {
  24774. var source = document.createElement("source");
  24775. source.src = url;
  24776. _this.video.appendChild(source);
  24777. });
  24778. }
  24779. else {
  24780. _this._createTexture();
  24781. }
  24782. _this._lastUpdate = BABYLON.Tools.Now;
  24783. return _this;
  24784. }
  24785. VideoTexture.prototype._createTexture = function () {
  24786. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24787. this._texture.isReady = true;
  24788. };
  24789. VideoTexture.prototype.update = function () {
  24790. if (this._autoLaunch) {
  24791. this._autoLaunch = false;
  24792. this.video.play();
  24793. }
  24794. var now = BABYLON.Tools.Now;
  24795. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24796. return false;
  24797. }
  24798. this._lastUpdate = now;
  24799. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24800. return true;
  24801. };
  24802. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  24803. var video = document.createElement("video");
  24804. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  24805. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  24806. if (navigator.getUserMedia) {
  24807. navigator.getUserMedia({
  24808. video: {
  24809. width: {
  24810. min: (constraints && constraints.minWidth) || 256,
  24811. max: (constraints && constraints.maxWidth) || 640
  24812. },
  24813. height: {
  24814. min: (constraints && constraints.minHeight) || 256,
  24815. max: (constraints && constraints.maxHeight) || 480
  24816. }
  24817. }
  24818. }, function (stream) {
  24819. if (video.mozSrcObject !== undefined) {
  24820. video.mozSrcObject = stream;
  24821. }
  24822. else {
  24823. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  24824. }
  24825. video.play();
  24826. if (onReady) {
  24827. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  24828. }
  24829. }, function (e) {
  24830. BABYLON.Tools.Error(e.name);
  24831. });
  24832. }
  24833. };
  24834. return VideoTexture;
  24835. }(BABYLON.Texture));
  24836. BABYLON.VideoTexture = VideoTexture;
  24837. })(BABYLON || (BABYLON = {}));
  24838. //# sourceMappingURL=babylon.videoTexture.js.map
  24839. var BABYLON;
  24840. (function (BABYLON) {
  24841. var CustomProceduralTexture = (function (_super) {
  24842. __extends(CustomProceduralTexture, _super);
  24843. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24844. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  24845. _this._animate = true;
  24846. _this._time = 0;
  24847. _this._texturePath = texturePath;
  24848. //Try to load json
  24849. _this.loadJson(texturePath);
  24850. _this.refreshRate = 1;
  24851. return _this;
  24852. }
  24853. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24854. var _this = this;
  24855. var that = this;
  24856. function noConfigFile() {
  24857. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24858. try {
  24859. that.setFragment(that._texturePath);
  24860. }
  24861. catch (ex) {
  24862. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24863. }
  24864. }
  24865. var configFileUrl = jsonUrl + "/config.json";
  24866. var xhr = new XMLHttpRequest();
  24867. xhr.open("GET", configFileUrl, true);
  24868. xhr.addEventListener("load", function () {
  24869. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24870. try {
  24871. _this._config = JSON.parse(xhr.response);
  24872. _this.updateShaderUniforms();
  24873. _this.updateTextures();
  24874. _this.setFragment(_this._texturePath + "/custom");
  24875. _this._animate = _this._config.animate;
  24876. _this.refreshRate = _this._config.refreshrate;
  24877. }
  24878. catch (ex) {
  24879. noConfigFile();
  24880. }
  24881. }
  24882. else {
  24883. noConfigFile();
  24884. }
  24885. }, false);
  24886. xhr.addEventListener("error", function () {
  24887. noConfigFile();
  24888. }, false);
  24889. try {
  24890. xhr.send();
  24891. }
  24892. catch (ex) {
  24893. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24894. }
  24895. };
  24896. CustomProceduralTexture.prototype.isReady = function () {
  24897. if (!_super.prototype.isReady.call(this)) {
  24898. return false;
  24899. }
  24900. for (var name in this._textures) {
  24901. var texture = this._textures[name];
  24902. if (!texture.isReady()) {
  24903. return false;
  24904. }
  24905. }
  24906. return true;
  24907. };
  24908. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24909. if (this._animate) {
  24910. this._time += this.getScene().getAnimationRatio() * 0.03;
  24911. this.updateShaderUniforms();
  24912. }
  24913. _super.prototype.render.call(this, useCameraPostProcess);
  24914. };
  24915. CustomProceduralTexture.prototype.updateTextures = function () {
  24916. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24917. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24918. }
  24919. };
  24920. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24921. if (this._config) {
  24922. for (var j = 0; j < this._config.uniforms.length; j++) {
  24923. var uniform = this._config.uniforms[j];
  24924. switch (uniform.type) {
  24925. case "float":
  24926. this.setFloat(uniform.name, uniform.value);
  24927. break;
  24928. case "color3":
  24929. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24930. break;
  24931. case "color4":
  24932. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24933. break;
  24934. case "vector2":
  24935. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24936. break;
  24937. case "vector3":
  24938. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24939. break;
  24940. }
  24941. }
  24942. }
  24943. this.setFloat("time", this._time);
  24944. };
  24945. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24946. get: function () {
  24947. return this._animate;
  24948. },
  24949. set: function (value) {
  24950. this._animate = value;
  24951. },
  24952. enumerable: true,
  24953. configurable: true
  24954. });
  24955. return CustomProceduralTexture;
  24956. }(BABYLON.ProceduralTexture));
  24957. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24958. })(BABYLON || (BABYLON = {}));
  24959. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  24960. var BABYLON;
  24961. (function (BABYLON) {
  24962. var EffectFallbacks = (function () {
  24963. function EffectFallbacks() {
  24964. this._defines = {};
  24965. this._currentRank = 32;
  24966. this._maxRank = -1;
  24967. }
  24968. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24969. if (!this._defines[rank]) {
  24970. if (rank < this._currentRank) {
  24971. this._currentRank = rank;
  24972. }
  24973. if (rank > this._maxRank) {
  24974. this._maxRank = rank;
  24975. }
  24976. this._defines[rank] = new Array();
  24977. }
  24978. this._defines[rank].push(define);
  24979. };
  24980. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24981. this._meshRank = rank;
  24982. this._mesh = mesh;
  24983. if (rank > this._maxRank) {
  24984. this._maxRank = rank;
  24985. }
  24986. };
  24987. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24988. get: function () {
  24989. return this._currentRank <= this._maxRank;
  24990. },
  24991. enumerable: true,
  24992. configurable: true
  24993. });
  24994. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24995. var currentFallbacks = this._defines[this._currentRank];
  24996. for (var index = 0; index < currentFallbacks.length; index++) {
  24997. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24998. }
  24999. if (this._mesh && this._currentRank === this._meshRank) {
  25000. this._mesh.computeBonesUsingShaders = false;
  25001. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25002. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25003. }
  25004. this._currentRank++;
  25005. return currentDefines;
  25006. };
  25007. return EffectFallbacks;
  25008. }());
  25009. BABYLON.EffectFallbacks = EffectFallbacks;
  25010. var Effect = (function () {
  25011. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25012. var _this = this;
  25013. this._isReady = false;
  25014. this._compilationError = "";
  25015. this._valueCache = {};
  25016. this._engine = engine;
  25017. this.name = baseName;
  25018. this.defines = defines;
  25019. this._uniformsNames = uniformsNames.concat(samplers);
  25020. this._samplers = samplers;
  25021. this._attributesNames = attributesNames;
  25022. this.onError = onError;
  25023. this.onCompiled = onCompiled;
  25024. this._indexParameters = indexParameters;
  25025. var vertexSource;
  25026. var fragmentSource;
  25027. if (baseName.vertexElement) {
  25028. vertexSource = document.getElementById(baseName.vertexElement);
  25029. if (!vertexSource) {
  25030. vertexSource = baseName.vertexElement;
  25031. }
  25032. }
  25033. else {
  25034. vertexSource = baseName.vertex || baseName;
  25035. }
  25036. if (baseName.fragmentElement) {
  25037. fragmentSource = document.getElementById(baseName.fragmentElement);
  25038. if (!fragmentSource) {
  25039. fragmentSource = baseName.fragmentElement;
  25040. }
  25041. }
  25042. else {
  25043. fragmentSource = baseName.fragment || baseName;
  25044. }
  25045. this._loadVertexShader(vertexSource, function (vertexCode) {
  25046. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25047. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25048. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25049. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  25050. });
  25051. });
  25052. });
  25053. });
  25054. }
  25055. // Properties
  25056. Effect.prototype.isReady = function () {
  25057. return this._isReady;
  25058. };
  25059. Effect.prototype.getProgram = function () {
  25060. return this._program;
  25061. };
  25062. Effect.prototype.getAttributesNames = function () {
  25063. return this._attributesNames;
  25064. };
  25065. Effect.prototype.getAttributeLocation = function (index) {
  25066. return this._attributes[index];
  25067. };
  25068. Effect.prototype.getAttributeLocationByName = function (name) {
  25069. var index = this._attributesNames.indexOf(name);
  25070. return this._attributes[index];
  25071. };
  25072. Effect.prototype.getAttributesCount = function () {
  25073. return this._attributes.length;
  25074. };
  25075. Effect.prototype.getUniformIndex = function (uniformName) {
  25076. return this._uniformsNames.indexOf(uniformName);
  25077. };
  25078. Effect.prototype.getUniform = function (uniformName) {
  25079. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25080. };
  25081. Effect.prototype.getSamplers = function () {
  25082. return this._samplers;
  25083. };
  25084. Effect.prototype.getCompilationError = function () {
  25085. return this._compilationError;
  25086. };
  25087. Effect.prototype.getVertexShaderSource = function () {
  25088. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  25089. };
  25090. Effect.prototype.getFragmentShaderSource = function () {
  25091. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  25092. };
  25093. // Methods
  25094. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25095. // DOM element ?
  25096. if (vertex instanceof HTMLElement) {
  25097. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25098. callback(vertexCode);
  25099. return;
  25100. }
  25101. // Base64 encoded ?
  25102. if (vertex.substr(0, 7) === "base64:") {
  25103. var vertexBinary = window.atob(vertex.substr(7));
  25104. callback(vertexBinary);
  25105. return;
  25106. }
  25107. // Is in local store ?
  25108. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25109. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25110. return;
  25111. }
  25112. var vertexShaderUrl;
  25113. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25114. vertexShaderUrl = vertex;
  25115. }
  25116. else {
  25117. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25118. }
  25119. // Vertex shader
  25120. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25121. };
  25122. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25123. // DOM element ?
  25124. if (fragment instanceof HTMLElement) {
  25125. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25126. callback(fragmentCode);
  25127. return;
  25128. }
  25129. // Base64 encoded ?
  25130. if (fragment.substr(0, 7) === "base64:") {
  25131. var fragmentBinary = window.atob(fragment.substr(7));
  25132. callback(fragmentBinary);
  25133. return;
  25134. }
  25135. // Is in local store ?
  25136. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25137. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25138. return;
  25139. }
  25140. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25141. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25142. return;
  25143. }
  25144. var fragmentShaderUrl;
  25145. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25146. fragmentShaderUrl = fragment;
  25147. }
  25148. else {
  25149. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25150. }
  25151. // Fragment shader
  25152. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25153. };
  25154. Effect.prototype._dumpShadersName = function () {
  25155. if (this.name.vertexElement) {
  25156. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25157. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25158. }
  25159. else if (this.name.vertex) {
  25160. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25161. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25162. }
  25163. else {
  25164. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25165. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25166. }
  25167. };
  25168. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25169. var _this = this;
  25170. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25171. var match = regex.exec(sourceCode);
  25172. var returnValue = new String(sourceCode);
  25173. while (match != null) {
  25174. var includeFile = match[1];
  25175. if (Effect.IncludesShadersStore[includeFile]) {
  25176. // Substitution
  25177. var includeContent = Effect.IncludesShadersStore[includeFile];
  25178. if (match[2]) {
  25179. var splits = match[3].split(",");
  25180. for (var index = 0; index < splits.length; index += 2) {
  25181. var source = new RegExp(splits[index], "g");
  25182. var dest = splits[index + 1];
  25183. includeContent = includeContent.replace(source, dest);
  25184. }
  25185. }
  25186. if (match[4]) {
  25187. var indexString = match[5];
  25188. if (indexString.indexOf("..") !== -1) {
  25189. var indexSplits = indexString.split("..");
  25190. var minIndex = parseInt(indexSplits[0]);
  25191. var maxIndex = parseInt(indexSplits[1]);
  25192. var sourceIncludeContent = includeContent.slice(0);
  25193. includeContent = "";
  25194. if (isNaN(maxIndex)) {
  25195. maxIndex = this._indexParameters[indexSplits[1]];
  25196. }
  25197. for (var i = minIndex; i <= maxIndex; i++) {
  25198. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  25199. }
  25200. }
  25201. else {
  25202. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25203. }
  25204. }
  25205. // Replace
  25206. returnValue = returnValue.replace(match[0], includeContent);
  25207. }
  25208. else {
  25209. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25210. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25211. Effect.IncludesShadersStore[includeFile] = fileContent;
  25212. _this._processIncludes(returnValue, callback);
  25213. });
  25214. return;
  25215. }
  25216. match = regex.exec(sourceCode);
  25217. }
  25218. callback(returnValue);
  25219. };
  25220. Effect.prototype._processPrecision = function (source) {
  25221. if (source.indexOf("precision highp float") === -1) {
  25222. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25223. source = "precision mediump float;\n" + source;
  25224. }
  25225. else {
  25226. source = "precision highp float;\n" + source;
  25227. }
  25228. }
  25229. else {
  25230. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25231. source = source.replace("precision highp float", "precision mediump float");
  25232. }
  25233. }
  25234. return source;
  25235. };
  25236. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  25237. try {
  25238. var engine = this._engine;
  25239. // Precision
  25240. vertexSourceCode = this._processPrecision(vertexSourceCode);
  25241. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  25242. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  25243. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25244. this._attributes = engine.getAttributes(this._program, attributesNames);
  25245. var index;
  25246. for (index = 0; index < this._samplers.length; index++) {
  25247. var sampler = this.getUniform(this._samplers[index]);
  25248. if (sampler == null) {
  25249. this._samplers.splice(index, 1);
  25250. index--;
  25251. }
  25252. }
  25253. engine.bindSamplers(this);
  25254. this._compilationError = "";
  25255. this._isReady = true;
  25256. if (this.onCompiled) {
  25257. this.onCompiled(this);
  25258. }
  25259. }
  25260. catch (e) {
  25261. this._compilationError = e.message;
  25262. // Let's go through fallbacks then
  25263. BABYLON.Tools.Error("Unable to compile effect: ");
  25264. BABYLON.Tools.Error("Defines: " + defines);
  25265. BABYLON.Tools.Error("Error: " + this._compilationError);
  25266. this._dumpShadersName();
  25267. if (fallbacks && fallbacks.isMoreFallbacks) {
  25268. BABYLON.Tools.Error("Trying next fallback.");
  25269. defines = fallbacks.reduce(defines);
  25270. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25271. }
  25272. else {
  25273. if (this.onError) {
  25274. this.onError(this, this._compilationError);
  25275. }
  25276. }
  25277. }
  25278. };
  25279. Object.defineProperty(Effect.prototype, "isSupported", {
  25280. get: function () {
  25281. return this._compilationError === "";
  25282. },
  25283. enumerable: true,
  25284. configurable: true
  25285. });
  25286. Effect.prototype._bindTexture = function (channel, texture) {
  25287. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25288. };
  25289. Effect.prototype.setTexture = function (channel, texture) {
  25290. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25291. };
  25292. Effect.prototype.setTextureArray = function (channel, textures) {
  25293. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25294. var initialPos = this._samplers.indexOf(channel);
  25295. for (var index = 1; index < textures.length; index++) {
  25296. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25297. }
  25298. }
  25299. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25300. };
  25301. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25302. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25303. };
  25304. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25305. var changed = false;
  25306. var cache = this._valueCache[uniformName];
  25307. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25308. changed = true;
  25309. cache = new BABYLON.Matrix();
  25310. }
  25311. var tm = cache.m;
  25312. var om = matrix.m;
  25313. for (var index = 0; index < 16; index++) {
  25314. if (tm[index] !== om[index]) {
  25315. tm[index] = om[index];
  25316. changed = true;
  25317. }
  25318. }
  25319. this._valueCache[uniformName] = cache;
  25320. return changed;
  25321. };
  25322. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25323. var cache = this._valueCache[uniformName];
  25324. if (!cache) {
  25325. cache = [x, y];
  25326. this._valueCache[uniformName] = cache;
  25327. return true;
  25328. }
  25329. var changed = false;
  25330. if (cache[0] !== x) {
  25331. cache[0] = x;
  25332. changed = true;
  25333. }
  25334. if (cache[1] !== y) {
  25335. cache[1] = y;
  25336. changed = true;
  25337. }
  25338. return changed;
  25339. };
  25340. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25341. var cache = this._valueCache[uniformName];
  25342. if (!cache) {
  25343. cache = [x, y, z];
  25344. this._valueCache[uniformName] = cache;
  25345. return true;
  25346. }
  25347. var changed = false;
  25348. if (cache[0] !== x) {
  25349. cache[0] = x;
  25350. changed = true;
  25351. }
  25352. if (cache[1] !== y) {
  25353. cache[1] = y;
  25354. changed = true;
  25355. }
  25356. if (cache[2] !== z) {
  25357. cache[2] = z;
  25358. changed = true;
  25359. }
  25360. return changed;
  25361. };
  25362. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25363. var cache = this._valueCache[uniformName];
  25364. if (!cache) {
  25365. cache = [x, y, z, w];
  25366. this._valueCache[uniformName] = cache;
  25367. return true;
  25368. }
  25369. var changed = false;
  25370. if (cache[0] !== x) {
  25371. cache[0] = x;
  25372. changed = true;
  25373. }
  25374. if (cache[1] !== y) {
  25375. cache[1] = y;
  25376. changed = true;
  25377. }
  25378. if (cache[2] !== z) {
  25379. cache[2] = z;
  25380. changed = true;
  25381. }
  25382. if (cache[3] !== w) {
  25383. cache[3] = w;
  25384. changed = true;
  25385. }
  25386. return changed;
  25387. };
  25388. Effect.prototype.setIntArray = function (uniformName, array) {
  25389. this._valueCache[uniformName] = null;
  25390. this._engine.setIntArray(this.getUniform(uniformName), array);
  25391. return this;
  25392. };
  25393. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25394. this._valueCache[uniformName] = null;
  25395. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25396. return this;
  25397. };
  25398. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25399. this._valueCache[uniformName] = null;
  25400. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25401. return this;
  25402. };
  25403. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25404. this._valueCache[uniformName] = null;
  25405. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25406. return this;
  25407. };
  25408. Effect.prototype.setFloatArray = function (uniformName, array) {
  25409. this._valueCache[uniformName] = null;
  25410. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25411. return this;
  25412. };
  25413. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25414. this._valueCache[uniformName] = null;
  25415. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25416. return this;
  25417. };
  25418. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25419. this._valueCache[uniformName] = null;
  25420. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25421. return this;
  25422. };
  25423. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25424. this._valueCache[uniformName] = null;
  25425. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25426. return this;
  25427. };
  25428. Effect.prototype.setArray = function (uniformName, array) {
  25429. this._valueCache[uniformName] = null;
  25430. this._engine.setArray(this.getUniform(uniformName), array);
  25431. return this;
  25432. };
  25433. Effect.prototype.setArray2 = function (uniformName, array) {
  25434. this._valueCache[uniformName] = null;
  25435. this._engine.setArray2(this.getUniform(uniformName), array);
  25436. return this;
  25437. };
  25438. Effect.prototype.setArray3 = function (uniformName, array) {
  25439. this._valueCache[uniformName] = null;
  25440. this._engine.setArray3(this.getUniform(uniformName), array);
  25441. return this;
  25442. };
  25443. Effect.prototype.setArray4 = function (uniformName, array) {
  25444. this._valueCache[uniformName] = null;
  25445. this._engine.setArray4(this.getUniform(uniformName), array);
  25446. return this;
  25447. };
  25448. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25449. this._valueCache[uniformName] = null;
  25450. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25451. return this;
  25452. };
  25453. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25454. if (this._cacheMatrix(uniformName, matrix)) {
  25455. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25456. }
  25457. return this;
  25458. };
  25459. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25460. this._valueCache[uniformName] = null;
  25461. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25462. return this;
  25463. };
  25464. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25465. this._valueCache[uniformName] = null;
  25466. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25467. return this;
  25468. };
  25469. Effect.prototype.setFloat = function (uniformName, value) {
  25470. var cache = this._valueCache[uniformName];
  25471. if (cache !== undefined && cache === value)
  25472. return this;
  25473. this._valueCache[uniformName] = value;
  25474. this._engine.setFloat(this.getUniform(uniformName), value);
  25475. return this;
  25476. };
  25477. Effect.prototype.setBool = function (uniformName, bool) {
  25478. var cache = this._valueCache[uniformName];
  25479. if (cache !== undefined && cache === bool)
  25480. return this;
  25481. this._valueCache[uniformName] = bool;
  25482. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25483. return this;
  25484. };
  25485. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25486. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25487. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25488. }
  25489. return this;
  25490. };
  25491. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25492. if (this._cacheFloat2(uniformName, x, y)) {
  25493. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25494. }
  25495. return this;
  25496. };
  25497. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25498. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25499. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25500. }
  25501. return this;
  25502. };
  25503. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25504. if (this._cacheFloat3(uniformName, x, y, z)) {
  25505. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25506. }
  25507. return this;
  25508. };
  25509. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25510. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25511. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25512. }
  25513. return this;
  25514. };
  25515. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25516. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25517. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25518. }
  25519. return this;
  25520. };
  25521. Effect.prototype.setColor3 = function (uniformName, color3) {
  25522. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25523. this._engine.setColor3(this.getUniform(uniformName), color3);
  25524. }
  25525. return this;
  25526. };
  25527. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25528. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25529. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25530. }
  25531. return this;
  25532. };
  25533. Effect.prototype._recombineShader = function (node) {
  25534. if (node.define) {
  25535. if (node.condition) {
  25536. var defineIndex = this.defines.indexOf("#define " + node.define);
  25537. if (defineIndex === -1) {
  25538. return null;
  25539. }
  25540. var nextComma = this.defines.indexOf("\n", defineIndex);
  25541. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  25542. var condition = defineValue + node.condition;
  25543. if (!eval(condition)) {
  25544. return null;
  25545. }
  25546. }
  25547. else if (node.ndef) {
  25548. if (this.defines.indexOf("#define " + node.define) !== -1) {
  25549. return null;
  25550. }
  25551. }
  25552. else if (this.defines.indexOf("#define " + node.define) === -1) {
  25553. return null;
  25554. }
  25555. }
  25556. var result = "";
  25557. for (var index = 0; index < node.children.length; index++) {
  25558. var line = node.children[index];
  25559. if (line.children) {
  25560. var combined = this._recombineShader(line);
  25561. if (combined !== null) {
  25562. result += combined + "\r\n";
  25563. }
  25564. continue;
  25565. }
  25566. if (line.length > 0) {
  25567. result += line + "\r\n";
  25568. }
  25569. }
  25570. return result;
  25571. };
  25572. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  25573. var root = {
  25574. children: []
  25575. };
  25576. var currentNode = root;
  25577. var lines = shaderString.split("\n");
  25578. for (var index = 0; index < lines.length; index++) {
  25579. var line = lines[index].trim();
  25580. // #ifdef
  25581. var pos = line.indexOf("#ifdef ");
  25582. if (pos !== -1) {
  25583. var define = line.substr(pos + 7);
  25584. var newNode = {
  25585. condition: null,
  25586. ndef: false,
  25587. define: define,
  25588. children: [],
  25589. parent: currentNode
  25590. };
  25591. currentNode.children.push(newNode);
  25592. currentNode = newNode;
  25593. continue;
  25594. }
  25595. // #ifndef
  25596. var pos = line.indexOf("#ifndef ");
  25597. if (pos !== -1) {
  25598. var define = line.substr(pos + 8);
  25599. newNode = {
  25600. condition: null,
  25601. define: define,
  25602. ndef: true,
  25603. children: [],
  25604. parent: currentNode
  25605. };
  25606. currentNode.children.push(newNode);
  25607. currentNode = newNode;
  25608. continue;
  25609. }
  25610. // #if
  25611. var pos = line.indexOf("#if ");
  25612. if (pos !== -1) {
  25613. var define = line.substr(pos + 4).trim();
  25614. var conditionPos = define.indexOf(" ");
  25615. newNode = {
  25616. condition: define.substr(conditionPos + 1),
  25617. define: define.substr(0, conditionPos),
  25618. ndef: false,
  25619. children: [],
  25620. parent: currentNode
  25621. };
  25622. currentNode.children.push(newNode);
  25623. currentNode = newNode;
  25624. continue;
  25625. }
  25626. // #endif
  25627. pos = line.indexOf("#endif");
  25628. if (pos !== -1) {
  25629. currentNode = currentNode.parent;
  25630. continue;
  25631. }
  25632. currentNode.children.push(line);
  25633. }
  25634. // Recombine
  25635. return this._recombineShader(root);
  25636. };
  25637. return Effect;
  25638. }());
  25639. // Statics
  25640. Effect.ShadersStore = {};
  25641. Effect.IncludesShadersStore = {};
  25642. BABYLON.Effect = Effect;
  25643. })(BABYLON || (BABYLON = {}));
  25644. //# sourceMappingURL=babylon.effect.js.map
  25645. var BABYLON;
  25646. (function (BABYLON) {
  25647. var MaterialHelper = (function () {
  25648. function MaterialHelper() {
  25649. }
  25650. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25651. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25652. var lightIndex = 0;
  25653. var needNormals = false;
  25654. var needRebuild = false;
  25655. var needShadows = false;
  25656. var lightmapMode = false;
  25657. for (var index = 0; index < scene.lights.length; index++) {
  25658. var light = scene.lights[index];
  25659. if (!light.isEnabled()) {
  25660. continue;
  25661. }
  25662. // Excluded check
  25663. if (light._excludedMeshesIds.length > 0) {
  25664. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25665. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25666. if (excludedMesh) {
  25667. light.excludedMeshes.push(excludedMesh);
  25668. }
  25669. }
  25670. light._excludedMeshesIds = [];
  25671. }
  25672. // Included check
  25673. if (light._includedOnlyMeshesIds.length > 0) {
  25674. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25675. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25676. if (includedOnlyMesh) {
  25677. light.includedOnlyMeshes.push(includedOnlyMesh);
  25678. }
  25679. }
  25680. light._includedOnlyMeshesIds = [];
  25681. }
  25682. if (!light.canAffectMesh(mesh)) {
  25683. continue;
  25684. }
  25685. needNormals = true;
  25686. if (defines["LIGHT" + lightIndex] === undefined) {
  25687. needRebuild = true;
  25688. }
  25689. defines["LIGHT" + lightIndex] = true;
  25690. var type;
  25691. if (light instanceof BABYLON.SpotLight) {
  25692. type = "SPOTLIGHT" + lightIndex;
  25693. }
  25694. else if (light instanceof BABYLON.HemisphericLight) {
  25695. type = "HEMILIGHT" + lightIndex;
  25696. }
  25697. else if (light instanceof BABYLON.PointLight) {
  25698. type = "POINTLIGHT" + lightIndex;
  25699. }
  25700. else {
  25701. type = "DIRLIGHT" + lightIndex;
  25702. }
  25703. if (defines[type] === undefined) {
  25704. needRebuild = true;
  25705. }
  25706. defines[type] = true;
  25707. // Specular
  25708. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25709. defines["SPECULARTERM"] = true;
  25710. }
  25711. // Shadows
  25712. if (scene.shadowsEnabled) {
  25713. var shadowGenerator = light.getShadowGenerator();
  25714. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25715. if (defines["SHADOW" + lightIndex] === undefined) {
  25716. needRebuild = true;
  25717. }
  25718. defines["SHADOW" + lightIndex] = true;
  25719. defines["SHADOWS"] = true;
  25720. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25721. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25722. needRebuild = true;
  25723. }
  25724. defines["SHADOWVSM" + lightIndex] = true;
  25725. }
  25726. if (shadowGenerator.usePoissonSampling) {
  25727. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25728. needRebuild = true;
  25729. }
  25730. defines["SHADOWPCF" + lightIndex] = true;
  25731. }
  25732. needShadows = true;
  25733. }
  25734. }
  25735. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25736. lightmapMode = true;
  25737. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25738. needRebuild = true;
  25739. }
  25740. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25741. needRebuild = true;
  25742. }
  25743. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25744. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25745. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25746. }
  25747. }
  25748. lightIndex++;
  25749. if (lightIndex === maxSimultaneousLights)
  25750. break;
  25751. }
  25752. var caps = scene.getEngine().getCaps();
  25753. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25754. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25755. needRebuild = true;
  25756. }
  25757. defines["SHADOWFULLFLOAT"] = true;
  25758. }
  25759. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25760. needRebuild = true;
  25761. }
  25762. if (lightmapMode) {
  25763. defines["LIGHTMAPEXCLUDED"] = true;
  25764. }
  25765. if (needRebuild) {
  25766. defines.rebuild();
  25767. }
  25768. return needNormals;
  25769. };
  25770. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25771. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25772. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25773. if (!defines["LIGHT" + lightIndex]) {
  25774. break;
  25775. }
  25776. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25777. samplersList.push("shadowSampler" + lightIndex);
  25778. }
  25779. };
  25780. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25781. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25782. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25783. if (!defines["LIGHT" + lightIndex]) {
  25784. break;
  25785. }
  25786. if (lightIndex > 0) {
  25787. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25788. }
  25789. if (defines["SHADOW" + lightIndex]) {
  25790. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25791. }
  25792. if (defines["SHADOWPCF" + lightIndex]) {
  25793. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25794. }
  25795. if (defines["SHADOWVSM" + lightIndex]) {
  25796. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25797. }
  25798. }
  25799. };
  25800. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25801. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25802. fallbacks.addCPUSkinningFallback(0, mesh);
  25803. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25804. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25805. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25806. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25807. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25808. }
  25809. }
  25810. };
  25811. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25812. if (defines["INSTANCES"]) {
  25813. attribs.push("world0");
  25814. attribs.push("world1");
  25815. attribs.push("world2");
  25816. attribs.push("world3");
  25817. }
  25818. };
  25819. // Bindings
  25820. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25821. var shadowGenerator = light.getShadowGenerator();
  25822. if (mesh.receiveShadows && shadowGenerator) {
  25823. if (!light.needCube()) {
  25824. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25825. }
  25826. else {
  25827. if (!depthValuesAlreadySet) {
  25828. depthValuesAlreadySet = true;
  25829. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25830. }
  25831. }
  25832. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25833. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25834. }
  25835. return depthValuesAlreadySet;
  25836. };
  25837. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25838. if (light instanceof BABYLON.PointLight) {
  25839. // Point Light
  25840. light.transferToEffect(effect, "vLightData" + lightIndex);
  25841. }
  25842. else if (light instanceof BABYLON.DirectionalLight) {
  25843. // Directional Light
  25844. light.transferToEffect(effect, "vLightData" + lightIndex);
  25845. }
  25846. else if (light instanceof BABYLON.SpotLight) {
  25847. // Spot Light
  25848. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25849. }
  25850. else if (light instanceof BABYLON.HemisphericLight) {
  25851. // Hemispheric Light
  25852. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25853. }
  25854. };
  25855. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25856. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25857. var lightIndex = 0;
  25858. var depthValuesAlreadySet = false;
  25859. for (var index = 0; index < scene.lights.length; index++) {
  25860. var light = scene.lights[index];
  25861. if (!light.isEnabled()) {
  25862. continue;
  25863. }
  25864. if (!light.canAffectMesh(mesh)) {
  25865. continue;
  25866. }
  25867. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25868. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25869. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25870. if (defines["SPECULARTERM"]) {
  25871. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25872. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25873. }
  25874. // Shadows
  25875. if (scene.shadowsEnabled) {
  25876. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25877. }
  25878. lightIndex++;
  25879. if (lightIndex === maxSimultaneousLights)
  25880. break;
  25881. }
  25882. };
  25883. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25884. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25885. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25886. effect.setColor3("vFogColor", scene.fogColor);
  25887. }
  25888. };
  25889. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25890. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25891. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25892. if (matrices) {
  25893. effect.setMatrices("mBones", matrices);
  25894. }
  25895. }
  25896. };
  25897. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25898. if (defines["LOGARITHMICDEPTH"]) {
  25899. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25900. }
  25901. };
  25902. MaterialHelper.BindClipPlane = function (effect, scene) {
  25903. if (scene.clipPlane) {
  25904. var clipPlane = scene.clipPlane;
  25905. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25906. }
  25907. };
  25908. return MaterialHelper;
  25909. }());
  25910. BABYLON.MaterialHelper = MaterialHelper;
  25911. })(BABYLON || (BABYLON = {}));
  25912. //# sourceMappingURL=babylon.materialHelper.js.map
  25913. var BABYLON;
  25914. (function (BABYLON) {
  25915. var FresnelParameters = (function () {
  25916. function FresnelParameters() {
  25917. this.isEnabled = true;
  25918. this.leftColor = BABYLON.Color3.White();
  25919. this.rightColor = BABYLON.Color3.Black();
  25920. this.bias = 0;
  25921. this.power = 1;
  25922. }
  25923. FresnelParameters.prototype.clone = function () {
  25924. var newFresnelParameters = new FresnelParameters();
  25925. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25926. return newFresnelParameters;
  25927. };
  25928. FresnelParameters.prototype.serialize = function () {
  25929. var serializationObject = {};
  25930. serializationObject.isEnabled = this.isEnabled;
  25931. serializationObject.leftColor = this.leftColor;
  25932. serializationObject.rightColor = this.rightColor;
  25933. serializationObject.bias = this.bias;
  25934. serializationObject.power = this.power;
  25935. return serializationObject;
  25936. };
  25937. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25938. var fresnelParameters = new FresnelParameters();
  25939. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25940. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25941. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25942. fresnelParameters.bias = parsedFresnelParameters.bias;
  25943. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25944. return fresnelParameters;
  25945. };
  25946. return FresnelParameters;
  25947. }());
  25948. BABYLON.FresnelParameters = FresnelParameters;
  25949. })(BABYLON || (BABYLON = {}));
  25950. //# sourceMappingURL=babylon.fresnelParameters.js.map
  25951. var BABYLON;
  25952. (function (BABYLON) {
  25953. var MaterialDefines = (function () {
  25954. function MaterialDefines() {
  25955. }
  25956. MaterialDefines.prototype.rebuild = function () {
  25957. if (this._keys) {
  25958. delete this._keys;
  25959. }
  25960. this._keys = Object.keys(this);
  25961. };
  25962. MaterialDefines.prototype.isEqual = function (other) {
  25963. if (this._keys.length !== other._keys.length) {
  25964. return false;
  25965. }
  25966. for (var index = 0; index < this._keys.length; index++) {
  25967. var prop = this._keys[index];
  25968. if (this[prop] !== other[prop]) {
  25969. return false;
  25970. }
  25971. }
  25972. return true;
  25973. };
  25974. MaterialDefines.prototype.cloneTo = function (other) {
  25975. if (this._keys.length !== other._keys.length) {
  25976. other._keys = this._keys.slice(0);
  25977. }
  25978. for (var index = 0; index < this._keys.length; index++) {
  25979. var prop = this._keys[index];
  25980. other[prop] = this[prop];
  25981. }
  25982. };
  25983. MaterialDefines.prototype.reset = function () {
  25984. for (var index = 0; index < this._keys.length; index++) {
  25985. var prop = this._keys[index];
  25986. if (typeof (this[prop]) === "number") {
  25987. this[prop] = 0;
  25988. }
  25989. else {
  25990. this[prop] = false;
  25991. }
  25992. }
  25993. };
  25994. MaterialDefines.prototype.toString = function () {
  25995. var result = "";
  25996. for (var index = 0; index < this._keys.length; index++) {
  25997. var prop = this._keys[index];
  25998. if (typeof (this[prop]) === "number") {
  25999. result += "#define " + prop + " " + this[prop] + "\n";
  26000. }
  26001. else if (this[prop]) {
  26002. result += "#define " + prop + "\n";
  26003. }
  26004. }
  26005. return result;
  26006. };
  26007. return MaterialDefines;
  26008. }());
  26009. BABYLON.MaterialDefines = MaterialDefines;
  26010. var Material = (function () {
  26011. function Material(name, scene, doNotAdd) {
  26012. this.checkReadyOnEveryCall = false;
  26013. this.checkReadyOnlyOnce = false;
  26014. this.state = "";
  26015. this.alpha = 1.0;
  26016. this.backFaceCulling = true;
  26017. this.doNotSerialize = false;
  26018. /**
  26019. * An event triggered when the material is disposed.
  26020. * @type {BABYLON.Observable}
  26021. */
  26022. this.onDisposeObservable = new BABYLON.Observable();
  26023. /**
  26024. * An event triggered when the material is bound.
  26025. * @type {BABYLON.Observable}
  26026. */
  26027. this.onBindObservable = new BABYLON.Observable();
  26028. /**
  26029. * An event triggered when the material is unbound.
  26030. * @type {BABYLON.Observable}
  26031. */
  26032. this.onUnBindObservable = new BABYLON.Observable();
  26033. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26034. this.disableDepthWrite = false;
  26035. this.fogEnabled = true;
  26036. this.pointSize = 1.0;
  26037. this.zOffset = 0;
  26038. this._wasPreviouslyReady = false;
  26039. this._fillMode = Material.TriangleFillMode;
  26040. this.name = name;
  26041. this.id = name;
  26042. this._scene = scene;
  26043. if (scene.useRightHandedSystem) {
  26044. this.sideOrientation = Material.ClockWiseSideOrientation;
  26045. }
  26046. else {
  26047. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26048. }
  26049. if (!doNotAdd) {
  26050. scene.materials.push(this);
  26051. }
  26052. }
  26053. Object.defineProperty(Material, "TriangleFillMode", {
  26054. get: function () {
  26055. return Material._TriangleFillMode;
  26056. },
  26057. enumerable: true,
  26058. configurable: true
  26059. });
  26060. Object.defineProperty(Material, "WireFrameFillMode", {
  26061. get: function () {
  26062. return Material._WireFrameFillMode;
  26063. },
  26064. enumerable: true,
  26065. configurable: true
  26066. });
  26067. Object.defineProperty(Material, "PointFillMode", {
  26068. get: function () {
  26069. return Material._PointFillMode;
  26070. },
  26071. enumerable: true,
  26072. configurable: true
  26073. });
  26074. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26075. get: function () {
  26076. return Material._ClockWiseSideOrientation;
  26077. },
  26078. enumerable: true,
  26079. configurable: true
  26080. });
  26081. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26082. get: function () {
  26083. return Material._CounterClockWiseSideOrientation;
  26084. },
  26085. enumerable: true,
  26086. configurable: true
  26087. });
  26088. Object.defineProperty(Material.prototype, "onDispose", {
  26089. set: function (callback) {
  26090. if (this._onDisposeObserver) {
  26091. this.onDisposeObservable.remove(this._onDisposeObserver);
  26092. }
  26093. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26094. },
  26095. enumerable: true,
  26096. configurable: true
  26097. });
  26098. Object.defineProperty(Material.prototype, "onBind", {
  26099. set: function (callback) {
  26100. if (this._onBindObserver) {
  26101. this.onBindObservable.remove(this._onBindObserver);
  26102. }
  26103. this._onBindObserver = this.onBindObservable.add(callback);
  26104. },
  26105. enumerable: true,
  26106. configurable: true
  26107. });
  26108. Object.defineProperty(Material.prototype, "wireframe", {
  26109. get: function () {
  26110. return this._fillMode === Material.WireFrameFillMode;
  26111. },
  26112. set: function (value) {
  26113. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26114. },
  26115. enumerable: true,
  26116. configurable: true
  26117. });
  26118. Object.defineProperty(Material.prototype, "pointsCloud", {
  26119. get: function () {
  26120. return this._fillMode === Material.PointFillMode;
  26121. },
  26122. set: function (value) {
  26123. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26124. },
  26125. enumerable: true,
  26126. configurable: true
  26127. });
  26128. Object.defineProperty(Material.prototype, "fillMode", {
  26129. get: function () {
  26130. return this._fillMode;
  26131. },
  26132. set: function (value) {
  26133. this._fillMode = value;
  26134. },
  26135. enumerable: true,
  26136. configurable: true
  26137. });
  26138. /**
  26139. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26140. * subclasses should override adding information pertainent to themselves
  26141. */
  26142. Material.prototype.toString = function (fullDetails) {
  26143. var ret = "Name: " + this.name;
  26144. if (fullDetails) {
  26145. }
  26146. return ret;
  26147. };
  26148. Material.prototype.getClassName = function () {
  26149. return "Material";
  26150. };
  26151. Object.defineProperty(Material.prototype, "isFrozen", {
  26152. get: function () {
  26153. return this.checkReadyOnlyOnce;
  26154. },
  26155. enumerable: true,
  26156. configurable: true
  26157. });
  26158. Material.prototype.freeze = function () {
  26159. this.checkReadyOnlyOnce = true;
  26160. };
  26161. Material.prototype.unfreeze = function () {
  26162. this.checkReadyOnlyOnce = false;
  26163. };
  26164. Material.prototype.isReady = function (mesh, useInstances) {
  26165. return true;
  26166. };
  26167. Material.prototype.getEffect = function () {
  26168. return this._effect;
  26169. };
  26170. Material.prototype.getScene = function () {
  26171. return this._scene;
  26172. };
  26173. Material.prototype.needAlphaBlending = function () {
  26174. return (this.alpha < 1.0);
  26175. };
  26176. Material.prototype.needAlphaTesting = function () {
  26177. return false;
  26178. };
  26179. Material.prototype.getAlphaTestTexture = function () {
  26180. return null;
  26181. };
  26182. Material.prototype.markDirty = function () {
  26183. this._wasPreviouslyReady = false;
  26184. };
  26185. Material.prototype._preBind = function () {
  26186. var engine = this._scene.getEngine();
  26187. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26188. engine.enableEffect(this._effect);
  26189. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26190. };
  26191. Material.prototype.bind = function (world, mesh) {
  26192. this._scene._cachedMaterial = this;
  26193. this.onBindObservable.notifyObservers(mesh);
  26194. if (this.disableDepthWrite) {
  26195. var engine = this._scene.getEngine();
  26196. this._cachedDepthWriteState = engine.getDepthWrite();
  26197. engine.setDepthWrite(false);
  26198. }
  26199. };
  26200. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26201. };
  26202. Material.prototype.unbind = function () {
  26203. this.onUnBindObservable.notifyObservers(this);
  26204. if (this.disableDepthWrite) {
  26205. var engine = this._scene.getEngine();
  26206. engine.setDepthWrite(this._cachedDepthWriteState);
  26207. }
  26208. };
  26209. Material.prototype.clone = function (name) {
  26210. return null;
  26211. };
  26212. Material.prototype.getBindedMeshes = function () {
  26213. var result = new Array();
  26214. for (var index = 0; index < this._scene.meshes.length; index++) {
  26215. var mesh = this._scene.meshes[index];
  26216. if (mesh.material === this) {
  26217. result.push(mesh);
  26218. }
  26219. }
  26220. return result;
  26221. };
  26222. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26223. // Animations
  26224. this.getScene().stopAnimation(this);
  26225. // Remove from scene
  26226. var index = this._scene.materials.indexOf(this);
  26227. if (index >= 0) {
  26228. this._scene.materials.splice(index, 1);
  26229. }
  26230. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26231. if (forceDisposeEffect && this._effect) {
  26232. this._scene.getEngine()._releaseEffect(this._effect);
  26233. this._effect = null;
  26234. }
  26235. // Remove from meshes
  26236. for (index = 0; index < this._scene.meshes.length; index++) {
  26237. var mesh = this._scene.meshes[index];
  26238. if (mesh.material === this) {
  26239. mesh.material = null;
  26240. }
  26241. }
  26242. // Callback
  26243. this.onDisposeObservable.notifyObservers(this);
  26244. this.onDisposeObservable.clear();
  26245. this.onBindObservable.clear();
  26246. this.onUnBindObservable.clear();
  26247. };
  26248. Material.prototype.serialize = function () {
  26249. return BABYLON.SerializationHelper.Serialize(this);
  26250. };
  26251. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26252. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26253. multiMaterial.id = parsedMultiMaterial.id;
  26254. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26255. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26256. var subMatId = parsedMultiMaterial.materials[matIndex];
  26257. if (subMatId) {
  26258. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26259. }
  26260. else {
  26261. multiMaterial.subMaterials.push(null);
  26262. }
  26263. }
  26264. return multiMaterial;
  26265. };
  26266. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26267. if (!parsedMaterial.customType) {
  26268. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26269. }
  26270. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26271. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26272. ;
  26273. };
  26274. return Material;
  26275. }());
  26276. Material._TriangleFillMode = 0;
  26277. Material._WireFrameFillMode = 1;
  26278. Material._PointFillMode = 2;
  26279. Material._ClockWiseSideOrientation = 0;
  26280. Material._CounterClockWiseSideOrientation = 1;
  26281. __decorate([
  26282. BABYLON.serialize()
  26283. ], Material.prototype, "id", void 0);
  26284. __decorate([
  26285. BABYLON.serialize()
  26286. ], Material.prototype, "name", void 0);
  26287. __decorate([
  26288. BABYLON.serialize()
  26289. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26290. __decorate([
  26291. BABYLON.serialize()
  26292. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26293. __decorate([
  26294. BABYLON.serialize()
  26295. ], Material.prototype, "state", void 0);
  26296. __decorate([
  26297. BABYLON.serialize()
  26298. ], Material.prototype, "alpha", void 0);
  26299. __decorate([
  26300. BABYLON.serialize()
  26301. ], Material.prototype, "backFaceCulling", void 0);
  26302. __decorate([
  26303. BABYLON.serialize()
  26304. ], Material.prototype, "sideOrientation", void 0);
  26305. __decorate([
  26306. BABYLON.serialize()
  26307. ], Material.prototype, "alphaMode", void 0);
  26308. __decorate([
  26309. BABYLON.serialize()
  26310. ], Material.prototype, "disableDepthWrite", void 0);
  26311. __decorate([
  26312. BABYLON.serialize()
  26313. ], Material.prototype, "fogEnabled", void 0);
  26314. __decorate([
  26315. BABYLON.serialize()
  26316. ], Material.prototype, "pointSize", void 0);
  26317. __decorate([
  26318. BABYLON.serialize()
  26319. ], Material.prototype, "zOffset", void 0);
  26320. __decorate([
  26321. BABYLON.serialize()
  26322. ], Material.prototype, "wireframe", null);
  26323. __decorate([
  26324. BABYLON.serialize()
  26325. ], Material.prototype, "pointsCloud", null);
  26326. __decorate([
  26327. BABYLON.serialize()
  26328. ], Material.prototype, "fillMode", null);
  26329. BABYLON.Material = Material;
  26330. })(BABYLON || (BABYLON = {}));
  26331. //# sourceMappingURL=babylon.material.js.map
  26332. var BABYLON;
  26333. (function (BABYLON) {
  26334. var StandardMaterialDefines = (function (_super) {
  26335. __extends(StandardMaterialDefines, _super);
  26336. function StandardMaterialDefines() {
  26337. var _this = _super.call(this) || this;
  26338. _this.DIFFUSE = false;
  26339. _this.AMBIENT = false;
  26340. _this.OPACITY = false;
  26341. _this.OPACITYRGB = false;
  26342. _this.REFLECTION = false;
  26343. _this.EMISSIVE = false;
  26344. _this.SPECULAR = false;
  26345. _this.BUMP = false;
  26346. _this.PARALLAX = false;
  26347. _this.PARALLAXOCCLUSION = false;
  26348. _this.SPECULAROVERALPHA = false;
  26349. _this.CLIPPLANE = false;
  26350. _this.ALPHATEST = false;
  26351. _this.ALPHAFROMDIFFUSE = false;
  26352. _this.POINTSIZE = false;
  26353. _this.FOG = false;
  26354. _this.SPECULARTERM = false;
  26355. _this.DIFFUSEFRESNEL = false;
  26356. _this.OPACITYFRESNEL = false;
  26357. _this.REFLECTIONFRESNEL = false;
  26358. _this.REFRACTIONFRESNEL = false;
  26359. _this.EMISSIVEFRESNEL = false;
  26360. _this.FRESNEL = false;
  26361. _this.NORMAL = false;
  26362. _this.UV1 = false;
  26363. _this.UV2 = false;
  26364. _this.VERTEXCOLOR = false;
  26365. _this.VERTEXALPHA = false;
  26366. _this.NUM_BONE_INFLUENCERS = 0;
  26367. _this.BonesPerMesh = 0;
  26368. _this.INSTANCES = false;
  26369. _this.GLOSSINESS = false;
  26370. _this.ROUGHNESS = false;
  26371. _this.EMISSIVEASILLUMINATION = false;
  26372. _this.LINKEMISSIVEWITHDIFFUSE = false;
  26373. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  26374. _this.LIGHTMAP = false;
  26375. _this.USELIGHTMAPASSHADOWMAP = false;
  26376. _this.REFLECTIONMAP_3D = false;
  26377. _this.REFLECTIONMAP_SPHERICAL = false;
  26378. _this.REFLECTIONMAP_PLANAR = false;
  26379. _this.REFLECTIONMAP_CUBIC = false;
  26380. _this.REFLECTIONMAP_PROJECTION = false;
  26381. _this.REFLECTIONMAP_SKYBOX = false;
  26382. _this.REFLECTIONMAP_EXPLICIT = false;
  26383. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26384. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26385. _this.INVERTCUBICMAP = false;
  26386. _this.LOGARITHMICDEPTH = false;
  26387. _this.REFRACTION = false;
  26388. _this.REFRACTIONMAP_3D = false;
  26389. _this.REFLECTIONOVERALPHA = false;
  26390. _this.INVERTNORMALMAPX = false;
  26391. _this.INVERTNORMALMAPY = false;
  26392. _this.SHADOWFULLFLOAT = false;
  26393. _this.CAMERACOLORGRADING = false;
  26394. _this.CAMERACOLORCURVES = false;
  26395. _this.rebuild();
  26396. return _this;
  26397. }
  26398. return StandardMaterialDefines;
  26399. }(BABYLON.MaterialDefines));
  26400. var StandardMaterial = (function (_super) {
  26401. __extends(StandardMaterial, _super);
  26402. function StandardMaterial(name, scene) {
  26403. var _this = _super.call(this, name, scene) || this;
  26404. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26405. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26406. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  26407. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26408. _this.specularPower = 64;
  26409. _this.useAlphaFromDiffuseTexture = false;
  26410. _this.useEmissiveAsIllumination = false;
  26411. _this.linkEmissiveWithDiffuse = false;
  26412. _this.useReflectionFresnelFromSpecular = false;
  26413. _this.useSpecularOverAlpha = false;
  26414. _this.useReflectionOverAlpha = false;
  26415. _this.disableLighting = false;
  26416. _this.useParallax = false;
  26417. _this.useParallaxOcclusion = false;
  26418. _this.parallaxScaleBias = 0.05;
  26419. _this.roughness = 0;
  26420. _this.indexOfRefraction = 0.98;
  26421. _this.invertRefractionY = true;
  26422. _this.useLightmapAsShadowmap = false;
  26423. _this.useGlossinessFromSpecularMapAlpha = false;
  26424. _this.maxSimultaneousLights = 4;
  26425. /**
  26426. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26427. */
  26428. _this.invertNormalMapX = false;
  26429. /**
  26430. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26431. */
  26432. _this.invertNormalMapY = false;
  26433. /**
  26434. * Color Grading 2D Lookup Texture.
  26435. * This allows special effects like sepia, black and white to sixties rendering style.
  26436. */
  26437. _this.cameraColorGradingTexture = null;
  26438. /**
  26439. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26440. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26441. * 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;
  26442. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26443. */
  26444. _this.cameraColorCurves = null;
  26445. _this._renderTargets = new BABYLON.SmartArray(16);
  26446. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26447. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26448. _this._defines = new StandardMaterialDefines();
  26449. _this._cachedDefines = new StandardMaterialDefines();
  26450. _this._cachedDefines.BonesPerMesh = -1;
  26451. _this.getRenderTargetTextures = function () {
  26452. _this._renderTargets.reset();
  26453. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  26454. _this._renderTargets.push(_this.reflectionTexture);
  26455. }
  26456. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  26457. _this._renderTargets.push(_this.refractionTexture);
  26458. }
  26459. return _this._renderTargets;
  26460. };
  26461. return _this;
  26462. }
  26463. StandardMaterial.prototype.getClassName = function () {
  26464. return "StandardMaterial";
  26465. };
  26466. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26467. get: function () {
  26468. return this._useLogarithmicDepth;
  26469. },
  26470. set: function (value) {
  26471. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26472. },
  26473. enumerable: true,
  26474. configurable: true
  26475. });
  26476. StandardMaterial.prototype.needAlphaBlending = function () {
  26477. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  26478. };
  26479. StandardMaterial.prototype.needAlphaTesting = function () {
  26480. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  26481. };
  26482. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26483. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  26484. };
  26485. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26486. return this.diffuseTexture;
  26487. };
  26488. // Methods
  26489. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  26490. if (!mesh) {
  26491. return true;
  26492. }
  26493. if (this._defines.INSTANCES !== useInstances) {
  26494. return false;
  26495. }
  26496. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  26497. return true;
  26498. }
  26499. return false;
  26500. };
  26501. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  26502. if (this.isFrozen) {
  26503. if (this._wasPreviouslyReady) {
  26504. return true;
  26505. }
  26506. }
  26507. var scene = this.getScene();
  26508. var engine = scene.getEngine();
  26509. var needUVs = false;
  26510. var needNormals = false;
  26511. this._defines.reset();
  26512. // Lights
  26513. if (scene.lightsEnabled && !this.disableLighting) {
  26514. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26515. }
  26516. if (!this.checkReadyOnEveryCall) {
  26517. if (this._renderId === scene.getRenderId()) {
  26518. if (this._checkCache(scene, mesh, useInstances)) {
  26519. return true;
  26520. }
  26521. }
  26522. }
  26523. // Textures
  26524. if (scene.texturesEnabled) {
  26525. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26526. if (!this.diffuseTexture.isReady()) {
  26527. return false;
  26528. }
  26529. else {
  26530. needUVs = true;
  26531. this._defines.DIFFUSE = true;
  26532. }
  26533. }
  26534. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26535. if (!this.ambientTexture.isReady()) {
  26536. return false;
  26537. }
  26538. else {
  26539. needUVs = true;
  26540. this._defines.AMBIENT = true;
  26541. }
  26542. }
  26543. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26544. if (!this.opacityTexture.isReady()) {
  26545. return false;
  26546. }
  26547. else {
  26548. needUVs = true;
  26549. this._defines.OPACITY = true;
  26550. if (this.opacityTexture.getAlphaFromRGB) {
  26551. this._defines.OPACITYRGB = true;
  26552. }
  26553. }
  26554. }
  26555. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26556. if (!this.reflectionTexture.isReady()) {
  26557. return false;
  26558. }
  26559. else {
  26560. needNormals = true;
  26561. this._defines.REFLECTION = true;
  26562. if (this.roughness > 0) {
  26563. this._defines.ROUGHNESS = true;
  26564. }
  26565. if (this.useReflectionOverAlpha) {
  26566. this._defines.REFLECTIONOVERALPHA = true;
  26567. }
  26568. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  26569. this._defines.INVERTCUBICMAP = true;
  26570. }
  26571. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  26572. switch (this.reflectionTexture.coordinatesMode) {
  26573. case BABYLON.Texture.CUBIC_MODE:
  26574. case BABYLON.Texture.INVCUBIC_MODE:
  26575. this._defines.REFLECTIONMAP_CUBIC = true;
  26576. break;
  26577. case BABYLON.Texture.EXPLICIT_MODE:
  26578. this._defines.REFLECTIONMAP_EXPLICIT = true;
  26579. break;
  26580. case BABYLON.Texture.PLANAR_MODE:
  26581. this._defines.REFLECTIONMAP_PLANAR = true;
  26582. break;
  26583. case BABYLON.Texture.PROJECTION_MODE:
  26584. this._defines.REFLECTIONMAP_PROJECTION = true;
  26585. break;
  26586. case BABYLON.Texture.SKYBOX_MODE:
  26587. this._defines.REFLECTIONMAP_SKYBOX = true;
  26588. break;
  26589. case BABYLON.Texture.SPHERICAL_MODE:
  26590. this._defines.REFLECTIONMAP_SPHERICAL = true;
  26591. break;
  26592. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26593. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  26594. break;
  26595. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26596. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  26597. break;
  26598. }
  26599. }
  26600. }
  26601. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26602. if (!this.emissiveTexture.isReady()) {
  26603. return false;
  26604. }
  26605. else {
  26606. needUVs = true;
  26607. this._defines.EMISSIVE = true;
  26608. }
  26609. }
  26610. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26611. if (!this.lightmapTexture.isReady()) {
  26612. return false;
  26613. }
  26614. else {
  26615. needUVs = true;
  26616. this._defines.LIGHTMAP = true;
  26617. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  26618. }
  26619. }
  26620. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26621. if (!this.specularTexture.isReady()) {
  26622. return false;
  26623. }
  26624. else {
  26625. needUVs = true;
  26626. this._defines.SPECULAR = true;
  26627. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  26628. }
  26629. }
  26630. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26631. if (!this.bumpTexture.isReady()) {
  26632. return false;
  26633. }
  26634. else {
  26635. needUVs = true;
  26636. this._defines.BUMP = true;
  26637. if (this.useParallax) {
  26638. this._defines.PARALLAX = true;
  26639. if (this.useParallaxOcclusion) {
  26640. this._defines.PARALLAXOCCLUSION = true;
  26641. }
  26642. }
  26643. if (this.invertNormalMapX) {
  26644. this._defines.INVERTNORMALMAPX = true;
  26645. }
  26646. if (this.invertNormalMapY) {
  26647. this._defines.INVERTNORMALMAPY = true;
  26648. }
  26649. }
  26650. }
  26651. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26652. if (!this.refractionTexture.isReady()) {
  26653. return false;
  26654. }
  26655. else {
  26656. needUVs = true;
  26657. this._defines.REFRACTION = true;
  26658. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26659. }
  26660. }
  26661. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26662. if (!this.cameraColorGradingTexture.isReady()) {
  26663. return false;
  26664. }
  26665. else {
  26666. this._defines.CAMERACOLORGRADING = true;
  26667. }
  26668. }
  26669. }
  26670. // Effect
  26671. if (scene.clipPlane) {
  26672. this._defines.CLIPPLANE = true;
  26673. }
  26674. if (engine.getAlphaTesting()) {
  26675. this._defines.ALPHATEST = true;
  26676. }
  26677. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26678. this._defines.ALPHAFROMDIFFUSE = true;
  26679. }
  26680. if (this.useEmissiveAsIllumination) {
  26681. this._defines.EMISSIVEASILLUMINATION = true;
  26682. }
  26683. if (this.linkEmissiveWithDiffuse) {
  26684. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26685. }
  26686. if (this.useLogarithmicDepth) {
  26687. this._defines.LOGARITHMICDEPTH = true;
  26688. }
  26689. if (this.cameraColorCurves) {
  26690. this._defines.CAMERACOLORCURVES = true;
  26691. }
  26692. // Point size
  26693. if (this.pointsCloud || scene.forcePointsCloud) {
  26694. this._defines.POINTSIZE = true;
  26695. }
  26696. // Fog
  26697. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26698. this._defines.FOG = true;
  26699. }
  26700. if (StandardMaterial.FresnelEnabled) {
  26701. // Fresnel
  26702. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26703. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26704. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26705. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26706. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26707. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26708. this._defines.DIFFUSEFRESNEL = true;
  26709. }
  26710. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26711. this._defines.OPACITYFRESNEL = true;
  26712. }
  26713. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26714. this._defines.REFLECTIONFRESNEL = true;
  26715. if (this.useReflectionFresnelFromSpecular) {
  26716. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26717. }
  26718. }
  26719. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26720. this._defines.REFRACTIONFRESNEL = true;
  26721. }
  26722. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26723. this._defines.EMISSIVEFRESNEL = true;
  26724. }
  26725. needNormals = true;
  26726. this._defines.FRESNEL = true;
  26727. }
  26728. }
  26729. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26730. this._defines.SPECULAROVERALPHA = true;
  26731. }
  26732. // Attribs
  26733. if (mesh) {
  26734. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26735. this._defines.NORMAL = true;
  26736. }
  26737. if (needUVs) {
  26738. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26739. this._defines.UV1 = true;
  26740. }
  26741. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26742. this._defines.UV2 = true;
  26743. }
  26744. }
  26745. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26746. this._defines.VERTEXCOLOR = true;
  26747. if (mesh.hasVertexAlpha) {
  26748. this._defines.VERTEXALPHA = true;
  26749. }
  26750. }
  26751. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26752. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26753. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26754. }
  26755. // Instances
  26756. if (useInstances) {
  26757. this._defines.INSTANCES = true;
  26758. }
  26759. }
  26760. // Get correct effect
  26761. if (!this._defines.isEqual(this._cachedDefines)) {
  26762. this._defines.cloneTo(this._cachedDefines);
  26763. scene.resetCachedMaterial();
  26764. // Fallbacks
  26765. var fallbacks = new BABYLON.EffectFallbacks();
  26766. if (this._defines.REFLECTION) {
  26767. fallbacks.addFallback(0, "REFLECTION");
  26768. }
  26769. if (this._defines.SPECULAR) {
  26770. fallbacks.addFallback(0, "SPECULAR");
  26771. }
  26772. if (this._defines.BUMP) {
  26773. fallbacks.addFallback(0, "BUMP");
  26774. }
  26775. if (this._defines.PARALLAX) {
  26776. fallbacks.addFallback(1, "PARALLAX");
  26777. }
  26778. if (this._defines.PARALLAXOCCLUSION) {
  26779. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26780. }
  26781. if (this._defines.SPECULAROVERALPHA) {
  26782. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26783. }
  26784. if (this._defines.FOG) {
  26785. fallbacks.addFallback(1, "FOG");
  26786. }
  26787. if (this._defines.POINTSIZE) {
  26788. fallbacks.addFallback(0, "POINTSIZE");
  26789. }
  26790. if (this._defines.LOGARITHMICDEPTH) {
  26791. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26792. }
  26793. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26794. if (this._defines.SPECULARTERM) {
  26795. fallbacks.addFallback(0, "SPECULARTERM");
  26796. }
  26797. if (this._defines.DIFFUSEFRESNEL) {
  26798. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26799. }
  26800. if (this._defines.OPACITYFRESNEL) {
  26801. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26802. }
  26803. if (this._defines.REFLECTIONFRESNEL) {
  26804. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26805. }
  26806. if (this._defines.EMISSIVEFRESNEL) {
  26807. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26808. }
  26809. if (this._defines.FRESNEL) {
  26810. fallbacks.addFallback(4, "FRESNEL");
  26811. }
  26812. //Attributes
  26813. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26814. if (this._defines.NORMAL) {
  26815. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26816. }
  26817. if (this._defines.UV1) {
  26818. attribs.push(BABYLON.VertexBuffer.UVKind);
  26819. }
  26820. if (this._defines.UV2) {
  26821. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26822. }
  26823. if (this._defines.VERTEXCOLOR) {
  26824. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26825. }
  26826. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26827. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26828. var shaderName = "default";
  26829. var join = this._defines.toString();
  26830. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26831. "vFogInfos", "vFogColor", "pointSize",
  26832. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26833. "mBones",
  26834. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26835. "depthValues",
  26836. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26837. "logarithmicDepthConstant"
  26838. ];
  26839. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26840. if (this._defines.CAMERACOLORCURVES) {
  26841. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26842. }
  26843. if (this._defines.CAMERACOLORGRADING) {
  26844. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26845. }
  26846. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26847. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26848. }
  26849. if (!this._effect.isReady()) {
  26850. return false;
  26851. }
  26852. this._renderId = scene.getRenderId();
  26853. this._wasPreviouslyReady = true;
  26854. if (mesh) {
  26855. if (!mesh._materialDefines) {
  26856. mesh._materialDefines = new StandardMaterialDefines();
  26857. }
  26858. this._defines.cloneTo(mesh._materialDefines);
  26859. }
  26860. return true;
  26861. };
  26862. StandardMaterial.prototype.unbind = function () {
  26863. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26864. this._effect.setTexture("reflection2DSampler", null);
  26865. }
  26866. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26867. this._effect.setTexture("refraction2DSampler", null);
  26868. }
  26869. _super.prototype.unbind.call(this);
  26870. };
  26871. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26872. this._effect.setMatrix("world", world);
  26873. };
  26874. StandardMaterial.prototype.bind = function (world, mesh) {
  26875. var scene = this.getScene();
  26876. // Matrices
  26877. this.bindOnlyWorldMatrix(world);
  26878. // Bones
  26879. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26880. if (scene.getCachedMaterial() !== this) {
  26881. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26882. if (StandardMaterial.FresnelEnabled) {
  26883. // Fresnel
  26884. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26885. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26886. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26887. }
  26888. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26889. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26890. }
  26891. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26892. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26893. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26894. }
  26895. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26896. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26897. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26898. }
  26899. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26900. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26901. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26902. }
  26903. }
  26904. // Textures
  26905. if (scene.texturesEnabled) {
  26906. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26907. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26908. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26909. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26910. }
  26911. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26912. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26913. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26914. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26915. }
  26916. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26917. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26918. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26919. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26920. }
  26921. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26922. if (this.reflectionTexture.isCube) {
  26923. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26924. }
  26925. else {
  26926. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26927. }
  26928. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26929. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26930. }
  26931. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26932. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26933. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26934. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26935. }
  26936. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26937. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26938. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26939. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26940. }
  26941. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26942. this._effect.setTexture("specularSampler", this.specularTexture);
  26943. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26944. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26945. }
  26946. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26947. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26948. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26949. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26950. }
  26951. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26952. var depth = 1.0;
  26953. if (this.refractionTexture.isCube) {
  26954. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26955. }
  26956. else {
  26957. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26958. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26959. if (this.refractionTexture.depth) {
  26960. depth = this.refractionTexture.depth;
  26961. }
  26962. }
  26963. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26964. }
  26965. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26966. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26967. }
  26968. }
  26969. // Clip plane
  26970. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26971. // Point size
  26972. if (this.pointsCloud) {
  26973. this._effect.setFloat("pointSize", this.pointSize);
  26974. }
  26975. // Colors
  26976. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26977. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26978. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26979. if (this._defines.SPECULARTERM) {
  26980. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26981. }
  26982. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26983. }
  26984. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26985. // Diffuse
  26986. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26987. // Lights
  26988. if (scene.lightsEnabled && !this.disableLighting) {
  26989. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26990. }
  26991. // View
  26992. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26993. this._effect.setMatrix("view", scene.getViewMatrix());
  26994. }
  26995. // Fog
  26996. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26997. // Log. depth
  26998. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26999. // Color Curves
  27000. if (this.cameraColorCurves) {
  27001. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  27002. }
  27003. }
  27004. _super.prototype.bind.call(this, world, mesh);
  27005. };
  27006. StandardMaterial.prototype.getAnimatables = function () {
  27007. var results = [];
  27008. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  27009. results.push(this.diffuseTexture);
  27010. }
  27011. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  27012. results.push(this.ambientTexture);
  27013. }
  27014. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  27015. results.push(this.opacityTexture);
  27016. }
  27017. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  27018. results.push(this.reflectionTexture);
  27019. }
  27020. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  27021. results.push(this.emissiveTexture);
  27022. }
  27023. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  27024. results.push(this.specularTexture);
  27025. }
  27026. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  27027. results.push(this.bumpTexture);
  27028. }
  27029. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  27030. results.push(this.lightmapTexture);
  27031. }
  27032. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  27033. results.push(this.refractionTexture);
  27034. }
  27035. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  27036. results.push(this.cameraColorGradingTexture);
  27037. }
  27038. return results;
  27039. };
  27040. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27041. if (forceDisposeTextures) {
  27042. if (this.diffuseTexture) {
  27043. this.diffuseTexture.dispose();
  27044. }
  27045. if (this.ambientTexture) {
  27046. this.ambientTexture.dispose();
  27047. }
  27048. if (this.opacityTexture) {
  27049. this.opacityTexture.dispose();
  27050. }
  27051. if (this.reflectionTexture) {
  27052. this.reflectionTexture.dispose();
  27053. }
  27054. if (this.emissiveTexture) {
  27055. this.emissiveTexture.dispose();
  27056. }
  27057. if (this.specularTexture) {
  27058. this.specularTexture.dispose();
  27059. }
  27060. if (this.bumpTexture) {
  27061. this.bumpTexture.dispose();
  27062. }
  27063. if (this.lightmapTexture) {
  27064. this.lightmapTexture.dispose();
  27065. }
  27066. if (this.refractionTexture) {
  27067. this.refractionTexture.dispose();
  27068. }
  27069. if (this.cameraColorGradingTexture) {
  27070. this.cameraColorGradingTexture.dispose();
  27071. }
  27072. }
  27073. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27074. };
  27075. StandardMaterial.prototype.clone = function (name) {
  27076. var _this = this;
  27077. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27078. };
  27079. StandardMaterial.prototype.serialize = function () {
  27080. return BABYLON.SerializationHelper.Serialize(this);
  27081. };
  27082. // Statics
  27083. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27084. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27085. };
  27086. return StandardMaterial;
  27087. }(BABYLON.Material));
  27088. // Flags used to enable or disable a type of texture for all Standard Materials
  27089. StandardMaterial.DiffuseTextureEnabled = true;
  27090. StandardMaterial.AmbientTextureEnabled = true;
  27091. StandardMaterial.OpacityTextureEnabled = true;
  27092. StandardMaterial.ReflectionTextureEnabled = true;
  27093. StandardMaterial.EmissiveTextureEnabled = true;
  27094. StandardMaterial.SpecularTextureEnabled = true;
  27095. StandardMaterial.BumpTextureEnabled = true;
  27096. StandardMaterial.FresnelEnabled = true;
  27097. StandardMaterial.LightmapTextureEnabled = true;
  27098. StandardMaterial.RefractionTextureEnabled = true;
  27099. StandardMaterial.ColorGradingTextureEnabled = true;
  27100. __decorate([
  27101. BABYLON.serializeAsTexture()
  27102. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27103. __decorate([
  27104. BABYLON.serializeAsTexture()
  27105. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27106. __decorate([
  27107. BABYLON.serializeAsTexture()
  27108. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27109. __decorate([
  27110. BABYLON.serializeAsTexture()
  27111. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27112. __decorate([
  27113. BABYLON.serializeAsTexture()
  27114. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27115. __decorate([
  27116. BABYLON.serializeAsTexture()
  27117. ], StandardMaterial.prototype, "specularTexture", void 0);
  27118. __decorate([
  27119. BABYLON.serializeAsTexture()
  27120. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27121. __decorate([
  27122. BABYLON.serializeAsTexture()
  27123. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27124. __decorate([
  27125. BABYLON.serializeAsTexture()
  27126. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27127. __decorate([
  27128. BABYLON.serializeAsColor3("ambient")
  27129. ], StandardMaterial.prototype, "ambientColor", void 0);
  27130. __decorate([
  27131. BABYLON.serializeAsColor3("diffuse")
  27132. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27133. __decorate([
  27134. BABYLON.serializeAsColor3("specular")
  27135. ], StandardMaterial.prototype, "specularColor", void 0);
  27136. __decorate([
  27137. BABYLON.serializeAsColor3("emissive")
  27138. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27139. __decorate([
  27140. BABYLON.serialize()
  27141. ], StandardMaterial.prototype, "specularPower", void 0);
  27142. __decorate([
  27143. BABYLON.serialize()
  27144. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27145. __decorate([
  27146. BABYLON.serialize()
  27147. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27148. __decorate([
  27149. BABYLON.serialize()
  27150. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27151. __decorate([
  27152. BABYLON.serialize()
  27153. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27154. __decorate([
  27155. BABYLON.serialize()
  27156. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27157. __decorate([
  27158. BABYLON.serialize()
  27159. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27160. __decorate([
  27161. BABYLON.serialize()
  27162. ], StandardMaterial.prototype, "disableLighting", void 0);
  27163. __decorate([
  27164. BABYLON.serialize()
  27165. ], StandardMaterial.prototype, "useParallax", void 0);
  27166. __decorate([
  27167. BABYLON.serialize()
  27168. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27169. __decorate([
  27170. BABYLON.serialize()
  27171. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27172. __decorate([
  27173. BABYLON.serialize()
  27174. ], StandardMaterial.prototype, "roughness", void 0);
  27175. __decorate([
  27176. BABYLON.serialize()
  27177. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27178. __decorate([
  27179. BABYLON.serialize()
  27180. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27181. __decorate([
  27182. BABYLON.serialize()
  27183. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27184. __decorate([
  27185. BABYLON.serializeAsFresnelParameters()
  27186. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27187. __decorate([
  27188. BABYLON.serializeAsFresnelParameters()
  27189. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27190. __decorate([
  27191. BABYLON.serializeAsFresnelParameters()
  27192. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27193. __decorate([
  27194. BABYLON.serializeAsFresnelParameters()
  27195. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27196. __decorate([
  27197. BABYLON.serializeAsFresnelParameters()
  27198. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27199. __decorate([
  27200. BABYLON.serialize()
  27201. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27202. __decorate([
  27203. BABYLON.serialize()
  27204. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27205. __decorate([
  27206. BABYLON.serialize()
  27207. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27208. __decorate([
  27209. BABYLON.serialize()
  27210. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27211. __decorate([
  27212. BABYLON.serializeAsTexture()
  27213. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27214. __decorate([
  27215. BABYLON.serializeAsColorCurves()
  27216. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27217. __decorate([
  27218. BABYLON.serialize()
  27219. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27220. BABYLON.StandardMaterial = StandardMaterial;
  27221. })(BABYLON || (BABYLON = {}));
  27222. //# sourceMappingURL=babylon.standardMaterial.js.map
  27223. var BABYLON;
  27224. (function (BABYLON) {
  27225. var MultiMaterial = (function (_super) {
  27226. __extends(MultiMaterial, _super);
  27227. function MultiMaterial(name, scene) {
  27228. var _this = _super.call(this, name, scene, true) || this;
  27229. _this.subMaterials = new Array();
  27230. scene.multiMaterials.push(_this);
  27231. return _this;
  27232. }
  27233. // Properties
  27234. MultiMaterial.prototype.getSubMaterial = function (index) {
  27235. if (index < 0 || index >= this.subMaterials.length) {
  27236. return this.getScene().defaultMaterial;
  27237. }
  27238. return this.subMaterials[index];
  27239. };
  27240. // Methods
  27241. MultiMaterial.prototype.getClassName = function () {
  27242. return "MultiMaterial";
  27243. };
  27244. MultiMaterial.prototype.isReady = function (mesh) {
  27245. for (var index = 0; index < this.subMaterials.length; index++) {
  27246. var subMaterial = this.subMaterials[index];
  27247. if (subMaterial) {
  27248. if (!this.subMaterials[index].isReady(mesh)) {
  27249. return false;
  27250. }
  27251. }
  27252. }
  27253. return true;
  27254. };
  27255. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27256. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27257. for (var index = 0; index < this.subMaterials.length; index++) {
  27258. var subMaterial = null;
  27259. if (cloneChildren) {
  27260. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27261. }
  27262. else {
  27263. subMaterial = this.subMaterials[index];
  27264. }
  27265. newMultiMaterial.subMaterials.push(subMaterial);
  27266. }
  27267. return newMultiMaterial;
  27268. };
  27269. MultiMaterial.prototype.serialize = function () {
  27270. var serializationObject = {};
  27271. serializationObject.name = this.name;
  27272. serializationObject.id = this.id;
  27273. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27274. serializationObject.materials = [];
  27275. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27276. var subMat = this.subMaterials[matIndex];
  27277. if (subMat) {
  27278. serializationObject.materials.push(subMat.id);
  27279. }
  27280. else {
  27281. serializationObject.materials.push(null);
  27282. }
  27283. }
  27284. return serializationObject;
  27285. };
  27286. return MultiMaterial;
  27287. }(BABYLON.Material));
  27288. BABYLON.MultiMaterial = MultiMaterial;
  27289. })(BABYLON || (BABYLON = {}));
  27290. //# sourceMappingURL=babylon.multiMaterial.js.map
  27291. var BABYLON;
  27292. (function (BABYLON) {
  27293. var SceneLoader = (function () {
  27294. function SceneLoader() {
  27295. }
  27296. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27297. get: function () {
  27298. return 0;
  27299. },
  27300. enumerable: true,
  27301. configurable: true
  27302. });
  27303. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27304. get: function () {
  27305. return 1;
  27306. },
  27307. enumerable: true,
  27308. configurable: true
  27309. });
  27310. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  27311. get: function () {
  27312. return 2;
  27313. },
  27314. enumerable: true,
  27315. configurable: true
  27316. });
  27317. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  27318. get: function () {
  27319. return 3;
  27320. },
  27321. enumerable: true,
  27322. configurable: true
  27323. });
  27324. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  27325. get: function () {
  27326. return SceneLoader._ForceFullSceneLoadingForIncremental;
  27327. },
  27328. set: function (value) {
  27329. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  27330. },
  27331. enumerable: true,
  27332. configurable: true
  27333. });
  27334. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  27335. get: function () {
  27336. return SceneLoader._ShowLoadingScreen;
  27337. },
  27338. set: function (value) {
  27339. SceneLoader._ShowLoadingScreen = value;
  27340. },
  27341. enumerable: true,
  27342. configurable: true
  27343. });
  27344. Object.defineProperty(SceneLoader, "loggingLevel", {
  27345. get: function () {
  27346. return SceneLoader._loggingLevel;
  27347. },
  27348. set: function (value) {
  27349. SceneLoader._loggingLevel = value;
  27350. },
  27351. enumerable: true,
  27352. configurable: true
  27353. });
  27354. SceneLoader._getDefaultPlugin = function () {
  27355. return SceneLoader._registeredPlugins[".babylon"];
  27356. };
  27357. SceneLoader._getPluginForExtension = function (extension) {
  27358. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  27359. if (registeredPlugin) {
  27360. return registeredPlugin;
  27361. }
  27362. return SceneLoader._getDefaultPlugin();
  27363. };
  27364. SceneLoader._getPluginForFilename = function (sceneFilename) {
  27365. if (sceneFilename.name) {
  27366. sceneFilename = sceneFilename.name;
  27367. }
  27368. var dotPosition = sceneFilename.lastIndexOf(".");
  27369. var queryStringPosition = sceneFilename.indexOf("?");
  27370. if (queryStringPosition === -1) {
  27371. queryStringPosition = sceneFilename.length;
  27372. }
  27373. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  27374. return SceneLoader._getPluginForExtension(extension);
  27375. };
  27376. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  27377. SceneLoader._getDirectLoad = function (sceneFilename) {
  27378. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  27379. return sceneFilename.substr(5);
  27380. }
  27381. return null;
  27382. };
  27383. // Public functions
  27384. SceneLoader.GetPluginForExtension = function (extension) {
  27385. return SceneLoader._getPluginForExtension(extension).plugin;
  27386. };
  27387. SceneLoader.RegisterPlugin = function (plugin) {
  27388. if (typeof plugin.extensions === "string") {
  27389. var extension = plugin.extensions;
  27390. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27391. plugin: plugin,
  27392. isBinary: false
  27393. };
  27394. }
  27395. else {
  27396. var extensions = plugin.extensions;
  27397. Object.keys(extensions).forEach(function (extension) {
  27398. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27399. plugin: plugin,
  27400. isBinary: extensions[extension].isBinary
  27401. };
  27402. });
  27403. }
  27404. };
  27405. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27406. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27407. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27408. return;
  27409. }
  27410. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27411. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27412. return;
  27413. }
  27414. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27415. var loadingToken = {};
  27416. scene._addPendingData(loadingToken);
  27417. var manifestChecked = function (success) {
  27418. scene.database = database;
  27419. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27420. var plugin = registeredPlugin.plugin;
  27421. var useArrayBuffer = registeredPlugin.isBinary;
  27422. var importMeshFromData = function (data) {
  27423. var meshes = [];
  27424. var particleSystems = [];
  27425. var skeletons = [];
  27426. try {
  27427. if (plugin.importMesh) {
  27428. var syncedPlugin = plugin;
  27429. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  27430. if (onerror) {
  27431. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27432. }
  27433. scene._removePendingData(loadingToken);
  27434. return;
  27435. }
  27436. if (onsuccess) {
  27437. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27438. onsuccess(meshes, particleSystems, skeletons);
  27439. scene._removePendingData(loadingToken);
  27440. }
  27441. }
  27442. else {
  27443. var asyncedPlugin = plugin;
  27444. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  27445. if (onsuccess) {
  27446. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27447. onsuccess(meshes, particleSystems, skeletons);
  27448. scene._removePendingData(loadingToken);
  27449. }
  27450. }, function () {
  27451. if (onerror) {
  27452. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27453. }
  27454. scene._removePendingData(loadingToken);
  27455. });
  27456. }
  27457. }
  27458. catch (e) {
  27459. if (onerror) {
  27460. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  27461. }
  27462. scene._removePendingData(loadingToken);
  27463. }
  27464. };
  27465. if (directLoad) {
  27466. importMeshFromData(directLoad);
  27467. return;
  27468. }
  27469. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  27470. importMeshFromData(data);
  27471. }, progressCallBack, database, useArrayBuffer);
  27472. };
  27473. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  27474. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27475. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27476. }
  27477. else {
  27478. // If the scene is a data stream or offline support is not enabled, it's a direct load
  27479. manifestChecked(true);
  27480. }
  27481. };
  27482. /**
  27483. * Load a scene
  27484. * @param rootUrl a string that defines the root url for scene and resources
  27485. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27486. * @param engine is the instance of BABYLON.Engine to use to create the scene
  27487. */
  27488. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  27489. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  27490. };
  27491. /**
  27492. * Append a scene
  27493. * @param rootUrl a string that defines the root url for scene and resources
  27494. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27495. * @param scene is the instance of BABYLON.Scene to append to
  27496. */
  27497. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27498. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27499. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27500. return;
  27501. }
  27502. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27503. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27504. var plugin = registeredPlugin.plugin;
  27505. var useArrayBuffer = registeredPlugin.isBinary;
  27506. var database;
  27507. var loadingToken = {};
  27508. scene._addPendingData(loadingToken);
  27509. if (SceneLoader.ShowLoadingScreen) {
  27510. scene.getEngine().displayLoadingUI();
  27511. }
  27512. var loadSceneFromData = function (data) {
  27513. scene.database = database;
  27514. if (plugin.load) {
  27515. var syncedPlugin = plugin;
  27516. if (!syncedPlugin.load(scene, data, rootUrl)) {
  27517. if (onerror) {
  27518. onerror(scene);
  27519. }
  27520. scene._removePendingData(loadingToken);
  27521. scene.getEngine().hideLoadingUI();
  27522. return;
  27523. }
  27524. if (onsuccess) {
  27525. onsuccess(scene);
  27526. }
  27527. scene._removePendingData(loadingToken);
  27528. }
  27529. else {
  27530. var asyncedPlugin = plugin;
  27531. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  27532. if (onsuccess) {
  27533. onsuccess(scene);
  27534. }
  27535. scene._removePendingData(loadingToken);
  27536. }, function () {
  27537. if (onerror) {
  27538. onerror(scene);
  27539. }
  27540. scene._removePendingData(loadingToken);
  27541. scene.getEngine().hideLoadingUI();
  27542. });
  27543. }
  27544. if (SceneLoader.ShowLoadingScreen) {
  27545. scene.executeWhenReady(function () {
  27546. scene.getEngine().hideLoadingUI();
  27547. });
  27548. }
  27549. };
  27550. var manifestChecked = function (success) {
  27551. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  27552. };
  27553. if (directLoad) {
  27554. loadSceneFromData(directLoad);
  27555. return;
  27556. }
  27557. if (rootUrl.indexOf("file:") === -1) {
  27558. if (scene.getEngine().enableOfflineSupport) {
  27559. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27560. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27561. }
  27562. else {
  27563. manifestChecked(true);
  27564. }
  27565. }
  27566. else {
  27567. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  27568. }
  27569. };
  27570. return SceneLoader;
  27571. }());
  27572. // Flags
  27573. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  27574. SceneLoader._ShowLoadingScreen = true;
  27575. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  27576. // Members
  27577. SceneLoader._registeredPlugins = {};
  27578. BABYLON.SceneLoader = SceneLoader;
  27579. ;
  27580. })(BABYLON || (BABYLON = {}));
  27581. //# sourceMappingURL=babylon.sceneLoader.js.map
  27582. var BABYLON;
  27583. (function (BABYLON) {
  27584. var Internals;
  27585. (function (Internals) {
  27586. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  27587. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27588. var parsedMaterial = parsedData.materials[index];
  27589. if (parsedMaterial.id === id) {
  27590. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27591. }
  27592. }
  27593. return null;
  27594. };
  27595. var isDescendantOf = function (mesh, names, hierarchyIds) {
  27596. names = (names instanceof Array) ? names : [names];
  27597. for (var i in names) {
  27598. if (mesh.name === names[i]) {
  27599. hierarchyIds.push(mesh.id);
  27600. return true;
  27601. }
  27602. }
  27603. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  27604. hierarchyIds.push(mesh.id);
  27605. return true;
  27606. }
  27607. return false;
  27608. };
  27609. var logOperation = function (operation, producer) {
  27610. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  27611. };
  27612. BABYLON.SceneLoader.RegisterPlugin({
  27613. extensions: ".babylon",
  27614. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  27615. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27616. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27617. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27618. // and avoid problems with multiple concurrent .babylon loads.
  27619. var log = "importMesh has failed JSON parse";
  27620. try {
  27621. var parsedData = JSON.parse(data);
  27622. log = "";
  27623. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27624. var loadedSkeletonsIds = [];
  27625. var loadedMaterialsIds = [];
  27626. var hierarchyIds = [];
  27627. var index;
  27628. var cache;
  27629. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27630. var parsedMesh = parsedData.meshes[index];
  27631. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  27632. if (meshesNames instanceof Array) {
  27633. // Remove found mesh name from list.
  27634. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  27635. }
  27636. //Geometry?
  27637. if (parsedMesh.geometryId) {
  27638. //does the file contain geometries?
  27639. if (parsedData.geometries) {
  27640. //find the correct geometry and add it to the scene
  27641. var found = false;
  27642. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  27643. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  27644. return;
  27645. }
  27646. else {
  27647. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  27648. if (parsedGeometryData.id === parsedMesh.geometryId) {
  27649. switch (geometryType) {
  27650. case "boxes":
  27651. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  27652. break;
  27653. case "spheres":
  27654. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  27655. break;
  27656. case "cylinders":
  27657. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27658. break;
  27659. case "toruses":
  27660. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27661. break;
  27662. case "grounds":
  27663. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27664. break;
  27665. case "planes":
  27666. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27667. break;
  27668. case "torusKnots":
  27669. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27670. break;
  27671. case "vertexData":
  27672. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27673. break;
  27674. }
  27675. found = true;
  27676. }
  27677. });
  27678. }
  27679. });
  27680. if (!found) {
  27681. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27682. }
  27683. }
  27684. }
  27685. // Material ?
  27686. if (parsedMesh.materialId) {
  27687. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27688. if (!materialFound && parsedData.multiMaterials) {
  27689. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27690. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27691. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27692. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27693. var subMatId = parsedMultiMaterial.materials[matIndex];
  27694. loadedMaterialsIds.push(subMatId);
  27695. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27696. log += "\n\tMaterial " + mat.toString(fullDetails);
  27697. }
  27698. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27699. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27700. materialFound = true;
  27701. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27702. break;
  27703. }
  27704. }
  27705. }
  27706. if (!materialFound) {
  27707. loadedMaterialsIds.push(parsedMesh.materialId);
  27708. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27709. if (!mat) {
  27710. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27711. }
  27712. else {
  27713. log += "\n\tMaterial " + mat.toString(fullDetails);
  27714. }
  27715. }
  27716. }
  27717. // Skeleton ?
  27718. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27719. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27720. if (!skeletonAlreadyLoaded) {
  27721. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27722. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27723. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27724. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27725. skeletons.push(skeleton);
  27726. loadedSkeletonsIds.push(parsedSkeleton.id);
  27727. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27728. }
  27729. }
  27730. }
  27731. }
  27732. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27733. meshes.push(mesh);
  27734. log += "\n\tMesh " + mesh.toString(fullDetails);
  27735. }
  27736. }
  27737. // Connecting parents
  27738. var currentMesh;
  27739. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27740. currentMesh = scene.meshes[index];
  27741. if (currentMesh._waitingParentId) {
  27742. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27743. currentMesh._waitingParentId = undefined;
  27744. }
  27745. }
  27746. // freeze and compute world matrix application
  27747. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27748. currentMesh = scene.meshes[index];
  27749. if (currentMesh._waitingFreezeWorldMatrix) {
  27750. currentMesh.freezeWorldMatrix();
  27751. currentMesh._waitingFreezeWorldMatrix = undefined;
  27752. }
  27753. else {
  27754. currentMesh.computeWorldMatrix(true);
  27755. }
  27756. }
  27757. // Particles
  27758. if (parsedData.particleSystems) {
  27759. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27760. var parsedParticleSystem = parsedData.particleSystems[index];
  27761. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27762. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27763. }
  27764. }
  27765. }
  27766. return true;
  27767. }
  27768. catch (err) {
  27769. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27770. log = null;
  27771. throw err;
  27772. }
  27773. finally {
  27774. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27775. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27776. }
  27777. }
  27778. },
  27779. load: function (scene, data, rootUrl) {
  27780. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27781. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27782. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27783. // and avoid problems with multiple concurrent .babylon loads.
  27784. var log = "importScene has failed JSON parse";
  27785. try {
  27786. var parsedData = JSON.parse(data);
  27787. log = "";
  27788. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27789. // Scene
  27790. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27791. scene.autoClear = parsedData.autoClear;
  27792. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27793. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27794. if (parsedData.gravity) {
  27795. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27796. }
  27797. // Fog
  27798. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27799. scene.fogMode = parsedData.fogMode;
  27800. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27801. scene.fogStart = parsedData.fogStart;
  27802. scene.fogEnd = parsedData.fogEnd;
  27803. scene.fogDensity = parsedData.fogDensity;
  27804. log += "\tFog mode for scene: ";
  27805. switch (scene.fogMode) {
  27806. // getters not compiling, so using hardcoded
  27807. case 1:
  27808. log += "exp\n";
  27809. break;
  27810. case 2:
  27811. log += "exp2\n";
  27812. break;
  27813. case 3:
  27814. log += "linear\n";
  27815. break;
  27816. }
  27817. }
  27818. //Physics
  27819. if (parsedData.physicsEnabled) {
  27820. var physicsPlugin;
  27821. if (parsedData.physicsEngine === "cannon") {
  27822. physicsPlugin = new BABYLON.CannonJSPlugin();
  27823. }
  27824. else if (parsedData.physicsEngine === "oimo") {
  27825. physicsPlugin = new BABYLON.OimoJSPlugin();
  27826. }
  27827. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27828. //else - default engine, which is currently oimo
  27829. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27830. scene.enablePhysics(physicsGravity, physicsPlugin);
  27831. }
  27832. // Metadata
  27833. if (parsedData.metadata !== undefined) {
  27834. scene.metadata = parsedData.metadata;
  27835. }
  27836. //collisions, if defined. otherwise, default is true
  27837. if (parsedData.collisionsEnabled != undefined) {
  27838. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27839. }
  27840. scene.workerCollisions = !!parsedData.workerCollisions;
  27841. var index;
  27842. var cache;
  27843. // Lights
  27844. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27845. var parsedLight = parsedData.lights[index];
  27846. var light = BABYLON.Light.Parse(parsedLight, scene);
  27847. log += (index === 0 ? "\n\tLights:" : "");
  27848. log += "\n\t\t" + light.toString(fullDetails);
  27849. }
  27850. // Animations
  27851. if (parsedData.animations) {
  27852. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27853. var parsedAnimation = parsedData.animations[index];
  27854. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27855. scene.animations.push(animation);
  27856. log += (index === 0 ? "\n\tAnimations:" : "");
  27857. log += "\n\t\t" + animation.toString(fullDetails);
  27858. }
  27859. }
  27860. if (parsedData.autoAnimate) {
  27861. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27862. }
  27863. // Materials
  27864. if (parsedData.materials) {
  27865. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27866. var parsedMaterial = parsedData.materials[index];
  27867. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27868. log += (index === 0 ? "\n\tMaterials:" : "");
  27869. log += "\n\t\t" + mat.toString(fullDetails);
  27870. }
  27871. }
  27872. if (parsedData.multiMaterials) {
  27873. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27874. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27875. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27876. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27877. log += "\n\t\t" + mmat.toString(fullDetails);
  27878. }
  27879. }
  27880. // Skeletons
  27881. if (parsedData.skeletons) {
  27882. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27883. var parsedSkeleton = parsedData.skeletons[index];
  27884. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27885. log += (index === 0 ? "\n\tSkeletons:" : "");
  27886. log += "\n\t\t" + skeleton.toString(fullDetails);
  27887. }
  27888. }
  27889. // Geometries
  27890. var geometries = parsedData.geometries;
  27891. if (geometries) {
  27892. // Boxes
  27893. var boxes = geometries.boxes;
  27894. if (boxes) {
  27895. for (index = 0, cache = boxes.length; index < cache; index++) {
  27896. var parsedBox = boxes[index];
  27897. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27898. }
  27899. }
  27900. // Spheres
  27901. var spheres = geometries.spheres;
  27902. if (spheres) {
  27903. for (index = 0, cache = spheres.length; index < cache; index++) {
  27904. var parsedSphere = spheres[index];
  27905. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27906. }
  27907. }
  27908. // Cylinders
  27909. var cylinders = geometries.cylinders;
  27910. if (cylinders) {
  27911. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27912. var parsedCylinder = cylinders[index];
  27913. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27914. }
  27915. }
  27916. // Toruses
  27917. var toruses = geometries.toruses;
  27918. if (toruses) {
  27919. for (index = 0, cache = toruses.length; index < cache; index++) {
  27920. var parsedTorus = toruses[index];
  27921. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27922. }
  27923. }
  27924. // Grounds
  27925. var grounds = geometries.grounds;
  27926. if (grounds) {
  27927. for (index = 0, cache = grounds.length; index < cache; index++) {
  27928. var parsedGround = grounds[index];
  27929. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27930. }
  27931. }
  27932. // Planes
  27933. var planes = geometries.planes;
  27934. if (planes) {
  27935. for (index = 0, cache = planes.length; index < cache; index++) {
  27936. var parsedPlane = planes[index];
  27937. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27938. }
  27939. }
  27940. // TorusKnots
  27941. var torusKnots = geometries.torusKnots;
  27942. if (torusKnots) {
  27943. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27944. var parsedTorusKnot = torusKnots[index];
  27945. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27946. }
  27947. }
  27948. // VertexData
  27949. var vertexData = geometries.vertexData;
  27950. if (vertexData) {
  27951. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27952. var parsedVertexData = vertexData[index];
  27953. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27954. }
  27955. }
  27956. }
  27957. // Meshes
  27958. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27959. var parsedMesh = parsedData.meshes[index];
  27960. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27961. log += (index === 0 ? "\n\tMeshes:" : "");
  27962. log += "\n\t\t" + mesh.toString(fullDetails);
  27963. }
  27964. // Cameras
  27965. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27966. var parsedCamera = parsedData.cameras[index];
  27967. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27968. log += (index === 0 ? "\n\tCameras:" : "");
  27969. log += "\n\t\t" + camera.toString(fullDetails);
  27970. }
  27971. if (parsedData.activeCameraID) {
  27972. scene.setActiveCameraByID(parsedData.activeCameraID);
  27973. }
  27974. // Browsing all the graph to connect the dots
  27975. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27976. var camera = scene.cameras[index];
  27977. if (camera._waitingParentId) {
  27978. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27979. camera._waitingParentId = undefined;
  27980. }
  27981. }
  27982. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27983. var light = scene.lights[index];
  27984. if (light._waitingParentId) {
  27985. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27986. light._waitingParentId = undefined;
  27987. }
  27988. }
  27989. // Sounds
  27990. var loadedSounds = [];
  27991. var loadedSound;
  27992. if (BABYLON.AudioEngine && parsedData.sounds) {
  27993. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27994. var parsedSound = parsedData.sounds[index];
  27995. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27996. if (!parsedSound.url)
  27997. parsedSound.url = parsedSound.name;
  27998. if (!loadedSounds[parsedSound.url]) {
  27999. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  28000. loadedSounds[parsedSound.url] = loadedSound;
  28001. }
  28002. else {
  28003. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  28004. }
  28005. }
  28006. else {
  28007. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  28008. }
  28009. }
  28010. }
  28011. loadedSounds = [];
  28012. // Connect parents & children and parse actions
  28013. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28014. var mesh = scene.meshes[index];
  28015. if (mesh._waitingParentId) {
  28016. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  28017. mesh._waitingParentId = undefined;
  28018. }
  28019. if (mesh._waitingActions) {
  28020. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  28021. mesh._waitingActions = undefined;
  28022. }
  28023. }
  28024. // freeze world matrix application
  28025. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28026. var currentMesh = scene.meshes[index];
  28027. if (currentMesh._waitingFreezeWorldMatrix) {
  28028. currentMesh.freezeWorldMatrix();
  28029. currentMesh._waitingFreezeWorldMatrix = undefined;
  28030. }
  28031. else {
  28032. currentMesh.computeWorldMatrix(true);
  28033. }
  28034. }
  28035. // Particles Systems
  28036. if (parsedData.particleSystems) {
  28037. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28038. var parsedParticleSystem = parsedData.particleSystems[index];
  28039. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  28040. }
  28041. }
  28042. // Lens flares
  28043. if (parsedData.lensFlareSystems) {
  28044. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  28045. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  28046. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  28047. }
  28048. }
  28049. // Shadows
  28050. if (parsedData.shadowGenerators) {
  28051. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  28052. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  28053. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  28054. }
  28055. }
  28056. // Actions (scene)
  28057. if (parsedData.actions) {
  28058. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  28059. }
  28060. // Finish
  28061. return true;
  28062. }
  28063. catch (err) {
  28064. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  28065. log = null;
  28066. throw err;
  28067. }
  28068. finally {
  28069. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28070. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28071. }
  28072. }
  28073. }
  28074. });
  28075. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28076. })(BABYLON || (BABYLON = {}));
  28077. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28078. var BABYLON;
  28079. (function (BABYLON) {
  28080. var SpriteManager = (function () {
  28081. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28082. if (epsilon === void 0) { epsilon = 0.01; }
  28083. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28084. this.name = name;
  28085. this.sprites = new Array();
  28086. this.renderingGroupId = 0;
  28087. this.layerMask = 0x0FFFFFFF;
  28088. this.fogEnabled = true;
  28089. this.isPickable = false;
  28090. /**
  28091. * An event triggered when the manager is disposed.
  28092. * @type {BABYLON.Observable}
  28093. */
  28094. this.onDisposeObservable = new BABYLON.Observable();
  28095. this._vertexBuffers = {};
  28096. this._capacity = capacity;
  28097. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28098. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28099. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28100. if (cellSize.width && cellSize.height) {
  28101. this.cellWidth = cellSize.width;
  28102. this.cellHeight = cellSize.height;
  28103. }
  28104. else if (cellSize !== undefined) {
  28105. this.cellWidth = cellSize;
  28106. this.cellHeight = cellSize;
  28107. }
  28108. else {
  28109. return;
  28110. }
  28111. this._epsilon = epsilon;
  28112. this._scene = scene;
  28113. this._scene.spriteManagers.push(this);
  28114. var indices = [];
  28115. var index = 0;
  28116. for (var count = 0; count < capacity; count++) {
  28117. indices.push(index);
  28118. indices.push(index + 1);
  28119. indices.push(index + 2);
  28120. indices.push(index);
  28121. indices.push(index + 2);
  28122. indices.push(index + 3);
  28123. index += 4;
  28124. }
  28125. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28126. // VBO
  28127. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28128. this._vertexData = new Float32Array(capacity * 16 * 4);
  28129. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28130. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28131. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28132. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28133. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28134. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28135. this._vertexBuffers["options"] = options;
  28136. this._vertexBuffers["cellInfo"] = cellInfo;
  28137. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28138. // Effects
  28139. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28140. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28141. }
  28142. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28143. set: function (callback) {
  28144. if (this._onDisposeObserver) {
  28145. this.onDisposeObservable.remove(this._onDisposeObserver);
  28146. }
  28147. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28148. },
  28149. enumerable: true,
  28150. configurable: true
  28151. });
  28152. Object.defineProperty(SpriteManager.prototype, "texture", {
  28153. get: function () {
  28154. return this._spriteTexture;
  28155. },
  28156. set: function (value) {
  28157. this._spriteTexture = value;
  28158. },
  28159. enumerable: true,
  28160. configurable: true
  28161. });
  28162. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28163. var arrayOffset = index * 16;
  28164. if (offsetX === 0)
  28165. offsetX = this._epsilon;
  28166. else if (offsetX === 1)
  28167. offsetX = 1 - this._epsilon;
  28168. if (offsetY === 0)
  28169. offsetY = this._epsilon;
  28170. else if (offsetY === 1)
  28171. offsetY = 1 - this._epsilon;
  28172. this._vertexData[arrayOffset] = sprite.position.x;
  28173. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28174. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28175. this._vertexData[arrayOffset + 3] = sprite.angle;
  28176. this._vertexData[arrayOffset + 4] = sprite.width;
  28177. this._vertexData[arrayOffset + 5] = sprite.height;
  28178. this._vertexData[arrayOffset + 6] = offsetX;
  28179. this._vertexData[arrayOffset + 7] = offsetY;
  28180. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28181. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28182. var offset = (sprite.cellIndex / rowSize) >> 0;
  28183. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28184. this._vertexData[arrayOffset + 11] = offset;
  28185. // Color
  28186. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28187. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28188. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28189. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28190. };
  28191. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28192. var count = Math.min(this._capacity, this.sprites.length);
  28193. var min = BABYLON.Vector3.Zero();
  28194. var max = BABYLON.Vector3.Zero();
  28195. var distance = Number.MAX_VALUE;
  28196. var currentSprite;
  28197. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28198. var cameraView = camera.getViewMatrix();
  28199. for (var index = 0; index < count; index++) {
  28200. var sprite = this.sprites[index];
  28201. if (!sprite) {
  28202. continue;
  28203. }
  28204. if (predicate) {
  28205. if (!predicate(sprite)) {
  28206. continue;
  28207. }
  28208. }
  28209. else if (!sprite.isPickable) {
  28210. continue;
  28211. }
  28212. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28213. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28214. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28215. if (ray.intersectsBoxMinMax(min, max)) {
  28216. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28217. if (distance > currentDistance) {
  28218. distance = currentDistance;
  28219. currentSprite = sprite;
  28220. if (fastCheck) {
  28221. break;
  28222. }
  28223. }
  28224. }
  28225. }
  28226. if (currentSprite) {
  28227. var result = new BABYLON.PickingInfo();
  28228. result.hit = true;
  28229. result.pickedSprite = currentSprite;
  28230. result.distance = distance;
  28231. return result;
  28232. }
  28233. return null;
  28234. };
  28235. SpriteManager.prototype.render = function () {
  28236. // Check
  28237. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28238. return;
  28239. var engine = this._scene.getEngine();
  28240. var baseSize = this._spriteTexture.getBaseSize();
  28241. // Sprites
  28242. var deltaTime = engine.getDeltaTime();
  28243. var max = Math.min(this._capacity, this.sprites.length);
  28244. var rowSize = baseSize.width / this.cellWidth;
  28245. var offset = 0;
  28246. for (var index = 0; index < max; index++) {
  28247. var sprite = this.sprites[index];
  28248. if (!sprite) {
  28249. continue;
  28250. }
  28251. sprite._animate(deltaTime);
  28252. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28253. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28254. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28255. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28256. }
  28257. this._buffer.update(this._vertexData);
  28258. // Render
  28259. var effect = this._effectBase;
  28260. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28261. effect = this._effectFog;
  28262. }
  28263. engine.enableEffect(effect);
  28264. var viewMatrix = this._scene.getViewMatrix();
  28265. effect.setTexture("diffuseSampler", this._spriteTexture);
  28266. effect.setMatrix("view", viewMatrix);
  28267. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28268. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28269. // Fog
  28270. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28271. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28272. effect.setColor3("vFogColor", this._scene.fogColor);
  28273. }
  28274. // VBOs
  28275. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28276. // Draw order
  28277. engine.setDepthFunctionToLessOrEqual();
  28278. effect.setBool("alphaTest", true);
  28279. engine.setColorWrite(false);
  28280. engine.draw(true, 0, max * 6);
  28281. engine.setColorWrite(true);
  28282. effect.setBool("alphaTest", false);
  28283. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28284. engine.draw(true, 0, max * 6);
  28285. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28286. };
  28287. SpriteManager.prototype.dispose = function () {
  28288. if (this._buffer) {
  28289. this._buffer.dispose();
  28290. this._buffer = null;
  28291. }
  28292. if (this._indexBuffer) {
  28293. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28294. this._indexBuffer = null;
  28295. }
  28296. if (this._spriteTexture) {
  28297. this._spriteTexture.dispose();
  28298. this._spriteTexture = null;
  28299. }
  28300. // Remove from scene
  28301. var index = this._scene.spriteManagers.indexOf(this);
  28302. this._scene.spriteManagers.splice(index, 1);
  28303. // Callback
  28304. this.onDisposeObservable.notifyObservers(this);
  28305. this.onDisposeObservable.clear();
  28306. };
  28307. return SpriteManager;
  28308. }());
  28309. BABYLON.SpriteManager = SpriteManager;
  28310. })(BABYLON || (BABYLON = {}));
  28311. //# sourceMappingURL=babylon.spriteManager.js.map
  28312. var BABYLON;
  28313. (function (BABYLON) {
  28314. var Sprite = (function () {
  28315. function Sprite(name, manager) {
  28316. this.name = name;
  28317. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28318. this.width = 1.0;
  28319. this.height = 1.0;
  28320. this.angle = 0;
  28321. this.cellIndex = 0;
  28322. this.invertU = 0;
  28323. this.invertV = 0;
  28324. this.animations = new Array();
  28325. this.isPickable = false;
  28326. this._animationStarted = false;
  28327. this._loopAnimation = false;
  28328. this._fromIndex = 0;
  28329. this._toIndex = 0;
  28330. this._delay = 0;
  28331. this._direction = 1;
  28332. this._frameCount = 0;
  28333. this._time = 0;
  28334. this._manager = manager;
  28335. this._manager.sprites.push(this);
  28336. this.position = BABYLON.Vector3.Zero();
  28337. }
  28338. Object.defineProperty(Sprite.prototype, "size", {
  28339. get: function () {
  28340. return this.width;
  28341. },
  28342. set: function (value) {
  28343. this.width = value;
  28344. this.height = value;
  28345. },
  28346. enumerable: true,
  28347. configurable: true
  28348. });
  28349. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  28350. this._fromIndex = from;
  28351. this._toIndex = to;
  28352. this._loopAnimation = loop;
  28353. this._delay = delay;
  28354. this._animationStarted = true;
  28355. this._direction = from < to ? 1 : -1;
  28356. this.cellIndex = from;
  28357. this._time = 0;
  28358. this._onAnimationEnd = onAnimationEnd;
  28359. };
  28360. Sprite.prototype.stopAnimation = function () {
  28361. this._animationStarted = false;
  28362. };
  28363. Sprite.prototype._animate = function (deltaTime) {
  28364. if (!this._animationStarted)
  28365. return;
  28366. this._time += deltaTime;
  28367. if (this._time > this._delay) {
  28368. this._time = this._time % this._delay;
  28369. this.cellIndex += this._direction;
  28370. if (this.cellIndex === this._toIndex) {
  28371. if (this._loopAnimation) {
  28372. this.cellIndex = this._fromIndex;
  28373. }
  28374. else {
  28375. this._animationStarted = false;
  28376. if (this._onAnimationEnd) {
  28377. this._onAnimationEnd();
  28378. }
  28379. if (this.disposeWhenFinishedAnimating) {
  28380. this.dispose();
  28381. }
  28382. }
  28383. }
  28384. }
  28385. };
  28386. Sprite.prototype.dispose = function () {
  28387. for (var i = 0; i < this._manager.sprites.length; i++) {
  28388. if (this._manager.sprites[i] == this) {
  28389. this._manager.sprites.splice(i, 1);
  28390. }
  28391. }
  28392. };
  28393. return Sprite;
  28394. }());
  28395. BABYLON.Sprite = Sprite;
  28396. })(BABYLON || (BABYLON = {}));
  28397. //# sourceMappingURL=babylon.sprite.js.map
  28398. var BABYLON;
  28399. (function (BABYLON) {
  28400. var Layer = (function () {
  28401. function Layer(name, imgUrl, scene, isBackground, color) {
  28402. this.name = name;
  28403. this.scale = new BABYLON.Vector2(1, 1);
  28404. this.offset = new BABYLON.Vector2(0, 0);
  28405. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  28406. this._vertexBuffers = {};
  28407. // Events
  28408. /**
  28409. * An event triggered when the layer is disposed.
  28410. * @type {BABYLON.Observable}
  28411. */
  28412. this.onDisposeObservable = new BABYLON.Observable();
  28413. /**
  28414. * An event triggered before rendering the scene
  28415. * @type {BABYLON.Observable}
  28416. */
  28417. this.onBeforeRenderObservable = new BABYLON.Observable();
  28418. /**
  28419. * An event triggered after rendering the scene
  28420. * @type {BABYLON.Observable}
  28421. */
  28422. this.onAfterRenderObservable = new BABYLON.Observable();
  28423. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  28424. this.isBackground = isBackground === undefined ? true : isBackground;
  28425. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  28426. this._scene = scene;
  28427. this._scene.layers.push(this);
  28428. var engine = scene.getEngine();
  28429. // VBO
  28430. var vertices = [];
  28431. vertices.push(1, 1);
  28432. vertices.push(-1, 1);
  28433. vertices.push(-1, -1);
  28434. vertices.push(1, -1);
  28435. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28436. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  28437. // Indices
  28438. var indices = [];
  28439. indices.push(0);
  28440. indices.push(1);
  28441. indices.push(2);
  28442. indices.push(0);
  28443. indices.push(2);
  28444. indices.push(3);
  28445. this._indexBuffer = engine.createIndexBuffer(indices);
  28446. // Effects
  28447. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  28448. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  28449. }
  28450. Object.defineProperty(Layer.prototype, "onDispose", {
  28451. set: function (callback) {
  28452. if (this._onDisposeObserver) {
  28453. this.onDisposeObservable.remove(this._onDisposeObserver);
  28454. }
  28455. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28456. },
  28457. enumerable: true,
  28458. configurable: true
  28459. });
  28460. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  28461. set: function (callback) {
  28462. if (this._onBeforeRenderObserver) {
  28463. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28464. }
  28465. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28466. },
  28467. enumerable: true,
  28468. configurable: true
  28469. });
  28470. Object.defineProperty(Layer.prototype, "onAfterRender", {
  28471. set: function (callback) {
  28472. if (this._onAfterRenderObserver) {
  28473. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28474. }
  28475. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28476. },
  28477. enumerable: true,
  28478. configurable: true
  28479. });
  28480. Layer.prototype.render = function () {
  28481. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  28482. // Check
  28483. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  28484. return;
  28485. var engine = this._scene.getEngine();
  28486. this.onBeforeRenderObservable.notifyObservers(this);
  28487. // Render
  28488. engine.enableEffect(currentEffect);
  28489. engine.setState(false);
  28490. // Texture
  28491. currentEffect.setTexture("textureSampler", this.texture);
  28492. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  28493. // Color
  28494. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  28495. // Scale / offset
  28496. currentEffect.setVector2("offset", this.offset);
  28497. currentEffect.setVector2("scale", this.scale);
  28498. // VBOs
  28499. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  28500. // Draw order
  28501. if (!this.alphaTest) {
  28502. engine.setAlphaMode(this.alphaBlendingMode);
  28503. engine.draw(true, 0, 6);
  28504. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28505. }
  28506. else {
  28507. engine.draw(true, 0, 6);
  28508. }
  28509. this.onAfterRenderObservable.notifyObservers(this);
  28510. };
  28511. Layer.prototype.dispose = function () {
  28512. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28513. if (vertexBuffer) {
  28514. vertexBuffer.dispose();
  28515. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28516. }
  28517. if (this._indexBuffer) {
  28518. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28519. this._indexBuffer = null;
  28520. }
  28521. if (this.texture) {
  28522. this.texture.dispose();
  28523. this.texture = null;
  28524. }
  28525. // Remove from scene
  28526. var index = this._scene.layers.indexOf(this);
  28527. this._scene.layers.splice(index, 1);
  28528. // Callback
  28529. this.onDisposeObservable.notifyObservers(this);
  28530. this.onDisposeObservable.clear();
  28531. this.onAfterRenderObservable.clear();
  28532. this.onBeforeRenderObservable.clear();
  28533. };
  28534. return Layer;
  28535. }());
  28536. BABYLON.Layer = Layer;
  28537. })(BABYLON || (BABYLON = {}));
  28538. //# sourceMappingURL=babylon.layer.js.map
  28539. var BABYLON;
  28540. (function (BABYLON) {
  28541. var Particle = (function () {
  28542. function Particle() {
  28543. this.position = BABYLON.Vector3.Zero();
  28544. this.direction = BABYLON.Vector3.Zero();
  28545. this.color = new BABYLON.Color4(0, 0, 0, 0);
  28546. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  28547. this.lifeTime = 1.0;
  28548. this.age = 0;
  28549. this.size = 0;
  28550. this.angle = 0;
  28551. this.angularSpeed = 0;
  28552. }
  28553. Particle.prototype.copyTo = function (other) {
  28554. other.position.copyFrom(this.position);
  28555. other.direction.copyFrom(this.direction);
  28556. other.color.copyFrom(this.color);
  28557. other.colorStep.copyFrom(this.colorStep);
  28558. other.lifeTime = this.lifeTime;
  28559. other.age = this.age;
  28560. other.size = this.size;
  28561. other.angle = this.angle;
  28562. other.angularSpeed = this.angularSpeed;
  28563. };
  28564. return Particle;
  28565. }());
  28566. BABYLON.Particle = Particle;
  28567. })(BABYLON || (BABYLON = {}));
  28568. //# sourceMappingURL=babylon.particle.js.map
  28569. var BABYLON;
  28570. (function (BABYLON) {
  28571. var randomNumber = function (min, max) {
  28572. if (min === max) {
  28573. return (min);
  28574. }
  28575. var random = Math.random();
  28576. return ((random * (max - min)) + min);
  28577. };
  28578. var ParticleSystem = (function () {
  28579. function ParticleSystem(name, capacity, scene, customEffect) {
  28580. var _this = this;
  28581. this.name = name;
  28582. // Members
  28583. this.animations = [];
  28584. this.renderingGroupId = 0;
  28585. this.emitter = null;
  28586. this.emitRate = 10;
  28587. this.manualEmitCount = -1;
  28588. this.updateSpeed = 0.01;
  28589. this.targetStopDuration = 0;
  28590. this.disposeOnStop = false;
  28591. this.minEmitPower = 1;
  28592. this.maxEmitPower = 1;
  28593. this.minLifeTime = 1;
  28594. this.maxLifeTime = 1;
  28595. this.minSize = 1;
  28596. this.maxSize = 1;
  28597. this.minAngularSpeed = 0;
  28598. this.maxAngularSpeed = 0;
  28599. this.layerMask = 0x0FFFFFFF;
  28600. /**
  28601. * An event triggered when the system is disposed.
  28602. * @type {BABYLON.Observable}
  28603. */
  28604. this.onDisposeObservable = new BABYLON.Observable();
  28605. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  28606. this.forceDepthWrite = false;
  28607. this.gravity = BABYLON.Vector3.Zero();
  28608. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  28609. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  28610. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  28611. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  28612. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28613. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28614. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  28615. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28616. this.particles = new Array();
  28617. this._stockParticles = new Array();
  28618. this._newPartsExcess = 0;
  28619. this._vertexBuffers = {};
  28620. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  28621. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  28622. this._scaledDirection = BABYLON.Vector3.Zero();
  28623. this._scaledGravity = BABYLON.Vector3.Zero();
  28624. this._currentRenderId = -1;
  28625. this._started = false;
  28626. this._stopped = false;
  28627. this._actualFrame = 0;
  28628. this.id = name;
  28629. this._capacity = capacity;
  28630. this._scene = scene;
  28631. this._customEffect = customEffect;
  28632. scene.particleSystems.push(this);
  28633. var indices = [];
  28634. var index = 0;
  28635. for (var count = 0; count < capacity; count++) {
  28636. indices.push(index);
  28637. indices.push(index + 1);
  28638. indices.push(index + 2);
  28639. indices.push(index);
  28640. indices.push(index + 2);
  28641. indices.push(index + 3);
  28642. index += 4;
  28643. }
  28644. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28645. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  28646. this._vertexData = new Float32Array(capacity * 11 * 4);
  28647. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  28648. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  28649. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  28650. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  28651. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28652. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28653. this._vertexBuffers["options"] = options;
  28654. // Default behaviors
  28655. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  28656. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  28657. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  28658. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  28659. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  28660. };
  28661. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  28662. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  28663. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  28664. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  28665. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  28666. };
  28667. this.updateFunction = function (particles) {
  28668. for (var index = 0; index < particles.length; index++) {
  28669. var particle = particles[index];
  28670. particle.age += _this._scaledUpdateSpeed;
  28671. if (particle.age >= particle.lifeTime) {
  28672. _this.recycleParticle(particle);
  28673. index--;
  28674. continue;
  28675. }
  28676. else {
  28677. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28678. particle.color.addInPlace(_this._scaledColorStep);
  28679. if (particle.color.a < 0)
  28680. particle.color.a = 0;
  28681. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28682. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28683. particle.position.addInPlace(_this._scaledDirection);
  28684. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28685. particle.direction.addInPlace(_this._scaledGravity);
  28686. }
  28687. }
  28688. };
  28689. }
  28690. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28691. set: function (callback) {
  28692. if (this._onDisposeObserver) {
  28693. this.onDisposeObservable.remove(this._onDisposeObserver);
  28694. }
  28695. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28696. },
  28697. enumerable: true,
  28698. configurable: true
  28699. });
  28700. ParticleSystem.prototype.recycleParticle = function (particle) {
  28701. var lastParticle = this.particles.pop();
  28702. if (lastParticle !== particle) {
  28703. lastParticle.copyTo(particle);
  28704. this._stockParticles.push(lastParticle);
  28705. }
  28706. };
  28707. ParticleSystem.prototype.getCapacity = function () {
  28708. return this._capacity;
  28709. };
  28710. ParticleSystem.prototype.isAlive = function () {
  28711. return this._alive;
  28712. };
  28713. ParticleSystem.prototype.isStarted = function () {
  28714. return this._started;
  28715. };
  28716. ParticleSystem.prototype.start = function () {
  28717. this._started = true;
  28718. this._stopped = false;
  28719. this._actualFrame = 0;
  28720. };
  28721. ParticleSystem.prototype.stop = function () {
  28722. this._stopped = true;
  28723. };
  28724. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28725. var offset = index * 11;
  28726. this._vertexData[offset] = particle.position.x;
  28727. this._vertexData[offset + 1] = particle.position.y;
  28728. this._vertexData[offset + 2] = particle.position.z;
  28729. this._vertexData[offset + 3] = particle.color.r;
  28730. this._vertexData[offset + 4] = particle.color.g;
  28731. this._vertexData[offset + 5] = particle.color.b;
  28732. this._vertexData[offset + 6] = particle.color.a;
  28733. this._vertexData[offset + 7] = particle.angle;
  28734. this._vertexData[offset + 8] = particle.size;
  28735. this._vertexData[offset + 9] = offsetX;
  28736. this._vertexData[offset + 10] = offsetY;
  28737. };
  28738. ParticleSystem.prototype._update = function (newParticles) {
  28739. // Update current
  28740. this._alive = this.particles.length > 0;
  28741. this.updateFunction(this.particles);
  28742. // Add new ones
  28743. var worldMatrix;
  28744. if (this.emitter.position) {
  28745. worldMatrix = this.emitter.getWorldMatrix();
  28746. }
  28747. else {
  28748. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28749. }
  28750. var particle;
  28751. for (var index = 0; index < newParticles; index++) {
  28752. if (this.particles.length === this._capacity) {
  28753. break;
  28754. }
  28755. if (this._stockParticles.length !== 0) {
  28756. particle = this._stockParticles.pop();
  28757. particle.age = 0;
  28758. }
  28759. else {
  28760. particle = new BABYLON.Particle();
  28761. }
  28762. this.particles.push(particle);
  28763. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28764. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28765. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28766. particle.size = randomNumber(this.minSize, this.maxSize);
  28767. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28768. this.startPositionFunction(worldMatrix, particle.position, particle);
  28769. var step = randomNumber(0, 1.0);
  28770. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28771. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28772. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28773. }
  28774. };
  28775. ParticleSystem.prototype._getEffect = function () {
  28776. if (this._customEffect) {
  28777. return this._customEffect;
  28778. }
  28779. ;
  28780. var defines = [];
  28781. if (this._scene.clipPlane) {
  28782. defines.push("#define CLIPPLANE");
  28783. }
  28784. // Effect
  28785. var join = defines.join("\n");
  28786. if (this._cachedDefines !== join) {
  28787. this._cachedDefines = join;
  28788. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28789. }
  28790. return this._effect;
  28791. };
  28792. ParticleSystem.prototype.animate = function () {
  28793. if (!this._started)
  28794. return;
  28795. var effect = this._getEffect();
  28796. // Check
  28797. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28798. return;
  28799. if (this._currentRenderId === this._scene.getRenderId()) {
  28800. return;
  28801. }
  28802. this._currentRenderId = this._scene.getRenderId();
  28803. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28804. // determine the number of particles we need to create
  28805. var newParticles;
  28806. if (this.manualEmitCount > -1) {
  28807. newParticles = this.manualEmitCount;
  28808. this._newPartsExcess = 0;
  28809. this.manualEmitCount = 0;
  28810. }
  28811. else {
  28812. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28813. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28814. }
  28815. if (this._newPartsExcess > 1.0) {
  28816. newParticles += this._newPartsExcess >> 0;
  28817. this._newPartsExcess -= this._newPartsExcess >> 0;
  28818. }
  28819. this._alive = false;
  28820. if (!this._stopped) {
  28821. this._actualFrame += this._scaledUpdateSpeed;
  28822. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28823. this.stop();
  28824. }
  28825. else {
  28826. newParticles = 0;
  28827. }
  28828. this._update(newParticles);
  28829. // Stopped?
  28830. if (this._stopped) {
  28831. if (!this._alive) {
  28832. this._started = false;
  28833. if (this.disposeOnStop) {
  28834. this._scene._toBeDisposed.push(this);
  28835. }
  28836. }
  28837. }
  28838. // Update VBO
  28839. var offset = 0;
  28840. for (var index = 0; index < this.particles.length; index++) {
  28841. var particle = this.particles[index];
  28842. this._appendParticleVertex(offset++, particle, 0, 0);
  28843. this._appendParticleVertex(offset++, particle, 1, 0);
  28844. this._appendParticleVertex(offset++, particle, 1, 1);
  28845. this._appendParticleVertex(offset++, particle, 0, 1);
  28846. }
  28847. this._vertexBuffer.update(this._vertexData);
  28848. };
  28849. ParticleSystem.prototype.render = function () {
  28850. var effect = this._getEffect();
  28851. // Check
  28852. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28853. return 0;
  28854. var engine = this._scene.getEngine();
  28855. // Render
  28856. engine.enableEffect(effect);
  28857. engine.setState(false);
  28858. var viewMatrix = this._scene.getViewMatrix();
  28859. effect.setTexture("diffuseSampler", this.particleTexture);
  28860. effect.setMatrix("view", viewMatrix);
  28861. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28862. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28863. if (this._scene.clipPlane) {
  28864. var clipPlane = this._scene.clipPlane;
  28865. var invView = viewMatrix.clone();
  28866. invView.invert();
  28867. effect.setMatrix("invView", invView);
  28868. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28869. }
  28870. // VBOs
  28871. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28872. // Draw order
  28873. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28874. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28875. }
  28876. else {
  28877. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28878. }
  28879. if (this.forceDepthWrite) {
  28880. engine.setDepthWrite(true);
  28881. }
  28882. engine.draw(true, 0, this.particles.length * 6);
  28883. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28884. return this.particles.length;
  28885. };
  28886. ParticleSystem.prototype.dispose = function () {
  28887. if (this._vertexBuffer) {
  28888. this._vertexBuffer.dispose();
  28889. this._vertexBuffer = null;
  28890. }
  28891. if (this._indexBuffer) {
  28892. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28893. this._indexBuffer = null;
  28894. }
  28895. if (this.particleTexture) {
  28896. this.particleTexture.dispose();
  28897. this.particleTexture = null;
  28898. }
  28899. // Remove from scene
  28900. var index = this._scene.particleSystems.indexOf(this);
  28901. this._scene.particleSystems.splice(index, 1);
  28902. // Callback
  28903. this.onDisposeObservable.notifyObservers(this);
  28904. this.onDisposeObservable.clear();
  28905. };
  28906. // Clone
  28907. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28908. var result = new ParticleSystem(name, this._capacity, this._scene);
  28909. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28910. if (newEmitter === undefined) {
  28911. newEmitter = this.emitter;
  28912. }
  28913. result.emitter = newEmitter;
  28914. if (this.particleTexture) {
  28915. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28916. }
  28917. result.start();
  28918. return result;
  28919. };
  28920. ParticleSystem.prototype.serialize = function () {
  28921. var serializationObject = {};
  28922. serializationObject.name = this.name;
  28923. serializationObject.id = this.id;
  28924. // Emitter
  28925. if (this.emitter.position) {
  28926. serializationObject.emitterId = this.emitter.id;
  28927. }
  28928. else {
  28929. serializationObject.emitter = this.emitter.asArray();
  28930. }
  28931. serializationObject.capacity = this.getCapacity();
  28932. if (this.particleTexture) {
  28933. serializationObject.textureName = this.particleTexture.name;
  28934. }
  28935. // Animations
  28936. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28937. // Particle system
  28938. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28939. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28940. serializationObject.minSize = this.minSize;
  28941. serializationObject.maxSize = this.maxSize;
  28942. serializationObject.minEmitPower = this.minEmitPower;
  28943. serializationObject.maxEmitPower = this.maxEmitPower;
  28944. serializationObject.minLifeTime = this.minLifeTime;
  28945. serializationObject.maxLifeTime = this.maxLifeTime;
  28946. serializationObject.emitRate = this.emitRate;
  28947. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28948. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28949. serializationObject.gravity = this.gravity.asArray();
  28950. serializationObject.direction1 = this.direction1.asArray();
  28951. serializationObject.direction2 = this.direction2.asArray();
  28952. serializationObject.color1 = this.color1.asArray();
  28953. serializationObject.color2 = this.color2.asArray();
  28954. serializationObject.colorDead = this.colorDead.asArray();
  28955. serializationObject.updateSpeed = this.updateSpeed;
  28956. serializationObject.targetStopDuration = this.targetStopDuration;
  28957. serializationObject.textureMask = this.textureMask.asArray();
  28958. serializationObject.blendMode = this.blendMode;
  28959. return serializationObject;
  28960. };
  28961. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28962. var name = parsedParticleSystem.name;
  28963. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28964. if (parsedParticleSystem.id) {
  28965. particleSystem.id = parsedParticleSystem.id;
  28966. }
  28967. // Texture
  28968. if (parsedParticleSystem.textureName) {
  28969. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28970. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28971. }
  28972. // Emitter
  28973. if (parsedParticleSystem.emitterId) {
  28974. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28975. }
  28976. else {
  28977. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28978. }
  28979. // Animations
  28980. if (parsedParticleSystem.animations) {
  28981. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28982. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28983. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28984. }
  28985. }
  28986. if (parsedParticleSystem.autoAnimate) {
  28987. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28988. }
  28989. // Particle system
  28990. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28991. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28992. particleSystem.minSize = parsedParticleSystem.minSize;
  28993. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28994. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28995. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28996. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28997. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28998. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28999. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  29000. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  29001. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  29002. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  29003. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  29004. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  29005. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  29006. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  29007. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  29008. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  29009. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  29010. particleSystem.blendMode = parsedParticleSystem.blendMode;
  29011. if (!parsedParticleSystem.preventAutoStart) {
  29012. particleSystem.start();
  29013. }
  29014. return particleSystem;
  29015. };
  29016. return ParticleSystem;
  29017. }());
  29018. // Statics
  29019. ParticleSystem.BLENDMODE_ONEONE = 0;
  29020. ParticleSystem.BLENDMODE_STANDARD = 1;
  29021. BABYLON.ParticleSystem = ParticleSystem;
  29022. })(BABYLON || (BABYLON = {}));
  29023. //# sourceMappingURL=babylon.particleSystem.js.map
  29024. var BABYLON;
  29025. (function (BABYLON) {
  29026. var AnimationRange = (function () {
  29027. function AnimationRange(name, from, to) {
  29028. this.name = name;
  29029. this.from = from;
  29030. this.to = to;
  29031. }
  29032. AnimationRange.prototype.clone = function () {
  29033. return new AnimationRange(this.name, this.from, this.to);
  29034. };
  29035. return AnimationRange;
  29036. }());
  29037. BABYLON.AnimationRange = AnimationRange;
  29038. /**
  29039. * Composed of a frame, and an action function
  29040. */
  29041. var AnimationEvent = (function () {
  29042. function AnimationEvent(frame, action, onlyOnce) {
  29043. this.frame = frame;
  29044. this.action = action;
  29045. this.onlyOnce = onlyOnce;
  29046. this.isDone = false;
  29047. }
  29048. return AnimationEvent;
  29049. }());
  29050. BABYLON.AnimationEvent = AnimationEvent;
  29051. var PathCursor = (function () {
  29052. function PathCursor(path) {
  29053. this.path = path;
  29054. this._onchange = new Array();
  29055. this.value = 0;
  29056. this.animations = new Array();
  29057. }
  29058. PathCursor.prototype.getPoint = function () {
  29059. var point = this.path.getPointAtLengthPosition(this.value);
  29060. return new BABYLON.Vector3(point.x, 0, point.y);
  29061. };
  29062. PathCursor.prototype.moveAhead = function (step) {
  29063. if (step === void 0) { step = 0.002; }
  29064. this.move(step);
  29065. return this;
  29066. };
  29067. PathCursor.prototype.moveBack = function (step) {
  29068. if (step === void 0) { step = 0.002; }
  29069. this.move(-step);
  29070. return this;
  29071. };
  29072. PathCursor.prototype.move = function (step) {
  29073. if (Math.abs(step) > 1) {
  29074. throw "step size should be less than 1.";
  29075. }
  29076. this.value += step;
  29077. this.ensureLimits();
  29078. this.raiseOnChange();
  29079. return this;
  29080. };
  29081. PathCursor.prototype.ensureLimits = function () {
  29082. while (this.value > 1) {
  29083. this.value -= 1;
  29084. }
  29085. while (this.value < 0) {
  29086. this.value += 1;
  29087. }
  29088. return this;
  29089. };
  29090. // used by animation engine
  29091. PathCursor.prototype.markAsDirty = function (propertyName) {
  29092. this.ensureLimits();
  29093. this.raiseOnChange();
  29094. return this;
  29095. };
  29096. PathCursor.prototype.raiseOnChange = function () {
  29097. var _this = this;
  29098. this._onchange.forEach(function (f) { return f(_this); });
  29099. return this;
  29100. };
  29101. PathCursor.prototype.onchange = function (f) {
  29102. this._onchange.push(f);
  29103. return this;
  29104. };
  29105. return PathCursor;
  29106. }());
  29107. BABYLON.PathCursor = PathCursor;
  29108. var Animation = (function () {
  29109. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29110. this.name = name;
  29111. this.targetProperty = targetProperty;
  29112. this.framePerSecond = framePerSecond;
  29113. this.dataType = dataType;
  29114. this.loopMode = loopMode;
  29115. this.enableBlending = enableBlending;
  29116. this._offsetsCache = {};
  29117. this._highLimitsCache = {};
  29118. this._stopped = false;
  29119. this._blendingFactor = 0;
  29120. // The set of event that will be linked to this animation
  29121. this._events = new Array();
  29122. this.allowMatricesInterpolation = false;
  29123. this.blendingSpeed = 0.01;
  29124. this._ranges = {};
  29125. this.targetPropertyPath = targetProperty.split(".");
  29126. this.dataType = dataType;
  29127. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29128. }
  29129. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29130. var dataType = undefined;
  29131. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29132. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29133. }
  29134. else if (from instanceof BABYLON.Quaternion) {
  29135. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29136. }
  29137. else if (from instanceof BABYLON.Vector3) {
  29138. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29139. }
  29140. else if (from instanceof BABYLON.Vector2) {
  29141. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29142. }
  29143. else if (from instanceof BABYLON.Color3) {
  29144. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29145. }
  29146. else if (from instanceof BABYLON.Size) {
  29147. dataType = Animation.ANIMATIONTYPE_SIZE;
  29148. }
  29149. if (dataType == undefined) {
  29150. return null;
  29151. }
  29152. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29153. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29154. animation.setKeys(keys);
  29155. if (easingFunction !== undefined) {
  29156. animation.setEasingFunction(easingFunction);
  29157. }
  29158. return animation;
  29159. };
  29160. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29161. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29162. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29163. };
  29164. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29165. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29166. node.animations.push(animation);
  29167. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29168. };
  29169. // Methods
  29170. /**
  29171. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29172. */
  29173. Animation.prototype.toString = function (fullDetails) {
  29174. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29175. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29176. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29177. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29178. if (fullDetails) {
  29179. ret += ", Ranges: {";
  29180. var first = true;
  29181. for (var name in this._ranges) {
  29182. if (first) {
  29183. ret += ", ";
  29184. first = false;
  29185. }
  29186. ret += name;
  29187. }
  29188. ret += "}";
  29189. }
  29190. return ret;
  29191. };
  29192. /**
  29193. * Add an event to this animation.
  29194. */
  29195. Animation.prototype.addEvent = function (event) {
  29196. this._events.push(event);
  29197. };
  29198. /**
  29199. * Remove all events found at the given frame
  29200. * @param frame
  29201. */
  29202. Animation.prototype.removeEvents = function (frame) {
  29203. for (var index = 0; index < this._events.length; index++) {
  29204. if (this._events[index].frame === frame) {
  29205. this._events.splice(index, 1);
  29206. index--;
  29207. }
  29208. }
  29209. };
  29210. Animation.prototype.createRange = function (name, from, to) {
  29211. // check name not already in use; could happen for bones after serialized
  29212. if (!this._ranges[name]) {
  29213. this._ranges[name] = new AnimationRange(name, from, to);
  29214. }
  29215. };
  29216. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29217. if (deleteFrames === void 0) { deleteFrames = true; }
  29218. if (this._ranges[name]) {
  29219. if (deleteFrames) {
  29220. var from = this._ranges[name].from;
  29221. var to = this._ranges[name].to;
  29222. // this loop MUST go high to low for multiple splices to work
  29223. for (var key = this._keys.length - 1; key >= 0; key--) {
  29224. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29225. this._keys.splice(key, 1);
  29226. }
  29227. }
  29228. }
  29229. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29230. }
  29231. };
  29232. Animation.prototype.getRange = function (name) {
  29233. return this._ranges[name];
  29234. };
  29235. Animation.prototype.reset = function () {
  29236. this._offsetsCache = {};
  29237. this._highLimitsCache = {};
  29238. this.currentFrame = 0;
  29239. this._blendingFactor = 0;
  29240. this._originalBlendValue = null;
  29241. };
  29242. Animation.prototype.isStopped = function () {
  29243. return this._stopped;
  29244. };
  29245. Animation.prototype.getKeys = function () {
  29246. return this._keys;
  29247. };
  29248. Animation.prototype.getHighestFrame = function () {
  29249. var ret = 0;
  29250. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29251. if (ret < this._keys[key].frame) {
  29252. ret = this._keys[key].frame;
  29253. }
  29254. }
  29255. return ret;
  29256. };
  29257. Animation.prototype.getEasingFunction = function () {
  29258. return this._easingFunction;
  29259. };
  29260. Animation.prototype.setEasingFunction = function (easingFunction) {
  29261. this._easingFunction = easingFunction;
  29262. };
  29263. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29264. return startValue + (endValue - startValue) * gradient;
  29265. };
  29266. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29267. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29268. };
  29269. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29270. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29271. };
  29272. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29273. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29274. };
  29275. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29276. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29277. };
  29278. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29279. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29280. };
  29281. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29282. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29283. };
  29284. Animation.prototype.clone = function () {
  29285. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29286. if (this._keys) {
  29287. clone.setKeys(this._keys);
  29288. }
  29289. if (this._ranges) {
  29290. clone._ranges = {};
  29291. for (var name in this._ranges) {
  29292. clone._ranges[name] = this._ranges[name].clone();
  29293. }
  29294. }
  29295. return clone;
  29296. };
  29297. Animation.prototype.setKeys = function (values) {
  29298. this._keys = values.slice(0);
  29299. this._offsetsCache = {};
  29300. this._highLimitsCache = {};
  29301. };
  29302. Animation.prototype._getKeyValue = function (value) {
  29303. if (typeof value === "function") {
  29304. return value();
  29305. }
  29306. return value;
  29307. };
  29308. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  29309. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  29310. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  29311. }
  29312. this.currentFrame = currentFrame;
  29313. // Try to get a hash to find the right key
  29314. 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));
  29315. if (this._keys[startKey].frame >= currentFrame) {
  29316. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  29317. startKey--;
  29318. }
  29319. }
  29320. for (var key = startKey; key < this._keys.length; key++) {
  29321. if (this._keys[key + 1].frame >= currentFrame) {
  29322. var startValue = this._getKeyValue(this._keys[key].value);
  29323. var endValue = this._getKeyValue(this._keys[key + 1].value);
  29324. // gradient : percent of currentFrame between the frame inf and the frame sup
  29325. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  29326. // check for easingFunction and correction of gradient
  29327. if (this._easingFunction != null) {
  29328. gradient = this._easingFunction.ease(gradient);
  29329. }
  29330. switch (this.dataType) {
  29331. // Float
  29332. case Animation.ANIMATIONTYPE_FLOAT:
  29333. switch (loopMode) {
  29334. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29335. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29336. return this.floatInterpolateFunction(startValue, endValue, gradient);
  29337. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29338. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  29339. }
  29340. break;
  29341. // Quaternion
  29342. case Animation.ANIMATIONTYPE_QUATERNION:
  29343. var quaternion = null;
  29344. switch (loopMode) {
  29345. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29346. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29347. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  29348. break;
  29349. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29350. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29351. break;
  29352. }
  29353. return quaternion;
  29354. // Vector3
  29355. case Animation.ANIMATIONTYPE_VECTOR3:
  29356. switch (loopMode) {
  29357. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29358. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29359. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  29360. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29361. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29362. }
  29363. // Vector2
  29364. case Animation.ANIMATIONTYPE_VECTOR2:
  29365. switch (loopMode) {
  29366. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29367. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29368. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  29369. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29370. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29371. }
  29372. // Size
  29373. case Animation.ANIMATIONTYPE_SIZE:
  29374. switch (loopMode) {
  29375. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29376. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29377. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  29378. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29379. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29380. }
  29381. // Color3
  29382. case Animation.ANIMATIONTYPE_COLOR3:
  29383. switch (loopMode) {
  29384. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29385. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29386. return this.color3InterpolateFunction(startValue, endValue, gradient);
  29387. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29388. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29389. }
  29390. // Matrix
  29391. case Animation.ANIMATIONTYPE_MATRIX:
  29392. switch (loopMode) {
  29393. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29394. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29395. if (this.allowMatricesInterpolation) {
  29396. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  29397. }
  29398. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29399. return startValue;
  29400. }
  29401. default:
  29402. break;
  29403. }
  29404. break;
  29405. }
  29406. }
  29407. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  29408. };
  29409. Animation.prototype.setValue = function (currentValue, blend) {
  29410. if (blend === void 0) { blend = false; }
  29411. // Set value
  29412. var path;
  29413. var destination;
  29414. if (this.targetPropertyPath.length > 1) {
  29415. var property = this._target[this.targetPropertyPath[0]];
  29416. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  29417. property = property[this.targetPropertyPath[index]];
  29418. }
  29419. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  29420. destination = property;
  29421. }
  29422. else {
  29423. path = this.targetPropertyPath[0];
  29424. destination = this._target;
  29425. }
  29426. // Blending
  29427. if (this.enableBlending && this._blendingFactor <= 1.0) {
  29428. if (!this._originalBlendValue) {
  29429. if (destination[path].clone) {
  29430. this._originalBlendValue = destination[path].clone();
  29431. }
  29432. else {
  29433. this._originalBlendValue = destination[path];
  29434. }
  29435. }
  29436. if (this._originalBlendValue.prototype) {
  29437. if (this._originalBlendValue.prototype.Lerp) {
  29438. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  29439. }
  29440. else {
  29441. destination[path] = currentValue;
  29442. }
  29443. }
  29444. else if (this._originalBlendValue.m) {
  29445. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  29446. }
  29447. else {
  29448. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  29449. }
  29450. this._blendingFactor += this.blendingSpeed;
  29451. }
  29452. else {
  29453. destination[path] = currentValue;
  29454. }
  29455. if (this._target.markAsDirty) {
  29456. this._target.markAsDirty(this.targetProperty);
  29457. }
  29458. };
  29459. Animation.prototype.goToFrame = function (frame) {
  29460. if (frame < this._keys[0].frame) {
  29461. frame = this._keys[0].frame;
  29462. }
  29463. else if (frame > this._keys[this._keys.length - 1].frame) {
  29464. frame = this._keys[this._keys.length - 1].frame;
  29465. }
  29466. var currentValue = this._interpolate(frame, 0, this.loopMode);
  29467. this.setValue(currentValue);
  29468. };
  29469. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  29470. if (blend === void 0) { blend = false; }
  29471. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  29472. this._stopped = true;
  29473. return false;
  29474. }
  29475. var returnValue = true;
  29476. // Adding a start key at frame 0 if missing
  29477. if (this._keys[0].frame !== 0) {
  29478. var newKey = { frame: 0, value: this._keys[0].value };
  29479. this._keys.splice(0, 0, newKey);
  29480. }
  29481. // Check limits
  29482. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  29483. from = this._keys[0].frame;
  29484. }
  29485. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  29486. to = this._keys[this._keys.length - 1].frame;
  29487. }
  29488. //to and from cannot be the same key
  29489. if (from === to) {
  29490. from++;
  29491. }
  29492. // Compute ratio
  29493. var range = to - from;
  29494. var offsetValue;
  29495. // ratio represents the frame delta between from and to
  29496. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  29497. var highLimitValue = 0;
  29498. if (ratio > range && !loop) {
  29499. returnValue = false;
  29500. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  29501. }
  29502. else {
  29503. // Get max value if required
  29504. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  29505. var keyOffset = to.toString() + from.toString();
  29506. if (!this._offsetsCache[keyOffset]) {
  29507. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29508. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29509. switch (this.dataType) {
  29510. // Float
  29511. case Animation.ANIMATIONTYPE_FLOAT:
  29512. this._offsetsCache[keyOffset] = toValue - fromValue;
  29513. break;
  29514. // Quaternion
  29515. case Animation.ANIMATIONTYPE_QUATERNION:
  29516. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29517. break;
  29518. // Vector3
  29519. case Animation.ANIMATIONTYPE_VECTOR3:
  29520. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29521. // Vector2
  29522. case Animation.ANIMATIONTYPE_VECTOR2:
  29523. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29524. // Size
  29525. case Animation.ANIMATIONTYPE_SIZE:
  29526. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29527. // Color3
  29528. case Animation.ANIMATIONTYPE_COLOR3:
  29529. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29530. default:
  29531. break;
  29532. }
  29533. this._highLimitsCache[keyOffset] = toValue;
  29534. }
  29535. highLimitValue = this._highLimitsCache[keyOffset];
  29536. offsetValue = this._offsetsCache[keyOffset];
  29537. }
  29538. }
  29539. if (offsetValue === undefined) {
  29540. switch (this.dataType) {
  29541. // Float
  29542. case Animation.ANIMATIONTYPE_FLOAT:
  29543. offsetValue = 0;
  29544. break;
  29545. // Quaternion
  29546. case Animation.ANIMATIONTYPE_QUATERNION:
  29547. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  29548. break;
  29549. // Vector3
  29550. case Animation.ANIMATIONTYPE_VECTOR3:
  29551. offsetValue = BABYLON.Vector3.Zero();
  29552. break;
  29553. // Vector2
  29554. case Animation.ANIMATIONTYPE_VECTOR2:
  29555. offsetValue = BABYLON.Vector2.Zero();
  29556. break;
  29557. // Size
  29558. case Animation.ANIMATIONTYPE_SIZE:
  29559. offsetValue = BABYLON.Size.Zero();
  29560. break;
  29561. // Color3
  29562. case Animation.ANIMATIONTYPE_COLOR3:
  29563. offsetValue = BABYLON.Color3.Black();
  29564. }
  29565. }
  29566. // Compute value
  29567. var repeatCount = (ratio / range) >> 0;
  29568. var currentFrame = returnValue ? from + ratio % range : to;
  29569. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29570. // Set value
  29571. this.setValue(currentValue);
  29572. // Check events
  29573. for (var index = 0; index < this._events.length; index++) {
  29574. if (currentFrame >= this._events[index].frame) {
  29575. var event = this._events[index];
  29576. if (!event.isDone) {
  29577. // If event should be done only once, remove it.
  29578. if (event.onlyOnce) {
  29579. this._events.splice(index, 1);
  29580. index--;
  29581. }
  29582. event.isDone = true;
  29583. event.action();
  29584. } // Don't do anything if the event has already be done.
  29585. }
  29586. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29587. // reset event, the animation is looping
  29588. this._events[index].isDone = false;
  29589. }
  29590. }
  29591. if (!returnValue) {
  29592. this._stopped = true;
  29593. }
  29594. return returnValue;
  29595. };
  29596. Animation.prototype.serialize = function () {
  29597. var serializationObject = {};
  29598. serializationObject.name = this.name;
  29599. serializationObject.property = this.targetProperty;
  29600. serializationObject.framePerSecond = this.framePerSecond;
  29601. serializationObject.dataType = this.dataType;
  29602. serializationObject.loopBehavior = this.loopMode;
  29603. var dataType = this.dataType;
  29604. serializationObject.keys = [];
  29605. var keys = this.getKeys();
  29606. for (var index = 0; index < keys.length; index++) {
  29607. var animationKey = keys[index];
  29608. var key = {};
  29609. key.frame = animationKey.frame;
  29610. switch (dataType) {
  29611. case Animation.ANIMATIONTYPE_FLOAT:
  29612. key.values = [animationKey.value];
  29613. break;
  29614. case Animation.ANIMATIONTYPE_QUATERNION:
  29615. case Animation.ANIMATIONTYPE_MATRIX:
  29616. case Animation.ANIMATIONTYPE_VECTOR3:
  29617. case Animation.ANIMATIONTYPE_COLOR3:
  29618. key.values = animationKey.value.asArray();
  29619. break;
  29620. }
  29621. serializationObject.keys.push(key);
  29622. }
  29623. serializationObject.ranges = [];
  29624. for (var name in this._ranges) {
  29625. var range = {};
  29626. range.name = name;
  29627. range.from = this._ranges[name].from;
  29628. range.to = this._ranges[name].to;
  29629. serializationObject.ranges.push(range);
  29630. }
  29631. return serializationObject;
  29632. };
  29633. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29634. get: function () {
  29635. return Animation._ANIMATIONTYPE_FLOAT;
  29636. },
  29637. enumerable: true,
  29638. configurable: true
  29639. });
  29640. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29641. get: function () {
  29642. return Animation._ANIMATIONTYPE_VECTOR3;
  29643. },
  29644. enumerable: true,
  29645. configurable: true
  29646. });
  29647. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29648. get: function () {
  29649. return Animation._ANIMATIONTYPE_VECTOR2;
  29650. },
  29651. enumerable: true,
  29652. configurable: true
  29653. });
  29654. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29655. get: function () {
  29656. return Animation._ANIMATIONTYPE_SIZE;
  29657. },
  29658. enumerable: true,
  29659. configurable: true
  29660. });
  29661. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29662. get: function () {
  29663. return Animation._ANIMATIONTYPE_QUATERNION;
  29664. },
  29665. enumerable: true,
  29666. configurable: true
  29667. });
  29668. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29669. get: function () {
  29670. return Animation._ANIMATIONTYPE_MATRIX;
  29671. },
  29672. enumerable: true,
  29673. configurable: true
  29674. });
  29675. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29676. get: function () {
  29677. return Animation._ANIMATIONTYPE_COLOR3;
  29678. },
  29679. enumerable: true,
  29680. configurable: true
  29681. });
  29682. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29683. get: function () {
  29684. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29685. },
  29686. enumerable: true,
  29687. configurable: true
  29688. });
  29689. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29690. get: function () {
  29691. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29692. },
  29693. enumerable: true,
  29694. configurable: true
  29695. });
  29696. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29697. get: function () {
  29698. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29699. },
  29700. enumerable: true,
  29701. configurable: true
  29702. });
  29703. Animation.Parse = function (parsedAnimation) {
  29704. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29705. var dataType = parsedAnimation.dataType;
  29706. var keys = [];
  29707. var data;
  29708. var index;
  29709. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29710. var key = parsedAnimation.keys[index];
  29711. switch (dataType) {
  29712. case Animation.ANIMATIONTYPE_FLOAT:
  29713. data = key.values[0];
  29714. break;
  29715. case Animation.ANIMATIONTYPE_QUATERNION:
  29716. data = BABYLON.Quaternion.FromArray(key.values);
  29717. break;
  29718. case Animation.ANIMATIONTYPE_MATRIX:
  29719. data = BABYLON.Matrix.FromArray(key.values);
  29720. break;
  29721. case Animation.ANIMATIONTYPE_COLOR3:
  29722. data = BABYLON.Color3.FromArray(key.values);
  29723. break;
  29724. case Animation.ANIMATIONTYPE_VECTOR3:
  29725. default:
  29726. data = BABYLON.Vector3.FromArray(key.values);
  29727. break;
  29728. }
  29729. keys.push({
  29730. frame: key.frame,
  29731. value: data
  29732. });
  29733. }
  29734. animation.setKeys(keys);
  29735. if (parsedAnimation.ranges) {
  29736. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29737. data = parsedAnimation.ranges[index];
  29738. animation.createRange(data.name, data.from, data.to);
  29739. }
  29740. }
  29741. return animation;
  29742. };
  29743. Animation.AppendSerializedAnimations = function (source, destination) {
  29744. if (source.animations) {
  29745. destination.animations = [];
  29746. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29747. var animation = source.animations[animationIndex];
  29748. destination.animations.push(animation.serialize());
  29749. }
  29750. }
  29751. };
  29752. return Animation;
  29753. }());
  29754. // Statics
  29755. Animation._ANIMATIONTYPE_FLOAT = 0;
  29756. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29757. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29758. Animation._ANIMATIONTYPE_MATRIX = 3;
  29759. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29760. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29761. Animation._ANIMATIONTYPE_SIZE = 6;
  29762. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29763. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29764. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29765. BABYLON.Animation = Animation;
  29766. })(BABYLON || (BABYLON = {}));
  29767. //# sourceMappingURL=babylon.animation.js.map
  29768. var BABYLON;
  29769. (function (BABYLON) {
  29770. var Animatable = (function () {
  29771. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29772. if (fromFrame === void 0) { fromFrame = 0; }
  29773. if (toFrame === void 0) { toFrame = 100; }
  29774. if (loopAnimation === void 0) { loopAnimation = false; }
  29775. if (speedRatio === void 0) { speedRatio = 1.0; }
  29776. this.target = target;
  29777. this.fromFrame = fromFrame;
  29778. this.toFrame = toFrame;
  29779. this.loopAnimation = loopAnimation;
  29780. this.speedRatio = speedRatio;
  29781. this.onAnimationEnd = onAnimationEnd;
  29782. this._animations = new Array();
  29783. this._paused = false;
  29784. this.animationStarted = false;
  29785. if (animations) {
  29786. this.appendAnimations(target, animations);
  29787. }
  29788. this._scene = scene;
  29789. scene._activeAnimatables.push(this);
  29790. }
  29791. // Methods
  29792. Animatable.prototype.getAnimations = function () {
  29793. return this._animations;
  29794. };
  29795. Animatable.prototype.appendAnimations = function (target, animations) {
  29796. for (var index = 0; index < animations.length; index++) {
  29797. var animation = animations[index];
  29798. animation._target = target;
  29799. this._animations.push(animation);
  29800. }
  29801. };
  29802. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29803. var animations = this._animations;
  29804. for (var index = 0; index < animations.length; index++) {
  29805. if (animations[index].targetProperty === property) {
  29806. return animations[index];
  29807. }
  29808. }
  29809. return null;
  29810. };
  29811. Animatable.prototype.reset = function () {
  29812. var animations = this._animations;
  29813. for (var index = 0; index < animations.length; index++) {
  29814. animations[index].reset();
  29815. }
  29816. this._localDelayOffset = null;
  29817. this._pausedDelay = null;
  29818. };
  29819. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29820. var animations = this._animations;
  29821. for (var index = 0; index < animations.length; index++) {
  29822. animations[index].enableBlending = true;
  29823. animations[index].blendingSpeed = blendingSpeed;
  29824. }
  29825. };
  29826. Animatable.prototype.disableBlending = function () {
  29827. var animations = this._animations;
  29828. for (var index = 0; index < animations.length; index++) {
  29829. animations[index].enableBlending = false;
  29830. }
  29831. };
  29832. Animatable.prototype.goToFrame = function (frame) {
  29833. var animations = this._animations;
  29834. if (animations[0]) {
  29835. var fps = animations[0].framePerSecond;
  29836. var currentFrame = animations[0].currentFrame;
  29837. var adjustTime = frame - currentFrame;
  29838. var delay = adjustTime * 1000 / fps;
  29839. this._localDelayOffset -= delay;
  29840. }
  29841. for (var index = 0; index < animations.length; index++) {
  29842. animations[index].goToFrame(frame);
  29843. }
  29844. };
  29845. Animatable.prototype.pause = function () {
  29846. if (this._paused) {
  29847. return;
  29848. }
  29849. this._paused = true;
  29850. };
  29851. Animatable.prototype.restart = function () {
  29852. this._paused = false;
  29853. };
  29854. Animatable.prototype.stop = function (animationName) {
  29855. var index = this._scene._activeAnimatables.indexOf(this);
  29856. if (index > -1) {
  29857. var animations = this._animations;
  29858. var numberOfAnimationsStopped = 0;
  29859. for (var index = animations.length - 1; index >= 0; index--) {
  29860. if (typeof animationName === "string" && animations[index].name != animationName) {
  29861. continue;
  29862. }
  29863. animations[index].reset();
  29864. animations.splice(index, 1);
  29865. numberOfAnimationsStopped++;
  29866. }
  29867. if (animations.length == numberOfAnimationsStopped) {
  29868. this._scene._activeAnimatables.splice(index, 1);
  29869. if (this.onAnimationEnd) {
  29870. this.onAnimationEnd();
  29871. }
  29872. }
  29873. }
  29874. };
  29875. Animatable.prototype._animate = function (delay) {
  29876. if (this._paused) {
  29877. this.animationStarted = false;
  29878. if (!this._pausedDelay) {
  29879. this._pausedDelay = delay;
  29880. }
  29881. return true;
  29882. }
  29883. if (!this._localDelayOffset) {
  29884. this._localDelayOffset = delay;
  29885. }
  29886. else if (this._pausedDelay) {
  29887. this._localDelayOffset += delay - this._pausedDelay;
  29888. this._pausedDelay = null;
  29889. }
  29890. // Animating
  29891. var running = false;
  29892. var animations = this._animations;
  29893. var index;
  29894. for (index = 0; index < animations.length; index++) {
  29895. var animation = animations[index];
  29896. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29897. running = running || isRunning;
  29898. }
  29899. this.animationStarted = running;
  29900. if (!running) {
  29901. // Remove from active animatables
  29902. index = this._scene._activeAnimatables.indexOf(this);
  29903. this._scene._activeAnimatables.splice(index, 1);
  29904. }
  29905. if (!running && this.onAnimationEnd) {
  29906. this.onAnimationEnd();
  29907. this.onAnimationEnd = null;
  29908. }
  29909. return running;
  29910. };
  29911. return Animatable;
  29912. }());
  29913. BABYLON.Animatable = Animatable;
  29914. })(BABYLON || (BABYLON = {}));
  29915. //# sourceMappingURL=babylon.animatable.js.map
  29916. var BABYLON;
  29917. (function (BABYLON) {
  29918. var EasingFunction = (function () {
  29919. function EasingFunction() {
  29920. // Properties
  29921. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29922. }
  29923. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29924. get: function () {
  29925. return EasingFunction._EASINGMODE_EASEIN;
  29926. },
  29927. enumerable: true,
  29928. configurable: true
  29929. });
  29930. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29931. get: function () {
  29932. return EasingFunction._EASINGMODE_EASEOUT;
  29933. },
  29934. enumerable: true,
  29935. configurable: true
  29936. });
  29937. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29938. get: function () {
  29939. return EasingFunction._EASINGMODE_EASEINOUT;
  29940. },
  29941. enumerable: true,
  29942. configurable: true
  29943. });
  29944. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29945. var n = Math.min(Math.max(easingMode, 0), 2);
  29946. this._easingMode = n;
  29947. };
  29948. EasingFunction.prototype.getEasingMode = function () {
  29949. return this._easingMode;
  29950. };
  29951. EasingFunction.prototype.easeInCore = function (gradient) {
  29952. throw new Error('You must implement this method');
  29953. };
  29954. EasingFunction.prototype.ease = function (gradient) {
  29955. switch (this._easingMode) {
  29956. case EasingFunction.EASINGMODE_EASEIN:
  29957. return this.easeInCore(gradient);
  29958. case EasingFunction.EASINGMODE_EASEOUT:
  29959. return (1 - this.easeInCore(1 - gradient));
  29960. }
  29961. if (gradient >= 0.5) {
  29962. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29963. }
  29964. return (this.easeInCore(gradient * 2) * 0.5);
  29965. };
  29966. return EasingFunction;
  29967. }());
  29968. //Statics
  29969. EasingFunction._EASINGMODE_EASEIN = 0;
  29970. EasingFunction._EASINGMODE_EASEOUT = 1;
  29971. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29972. BABYLON.EasingFunction = EasingFunction;
  29973. var CircleEase = (function (_super) {
  29974. __extends(CircleEase, _super);
  29975. function CircleEase() {
  29976. return _super.apply(this, arguments) || this;
  29977. }
  29978. CircleEase.prototype.easeInCore = function (gradient) {
  29979. gradient = Math.max(0, Math.min(1, gradient));
  29980. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29981. };
  29982. return CircleEase;
  29983. }(EasingFunction));
  29984. BABYLON.CircleEase = CircleEase;
  29985. var BackEase = (function (_super) {
  29986. __extends(BackEase, _super);
  29987. function BackEase(amplitude) {
  29988. if (amplitude === void 0) { amplitude = 1; }
  29989. var _this = _super.call(this) || this;
  29990. _this.amplitude = amplitude;
  29991. return _this;
  29992. }
  29993. BackEase.prototype.easeInCore = function (gradient) {
  29994. var num = Math.max(0, this.amplitude);
  29995. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29996. };
  29997. return BackEase;
  29998. }(EasingFunction));
  29999. BABYLON.BackEase = BackEase;
  30000. var BounceEase = (function (_super) {
  30001. __extends(BounceEase, _super);
  30002. function BounceEase(bounces, bounciness) {
  30003. if (bounces === void 0) { bounces = 3; }
  30004. if (bounciness === void 0) { bounciness = 2; }
  30005. var _this = _super.call(this) || this;
  30006. _this.bounces = bounces;
  30007. _this.bounciness = bounciness;
  30008. return _this;
  30009. }
  30010. BounceEase.prototype.easeInCore = function (gradient) {
  30011. var y = Math.max(0.0, this.bounces);
  30012. var bounciness = this.bounciness;
  30013. if (bounciness <= 1.0) {
  30014. bounciness = 1.001;
  30015. }
  30016. var num9 = Math.pow(bounciness, y);
  30017. var num5 = 1.0 - bounciness;
  30018. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30019. var num15 = gradient * num4;
  30020. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30021. var num3 = Math.floor(num65);
  30022. var num13 = num3 + 1.0;
  30023. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30024. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30025. var num7 = (num8 + num12) * 0.5;
  30026. var num6 = gradient - num7;
  30027. var num2 = num7 - num8;
  30028. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30029. };
  30030. return BounceEase;
  30031. }(EasingFunction));
  30032. BABYLON.BounceEase = BounceEase;
  30033. var CubicEase = (function (_super) {
  30034. __extends(CubicEase, _super);
  30035. function CubicEase() {
  30036. return _super.apply(this, arguments) || this;
  30037. }
  30038. CubicEase.prototype.easeInCore = function (gradient) {
  30039. return (gradient * gradient * gradient);
  30040. };
  30041. return CubicEase;
  30042. }(EasingFunction));
  30043. BABYLON.CubicEase = CubicEase;
  30044. var ElasticEase = (function (_super) {
  30045. __extends(ElasticEase, _super);
  30046. function ElasticEase(oscillations, springiness) {
  30047. if (oscillations === void 0) { oscillations = 3; }
  30048. if (springiness === void 0) { springiness = 3; }
  30049. var _this = _super.call(this) || this;
  30050. _this.oscillations = oscillations;
  30051. _this.springiness = springiness;
  30052. return _this;
  30053. }
  30054. ElasticEase.prototype.easeInCore = function (gradient) {
  30055. var num2;
  30056. var num3 = Math.max(0.0, this.oscillations);
  30057. var num = Math.max(0.0, this.springiness);
  30058. if (num == 0) {
  30059. num2 = gradient;
  30060. }
  30061. else {
  30062. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30063. }
  30064. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30065. };
  30066. return ElasticEase;
  30067. }(EasingFunction));
  30068. BABYLON.ElasticEase = ElasticEase;
  30069. var ExponentialEase = (function (_super) {
  30070. __extends(ExponentialEase, _super);
  30071. function ExponentialEase(exponent) {
  30072. if (exponent === void 0) { exponent = 2; }
  30073. var _this = _super.call(this) || this;
  30074. _this.exponent = exponent;
  30075. return _this;
  30076. }
  30077. ExponentialEase.prototype.easeInCore = function (gradient) {
  30078. if (this.exponent <= 0) {
  30079. return gradient;
  30080. }
  30081. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30082. };
  30083. return ExponentialEase;
  30084. }(EasingFunction));
  30085. BABYLON.ExponentialEase = ExponentialEase;
  30086. var PowerEase = (function (_super) {
  30087. __extends(PowerEase, _super);
  30088. function PowerEase(power) {
  30089. if (power === void 0) { power = 2; }
  30090. var _this = _super.call(this) || this;
  30091. _this.power = power;
  30092. return _this;
  30093. }
  30094. PowerEase.prototype.easeInCore = function (gradient) {
  30095. var y = Math.max(0.0, this.power);
  30096. return Math.pow(gradient, y);
  30097. };
  30098. return PowerEase;
  30099. }(EasingFunction));
  30100. BABYLON.PowerEase = PowerEase;
  30101. var QuadraticEase = (function (_super) {
  30102. __extends(QuadraticEase, _super);
  30103. function QuadraticEase() {
  30104. return _super.apply(this, arguments) || this;
  30105. }
  30106. QuadraticEase.prototype.easeInCore = function (gradient) {
  30107. return (gradient * gradient);
  30108. };
  30109. return QuadraticEase;
  30110. }(EasingFunction));
  30111. BABYLON.QuadraticEase = QuadraticEase;
  30112. var QuarticEase = (function (_super) {
  30113. __extends(QuarticEase, _super);
  30114. function QuarticEase() {
  30115. return _super.apply(this, arguments) || this;
  30116. }
  30117. QuarticEase.prototype.easeInCore = function (gradient) {
  30118. return (gradient * gradient * gradient * gradient);
  30119. };
  30120. return QuarticEase;
  30121. }(EasingFunction));
  30122. BABYLON.QuarticEase = QuarticEase;
  30123. var QuinticEase = (function (_super) {
  30124. __extends(QuinticEase, _super);
  30125. function QuinticEase() {
  30126. return _super.apply(this, arguments) || this;
  30127. }
  30128. QuinticEase.prototype.easeInCore = function (gradient) {
  30129. return (gradient * gradient * gradient * gradient * gradient);
  30130. };
  30131. return QuinticEase;
  30132. }(EasingFunction));
  30133. BABYLON.QuinticEase = QuinticEase;
  30134. var SineEase = (function (_super) {
  30135. __extends(SineEase, _super);
  30136. function SineEase() {
  30137. return _super.apply(this, arguments) || this;
  30138. }
  30139. SineEase.prototype.easeInCore = function (gradient) {
  30140. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30141. };
  30142. return SineEase;
  30143. }(EasingFunction));
  30144. BABYLON.SineEase = SineEase;
  30145. var BezierCurveEase = (function (_super) {
  30146. __extends(BezierCurveEase, _super);
  30147. function BezierCurveEase(x1, y1, x2, y2) {
  30148. if (x1 === void 0) { x1 = 0; }
  30149. if (y1 === void 0) { y1 = 0; }
  30150. if (x2 === void 0) { x2 = 1; }
  30151. if (y2 === void 0) { y2 = 1; }
  30152. var _this = _super.call(this) || this;
  30153. _this.x1 = x1;
  30154. _this.y1 = y1;
  30155. _this.x2 = x2;
  30156. _this.y2 = y2;
  30157. return _this;
  30158. }
  30159. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30160. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30161. };
  30162. return BezierCurveEase;
  30163. }(EasingFunction));
  30164. BABYLON.BezierCurveEase = BezierCurveEase;
  30165. })(BABYLON || (BABYLON = {}));
  30166. //# sourceMappingURL=babylon.easing.js.map
  30167. var BABYLON;
  30168. (function (BABYLON) {
  30169. var Bone = (function (_super) {
  30170. __extends(Bone, _super);
  30171. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30172. var _this = _super.call(this, name, skeleton.getScene()) || this;
  30173. _this.name = name;
  30174. _this.children = new Array();
  30175. _this.animations = new Array();
  30176. _this._worldTransform = new BABYLON.Matrix();
  30177. _this._absoluteTransform = new BABYLON.Matrix();
  30178. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30179. _this._scaleMatrix = BABYLON.Matrix.Identity();
  30180. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30181. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30182. _this._scalingDeterminant = 1;
  30183. _this._syncScaleVector = function () {
  30184. var lm = this.getLocalMatrix();
  30185. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30186. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30187. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30188. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30189. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30190. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30191. this._scaleVector.x = xs * Math.sqrt(xsq);
  30192. this._scaleVector.y = ys * Math.sqrt(ysq);
  30193. this._scaleVector.z = zs * Math.sqrt(zsq);
  30194. if (this._parent) {
  30195. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30196. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30197. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30198. }
  30199. 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);
  30200. };
  30201. _this._skeleton = skeleton;
  30202. _this._matrix = matrix;
  30203. _this._baseMatrix = matrix;
  30204. _this._restPose = restPose ? restPose : matrix.clone();
  30205. skeleton.bones.push(_this);
  30206. if (parentBone) {
  30207. _this._parent = parentBone;
  30208. parentBone.children.push(_this);
  30209. }
  30210. else {
  30211. _this._parent = null;
  30212. }
  30213. _this._updateDifferenceMatrix();
  30214. if (_this.getAbsoluteTransform().determinant() < 0) {
  30215. _this._scalingDeterminant *= -1;
  30216. }
  30217. return _this;
  30218. }
  30219. // Members
  30220. Bone.prototype.getParent = function () {
  30221. return this._parent;
  30222. };
  30223. Bone.prototype.getLocalMatrix = function () {
  30224. return this._matrix;
  30225. };
  30226. Bone.prototype.getBaseMatrix = function () {
  30227. return this._baseMatrix;
  30228. };
  30229. Bone.prototype.getRestPose = function () {
  30230. return this._restPose;
  30231. };
  30232. Bone.prototype.returnToRest = function () {
  30233. this.updateMatrix(this._restPose.clone());
  30234. };
  30235. Bone.prototype.getWorldMatrix = function () {
  30236. return this._worldTransform;
  30237. };
  30238. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30239. return this._invertedAbsoluteTransform;
  30240. };
  30241. Bone.prototype.getAbsoluteTransform = function () {
  30242. return this._absoluteTransform;
  30243. };
  30244. // Methods
  30245. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30246. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30247. this._baseMatrix = matrix.clone();
  30248. this._matrix = matrix.clone();
  30249. this._skeleton._markAsDirty();
  30250. if (updateDifferenceMatrix) {
  30251. this._updateDifferenceMatrix();
  30252. }
  30253. };
  30254. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30255. if (!rootMatrix) {
  30256. rootMatrix = this._baseMatrix;
  30257. }
  30258. if (this._parent) {
  30259. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30260. }
  30261. else {
  30262. this._absoluteTransform.copyFrom(rootMatrix);
  30263. }
  30264. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  30265. for (var index = 0; index < this.children.length; index++) {
  30266. this.children[index]._updateDifferenceMatrix();
  30267. }
  30268. };
  30269. Bone.prototype.markAsDirty = function () {
  30270. this._currentRenderId++;
  30271. this._skeleton._markAsDirty();
  30272. };
  30273. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  30274. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30275. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  30276. // all animation may be coming from a library skeleton, so may need to create animation
  30277. if (this.animations.length === 0) {
  30278. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  30279. this.animations[0].setKeys([]);
  30280. }
  30281. // get animation info / verify there is such a range from the source bone
  30282. var sourceRange = source.animations[0].getRange(rangeName);
  30283. if (!sourceRange) {
  30284. return false;
  30285. }
  30286. var from = sourceRange.from;
  30287. var to = sourceRange.to;
  30288. var sourceKeys = source.animations[0].getKeys();
  30289. // rescaling prep
  30290. var sourceBoneLength = source.length;
  30291. var sourceParent = source.getParent();
  30292. var parent = this.getParent();
  30293. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  30294. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  30295. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  30296. var destKeys = this.animations[0].getKeys();
  30297. // loop vars declaration
  30298. var orig;
  30299. var origTranslation;
  30300. var mat;
  30301. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  30302. orig = sourceKeys[key];
  30303. if (orig.frame >= from && orig.frame <= to) {
  30304. if (rescaleAsRequired) {
  30305. mat = orig.value.clone();
  30306. // scale based on parent ratio, when bone has parent
  30307. if (parentScalingReqd) {
  30308. origTranslation = mat.getTranslation();
  30309. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  30310. }
  30311. else if (dimensionsScalingReqd) {
  30312. origTranslation = mat.getTranslation();
  30313. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  30314. }
  30315. else {
  30316. mat = orig.value;
  30317. }
  30318. }
  30319. else {
  30320. mat = orig.value;
  30321. }
  30322. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  30323. }
  30324. }
  30325. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  30326. return true;
  30327. };
  30328. Bone.prototype.translate = function (vec, space, mesh) {
  30329. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30330. var lm = this.getLocalMatrix();
  30331. if (space == BABYLON.Space.LOCAL) {
  30332. lm.m[12] += vec.x;
  30333. lm.m[13] += vec.y;
  30334. lm.m[14] += vec.z;
  30335. }
  30336. else {
  30337. this._skeleton.computeAbsoluteTransforms();
  30338. var tmat = BABYLON.Tmp.Matrix[0];
  30339. var tvec = BABYLON.Tmp.Vector3[0];
  30340. if (mesh) {
  30341. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30342. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30343. }
  30344. else {
  30345. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30346. }
  30347. tmat.m[12] = 0;
  30348. tmat.m[13] = 0;
  30349. tmat.m[14] = 0;
  30350. tmat.invert();
  30351. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  30352. lm.m[12] += tvec.x;
  30353. lm.m[13] += tvec.y;
  30354. lm.m[14] += tvec.z;
  30355. }
  30356. this.markAsDirty();
  30357. };
  30358. Bone.prototype.setPosition = function (position, space, mesh) {
  30359. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30360. var lm = this.getLocalMatrix();
  30361. if (space == BABYLON.Space.LOCAL) {
  30362. lm.m[12] = position.x;
  30363. lm.m[13] = position.y;
  30364. lm.m[14] = position.z;
  30365. }
  30366. else {
  30367. this._skeleton.computeAbsoluteTransforms();
  30368. var tmat = BABYLON.Tmp.Matrix[0];
  30369. var vec = BABYLON.Tmp.Vector3[0];
  30370. if (mesh) {
  30371. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30372. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30373. }
  30374. else {
  30375. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30376. }
  30377. tmat.invert();
  30378. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  30379. lm.m[12] = vec.x;
  30380. lm.m[13] = vec.y;
  30381. lm.m[14] = vec.z;
  30382. }
  30383. this.markAsDirty();
  30384. };
  30385. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  30386. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  30387. };
  30388. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  30389. if (scaleChildren === void 0) { scaleChildren = false; }
  30390. if (this.animations[0] && !this.animations[0].isStopped()) {
  30391. if (!scaleChildren) {
  30392. this._negateScaleChildren.x = 1 / x;
  30393. this._negateScaleChildren.y = 1 / y;
  30394. this._negateScaleChildren.z = 1 / z;
  30395. }
  30396. this._syncScaleVector();
  30397. }
  30398. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  30399. };
  30400. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  30401. if (scaleChildren === void 0) { scaleChildren = false; }
  30402. var locMat = this.getLocalMatrix();
  30403. var origLocMat = BABYLON.Tmp.Matrix[0];
  30404. origLocMat.copyFrom(locMat);
  30405. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  30406. origLocMatInv.copyFrom(origLocMat);
  30407. origLocMatInv.invert();
  30408. var scaleMat = BABYLON.Tmp.Matrix[2];
  30409. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  30410. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  30411. this._scaleVector.x *= x;
  30412. this._scaleVector.y *= y;
  30413. this._scaleVector.z *= z;
  30414. locMat.multiplyToRef(origLocMatInv, locMat);
  30415. locMat.multiplyToRef(scaleMat, locMat);
  30416. locMat.multiplyToRef(origLocMat, locMat);
  30417. var parent = this.getParent();
  30418. if (parent) {
  30419. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  30420. }
  30421. else {
  30422. this.getAbsoluteTransform().copyFrom(locMat);
  30423. }
  30424. var len = this.children.length;
  30425. scaleMat.invert();
  30426. for (var i = 0; i < len; i++) {
  30427. var child = this.children[i];
  30428. var cm = child.getLocalMatrix();
  30429. cm.multiplyToRef(scaleMat, cm);
  30430. var lm = child.getLocalMatrix();
  30431. lm.m[12] *= x;
  30432. lm.m[13] *= y;
  30433. lm.m[14] *= z;
  30434. }
  30435. this.computeAbsoluteTransforms();
  30436. if (scaleChildren) {
  30437. for (var i = 0; i < len; i++) {
  30438. this.children[i].scale(x, y, z, scaleChildren);
  30439. }
  30440. }
  30441. this.markAsDirty();
  30442. };
  30443. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  30444. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30445. var rotMat = BABYLON.Tmp.Matrix[0];
  30446. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  30447. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30448. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30449. rotMatInv.multiplyToRef(rotMat, rotMat);
  30450. this._rotateWithMatrix(rotMat, space, mesh);
  30451. };
  30452. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  30453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30454. var rmat = BABYLON.Tmp.Matrix[0];
  30455. rmat.m[12] = 0;
  30456. rmat.m[13] = 0;
  30457. rmat.m[14] = 0;
  30458. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  30459. this._rotateWithMatrix(rmat, space, mesh);
  30460. };
  30461. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  30462. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30463. var rotMat = BABYLON.Tmp.Matrix[0];
  30464. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  30465. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30466. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30467. rotMatInv.multiplyToRef(rotMat, rotMat);
  30468. this._rotateWithMatrix(rotMat, space, mesh);
  30469. };
  30470. Bone.prototype.setRotation = function (rotation, space, mesh) {
  30471. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30472. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  30473. };
  30474. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  30475. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30476. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30477. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30478. var rotMat = BABYLON.Tmp.Matrix[1];
  30479. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  30480. rotMatInv.multiplyToRef(rotMat, rotMat);
  30481. this._rotateWithMatrix(rotMat, space, mesh);
  30482. };
  30483. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  30484. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30485. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30486. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30487. var rotMat2 = BABYLON.Tmp.Matrix[1];
  30488. rotMat2.copyFrom(rotMat);
  30489. rotMatInv.multiplyToRef(rotMat, rotMat2);
  30490. this._rotateWithMatrix(rotMat2, space, mesh);
  30491. };
  30492. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  30493. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30494. var lmat = this.getLocalMatrix();
  30495. var lx = lmat.m[12];
  30496. var ly = lmat.m[13];
  30497. var lz = lmat.m[14];
  30498. var parent = this.getParent();
  30499. var parentScale = BABYLON.Tmp.Matrix[3];
  30500. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  30501. if (parent) {
  30502. if (space == BABYLON.Space.WORLD) {
  30503. if (mesh) {
  30504. parentScale.copyFrom(mesh.getWorldMatrix());
  30505. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  30506. }
  30507. else {
  30508. parentScale.copyFrom(parent.getAbsoluteTransform());
  30509. }
  30510. }
  30511. else {
  30512. parentScale = parent._scaleMatrix;
  30513. }
  30514. parentScaleInv.copyFrom(parentScale);
  30515. parentScaleInv.invert();
  30516. lmat.multiplyToRef(parentScale, lmat);
  30517. lmat.multiplyToRef(rmat, lmat);
  30518. lmat.multiplyToRef(parentScaleInv, lmat);
  30519. }
  30520. else {
  30521. if (space == BABYLON.Space.WORLD && mesh) {
  30522. parentScale.copyFrom(mesh.getWorldMatrix());
  30523. parentScaleInv.copyFrom(parentScale);
  30524. parentScaleInv.invert();
  30525. lmat.multiplyToRef(parentScale, lmat);
  30526. lmat.multiplyToRef(rmat, lmat);
  30527. lmat.multiplyToRef(parentScaleInv, lmat);
  30528. }
  30529. else {
  30530. lmat.multiplyToRef(rmat, lmat);
  30531. }
  30532. }
  30533. lmat.m[12] = lx;
  30534. lmat.m[13] = ly;
  30535. lmat.m[14] = lz;
  30536. this.computeAbsoluteTransforms();
  30537. this.markAsDirty();
  30538. };
  30539. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  30540. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30541. if (space == BABYLON.Space.WORLD) {
  30542. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30543. scaleMatrix.copyFrom(this._scaleMatrix);
  30544. rotMatInv.copyFrom(this.getAbsoluteTransform());
  30545. if (mesh) {
  30546. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  30547. var meshScale = BABYLON.Tmp.Matrix[3];
  30548. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  30549. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  30550. }
  30551. rotMatInv.invert();
  30552. scaleMatrix.m[0] *= this._scalingDeterminant;
  30553. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30554. }
  30555. else {
  30556. rotMatInv.copyFrom(this.getLocalMatrix());
  30557. rotMatInv.invert();
  30558. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30559. scaleMatrix.copyFrom(this._scaleMatrix);
  30560. if (this._parent) {
  30561. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  30562. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  30563. pscaleMatrix.invert();
  30564. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  30565. }
  30566. else {
  30567. scaleMatrix.m[0] *= this._scalingDeterminant;
  30568. }
  30569. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30570. }
  30571. };
  30572. Bone.prototype.getScale = function () {
  30573. return this._scaleVector.clone();
  30574. };
  30575. Bone.prototype.getScaleToRef = function (result) {
  30576. result.copyFrom(this._scaleVector);
  30577. };
  30578. Bone.prototype.getPosition = function (space, mesh) {
  30579. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30580. var pos = BABYLON.Vector3.Zero();
  30581. this.getPositionToRef(space, mesh, pos);
  30582. return pos;
  30583. };
  30584. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  30585. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30586. if (space == BABYLON.Space.LOCAL) {
  30587. var lm = this.getLocalMatrix();
  30588. result.x = lm.m[12];
  30589. result.y = lm.m[13];
  30590. result.z = lm.m[14];
  30591. }
  30592. else {
  30593. this._skeleton.computeAbsoluteTransforms();
  30594. var tmat = BABYLON.Tmp.Matrix[0];
  30595. if (mesh) {
  30596. tmat.copyFrom(this.getAbsoluteTransform());
  30597. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30598. }
  30599. else {
  30600. tmat = this.getAbsoluteTransform();
  30601. }
  30602. result.x = tmat.m[12];
  30603. result.y = tmat.m[13];
  30604. result.z = tmat.m[14];
  30605. }
  30606. };
  30607. Bone.prototype.getAbsolutePosition = function (mesh) {
  30608. var pos = BABYLON.Vector3.Zero();
  30609. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  30610. return pos;
  30611. };
  30612. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  30613. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  30614. };
  30615. Bone.prototype.computeAbsoluteTransforms = function () {
  30616. if (this._parent) {
  30617. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30618. }
  30619. else {
  30620. this._absoluteTransform.copyFrom(this._matrix);
  30621. var poseMatrix = this._skeleton.getPoseMatrix();
  30622. if (poseMatrix) {
  30623. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  30624. }
  30625. }
  30626. var children = this.children;
  30627. var len = children.length;
  30628. for (var i = 0; i < len; i++) {
  30629. children[i].computeAbsoluteTransforms();
  30630. }
  30631. };
  30632. Bone.prototype.getDirection = function (localAxis, mesh) {
  30633. var result = BABYLON.Vector3.Zero();
  30634. this.getDirectionToRef(localAxis, mesh, result);
  30635. return result;
  30636. };
  30637. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  30638. this._skeleton.computeAbsoluteTransforms();
  30639. var mat = BABYLON.Tmp.Matrix[0];
  30640. mat.copyFrom(this.getAbsoluteTransform());
  30641. if (mesh) {
  30642. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30643. }
  30644. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  30645. result.normalize();
  30646. };
  30647. Bone.prototype.getRotation = function (space, mesh) {
  30648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30649. var result = BABYLON.Vector3.Zero();
  30650. this.getRotationToRef(space, mesh, result);
  30651. return result;
  30652. };
  30653. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  30654. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30655. var quat = BABYLON.Tmp.Quaternion[0];
  30656. this.getRotationQuaternionToRef(space, mesh, quat);
  30657. quat.toEulerAnglesToRef(result);
  30658. };
  30659. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  30660. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30661. var result = BABYLON.Quaternion.Identity();
  30662. this.getRotationQuaternionToRef(space, mesh, result);
  30663. return result;
  30664. };
  30665. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  30666. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30667. if (space == BABYLON.Space.LOCAL) {
  30668. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30669. }
  30670. else {
  30671. var mat = BABYLON.Tmp.Matrix[0];
  30672. var amat = this.getAbsoluteTransform();
  30673. if (mesh) {
  30674. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30675. }
  30676. else {
  30677. mat.copyFrom(amat);
  30678. }
  30679. mat.m[0] *= this._scalingDeterminant;
  30680. mat.m[1] *= this._scalingDeterminant;
  30681. mat.m[2] *= this._scalingDeterminant;
  30682. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30683. }
  30684. };
  30685. Bone.prototype.getRotationMatrix = function (space, mesh) {
  30686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30687. var result = BABYLON.Matrix.Identity();
  30688. this.getRotationMatrixToRef(space, mesh, result);
  30689. return result;
  30690. };
  30691. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  30692. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30693. if (space == BABYLON.Space.LOCAL) {
  30694. this.getLocalMatrix().getRotationMatrixToRef(result);
  30695. }
  30696. else {
  30697. var mat = BABYLON.Tmp.Matrix[0];
  30698. var amat = this.getAbsoluteTransform();
  30699. if (mesh) {
  30700. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30701. }
  30702. else {
  30703. mat.copyFrom(amat);
  30704. }
  30705. mat.m[0] *= this._scalingDeterminant;
  30706. mat.m[1] *= this._scalingDeterminant;
  30707. mat.m[2] *= this._scalingDeterminant;
  30708. mat.getRotationMatrixToRef(result);
  30709. }
  30710. };
  30711. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  30712. var result = BABYLON.Vector3.Zero();
  30713. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  30714. return result;
  30715. };
  30716. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  30717. this._skeleton.computeAbsoluteTransforms();
  30718. var tmat = BABYLON.Tmp.Matrix[0];
  30719. if (mesh) {
  30720. tmat.copyFrom(this.getAbsoluteTransform());
  30721. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30722. }
  30723. else {
  30724. tmat = this.getAbsoluteTransform();
  30725. }
  30726. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30727. };
  30728. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  30729. var result = BABYLON.Vector3.Zero();
  30730. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  30731. return result;
  30732. };
  30733. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  30734. this._skeleton.computeAbsoluteTransforms();
  30735. var tmat = BABYLON.Tmp.Matrix[0];
  30736. tmat.copyFrom(this.getAbsoluteTransform());
  30737. if (mesh) {
  30738. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30739. }
  30740. tmat.invert();
  30741. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30742. };
  30743. return Bone;
  30744. }(BABYLON.Node));
  30745. BABYLON.Bone = Bone;
  30746. })(BABYLON || (BABYLON = {}));
  30747. //# sourceMappingURL=babylon.bone.js.map
  30748. var BABYLON;
  30749. (function (BABYLON) {
  30750. var BoneIKController = (function () {
  30751. function BoneIKController(mesh, bone, options) {
  30752. this.targetPosition = BABYLON.Vector3.Zero();
  30753. this.poleTargetPosition = BABYLON.Vector3.Zero();
  30754. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  30755. this.poleAngle = 0;
  30756. this.slerpAmount = 1;
  30757. this._bone1Quat = BABYLON.Quaternion.Identity();
  30758. this._bone1Mat = BABYLON.Matrix.Identity();
  30759. this._bone2Ang = Math.PI;
  30760. this._maxAngle = Math.PI;
  30761. this._tmpVec1 = BABYLON.Vector3.Zero();
  30762. this._tmpVec2 = BABYLON.Vector3.Zero();
  30763. this._tmpVec3 = BABYLON.Vector3.Zero();
  30764. this._tmpVec4 = BABYLON.Vector3.Zero();
  30765. this._tmpVec5 = BABYLON.Vector3.Zero();
  30766. this._tmpMat1 = BABYLON.Matrix.Identity();
  30767. this._tmpMat2 = BABYLON.Matrix.Identity();
  30768. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  30769. this._rightHandedSystem = false;
  30770. this._bendAxis = BABYLON.Vector3.Right();
  30771. this._slerping = false;
  30772. this._bone2 = bone;
  30773. this._bone1 = bone.getParent();
  30774. this.mesh = mesh;
  30775. if (bone.getAbsoluteTransform().determinant() > 0) {
  30776. this._rightHandedSystem = true;
  30777. this._bendAxis.x = 0;
  30778. this._bendAxis.y = 0;
  30779. this._bendAxis.z = 1;
  30780. }
  30781. if (this._bone1.length) {
  30782. var boneScale1 = this._bone1.getScale();
  30783. var boneScale2 = this._bone2.getScale();
  30784. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  30785. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  30786. }
  30787. else if (this._bone1.children[0]) {
  30788. mesh.computeWorldMatrix(true);
  30789. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  30790. var pos2 = this._bone2.getAbsolutePosition(mesh);
  30791. var pos3 = this._bone1.getAbsolutePosition(mesh);
  30792. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  30793. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  30794. }
  30795. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  30796. this.maxAngle = Math.PI;
  30797. if (options) {
  30798. if (options.targetMesh) {
  30799. this.targetMesh = options.targetMesh;
  30800. this.targetMesh.computeWorldMatrix(true);
  30801. }
  30802. if (options.poleTargetMesh) {
  30803. this.poleTargetMesh = options.poleTargetMesh;
  30804. this.poleTargetMesh.computeWorldMatrix(true);
  30805. }
  30806. else if (options.poleTargetBone) {
  30807. this.poleTargetBone = options.poleTargetBone;
  30808. }
  30809. else if (this._bone1.getParent()) {
  30810. this.poleTargetBone = this._bone1.getParent();
  30811. }
  30812. if (options.poleTargetLocalOffset) {
  30813. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  30814. }
  30815. if (options.poleAngle) {
  30816. this.poleAngle = options.poleAngle;
  30817. }
  30818. if (options.bendAxis) {
  30819. this._bendAxis.copyFrom(options.bendAxis);
  30820. }
  30821. if (options.maxAngle) {
  30822. this.maxAngle = options.maxAngle;
  30823. }
  30824. if (options.slerpAmount) {
  30825. this.slerpAmount = options.slerpAmount;
  30826. }
  30827. }
  30828. }
  30829. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  30830. get: function () {
  30831. return this._maxAngle;
  30832. },
  30833. set: function (value) {
  30834. this._setMaxAngle(value);
  30835. },
  30836. enumerable: true,
  30837. configurable: true
  30838. });
  30839. BoneIKController.prototype._setMaxAngle = function (ang) {
  30840. if (ang < 0) {
  30841. ang = 0;
  30842. }
  30843. if (ang > Math.PI || ang == undefined) {
  30844. ang = Math.PI;
  30845. }
  30846. this._maxAngle = ang;
  30847. var a = this._bone1Length;
  30848. var b = this._bone2Length;
  30849. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  30850. };
  30851. BoneIKController.prototype.update = function () {
  30852. var bone1 = this._bone1;
  30853. var target = this.targetPosition;
  30854. var poleTarget = this.poleTargetPosition;
  30855. var mat1 = this._tmpMat1;
  30856. var mat2 = this._tmpMat2;
  30857. if (this.targetMesh) {
  30858. target.copyFrom(this.targetMesh.getAbsolutePosition());
  30859. }
  30860. if (this.poleTargetBone) {
  30861. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  30862. }
  30863. else if (this.poleTargetMesh) {
  30864. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  30865. }
  30866. var bonePos = this._tmpVec1;
  30867. var zaxis = this._tmpVec2;
  30868. var xaxis = this._tmpVec3;
  30869. var yaxis = this._tmpVec4;
  30870. var upAxis = this._tmpVec5;
  30871. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  30872. poleTarget.subtractToRef(bonePos, upAxis);
  30873. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  30874. upAxis.y = 1;
  30875. }
  30876. else {
  30877. upAxis.normalize();
  30878. }
  30879. target.subtractToRef(bonePos, yaxis);
  30880. yaxis.normalize();
  30881. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  30882. zaxis.normalize();
  30883. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  30884. xaxis.normalize();
  30885. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30886. var a = this._bone1Length;
  30887. var b = this._bone2Length;
  30888. var c = BABYLON.Vector3.Distance(bonePos, target);
  30889. if (this._maxReach > 0) {
  30890. c = Math.min(this._maxReach, c);
  30891. }
  30892. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  30893. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  30894. if (acosa > 1) {
  30895. acosa = 1;
  30896. }
  30897. if (acosb > 1) {
  30898. acosb = 1;
  30899. }
  30900. if (acosa < -1) {
  30901. acosa = -1;
  30902. }
  30903. if (acosb < -1) {
  30904. acosb = -1;
  30905. }
  30906. var angA = Math.acos(acosa);
  30907. var angB = Math.acos(acosb);
  30908. var angC = -angA - angB;
  30909. if (this._rightHandedSystem) {
  30910. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  30911. mat2.multiplyToRef(mat1, mat1);
  30912. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  30913. mat2.multiplyToRef(mat1, mat1);
  30914. }
  30915. else {
  30916. this._tmpVec1.copyFrom(this._bendAxis);
  30917. this._tmpVec1.x *= -1;
  30918. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  30919. mat2.multiplyToRef(mat1, mat1);
  30920. }
  30921. if (this.poleAngle) {
  30922. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  30923. mat1.multiplyToRef(mat2, mat1);
  30924. }
  30925. if (this.slerpAmount < 1) {
  30926. if (!this._slerping) {
  30927. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  30928. }
  30929. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  30930. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  30931. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  30932. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  30933. this._slerping = true;
  30934. }
  30935. else {
  30936. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30937. this._bone1Mat.copyFrom(mat1);
  30938. this._slerping = false;
  30939. }
  30940. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  30941. this._bone2Ang = angC;
  30942. };
  30943. return BoneIKController;
  30944. }());
  30945. BABYLON.BoneIKController = BoneIKController;
  30946. })(BABYLON || (BABYLON = {}));
  30947. //# sourceMappingURL=babylon.boneIKController.js.map
  30948. var BABYLON;
  30949. (function (BABYLON) {
  30950. var BoneLookController = (function () {
  30951. function BoneLookController(mesh, bone, target, options) {
  30952. this.upAxis = BABYLON.Vector3.Up();
  30953. this.adjustYaw = 0;
  30954. this.adjustPitch = 0;
  30955. this.adjustRoll = 0;
  30956. this._tmpVec1 = BABYLON.Vector3.Zero();
  30957. this._tmpVec2 = BABYLON.Vector3.Zero();
  30958. this._tmpVec3 = BABYLON.Vector3.Zero();
  30959. this._tmpVec4 = BABYLON.Vector3.Zero();
  30960. this._tmpMat1 = BABYLON.Matrix.Identity();
  30961. this._tmpMat2 = BABYLON.Matrix.Identity();
  30962. this.mesh = mesh;
  30963. this.bone = bone;
  30964. this.target = target;
  30965. if (options) {
  30966. if (options.adjustYaw) {
  30967. this.adjustYaw = options.adjustYaw;
  30968. }
  30969. if (options.adjustPitch) {
  30970. this.adjustPitch = options.adjustPitch;
  30971. }
  30972. if (options.adjustRoll) {
  30973. this.adjustRoll = options.adjustRoll;
  30974. }
  30975. }
  30976. }
  30977. BoneLookController.prototype.update = function () {
  30978. var bone = this.bone;
  30979. var target = this.target;
  30980. var bonePos = this._tmpVec1;
  30981. var zaxis = this._tmpVec2;
  30982. var xaxis = this._tmpVec3;
  30983. var yaxis = this._tmpVec4;
  30984. var mat1 = this._tmpMat1;
  30985. var mat2 = this._tmpMat2;
  30986. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  30987. target.subtractToRef(bonePos, zaxis);
  30988. zaxis.normalize();
  30989. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  30990. xaxis.normalize();
  30991. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  30992. yaxis.normalize();
  30993. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30994. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  30995. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  30996. mat2.multiplyToRef(mat1, mat1);
  30997. }
  30998. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30999. };
  31000. return BoneLookController;
  31001. }());
  31002. BABYLON.BoneLookController = BoneLookController;
  31003. })(BABYLON || (BABYLON = {}));
  31004. //# sourceMappingURL=babylon.boneLookController.js.map
  31005. var BABYLON;
  31006. (function (BABYLON) {
  31007. var Skeleton = (function () {
  31008. function Skeleton(name, id, scene) {
  31009. this.name = name;
  31010. this.id = id;
  31011. this.bones = new Array();
  31012. this.needInitialSkinMatrix = false;
  31013. this._isDirty = true;
  31014. this._meshesWithPoseMatrix = new Array();
  31015. this._identity = BABYLON.Matrix.Identity();
  31016. this._ranges = {};
  31017. this._lastAbsoluteTransformsUpdateId = -1;
  31018. this.bones = [];
  31019. this._scene = scene;
  31020. scene.skeletons.push(this);
  31021. //make sure it will recalculate the matrix next time prepare is called.
  31022. this._isDirty = true;
  31023. }
  31024. // Members
  31025. Skeleton.prototype.getTransformMatrices = function (mesh) {
  31026. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  31027. return mesh._bonesTransformMatrices;
  31028. }
  31029. if (!this._transformMatrices) {
  31030. this.prepare();
  31031. }
  31032. return this._transformMatrices;
  31033. };
  31034. Skeleton.prototype.getScene = function () {
  31035. return this._scene;
  31036. };
  31037. // Methods
  31038. /**
  31039. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31040. */
  31041. Skeleton.prototype.toString = function (fullDetails) {
  31042. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  31043. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31044. if (fullDetails) {
  31045. ret += ", Ranges: {";
  31046. var first = true;
  31047. for (var name_1 in this._ranges) {
  31048. if (first) {
  31049. ret += ", ";
  31050. first = false;
  31051. }
  31052. ret += name_1;
  31053. }
  31054. ret += "}";
  31055. }
  31056. return ret;
  31057. };
  31058. /**
  31059. * Get bone's index searching by name
  31060. * @param {string} name is bone's name to search for
  31061. * @return {number} Indice of the bone. Returns -1 if not found
  31062. */
  31063. Skeleton.prototype.getBoneIndexByName = function (name) {
  31064. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  31065. if (this.bones[boneIndex].name === name) {
  31066. return boneIndex;
  31067. }
  31068. }
  31069. return -1;
  31070. };
  31071. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  31072. // check name not already in use
  31073. if (!this._ranges[name]) {
  31074. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  31075. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31076. if (this.bones[i].animations[0]) {
  31077. this.bones[i].animations[0].createRange(name, from, to);
  31078. }
  31079. }
  31080. }
  31081. };
  31082. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31083. if (deleteFrames === void 0) { deleteFrames = true; }
  31084. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31085. if (this.bones[i].animations[0]) {
  31086. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31087. }
  31088. }
  31089. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31090. };
  31091. Skeleton.prototype.getAnimationRange = function (name) {
  31092. return this._ranges[name];
  31093. };
  31094. /**
  31095. * Returns as an Array, all AnimationRanges defined on this skeleton
  31096. */
  31097. Skeleton.prototype.getAnimationRanges = function () {
  31098. var animationRanges = [];
  31099. var name;
  31100. var i = 0;
  31101. for (name in this._ranges) {
  31102. animationRanges[i] = this._ranges[name];
  31103. i++;
  31104. }
  31105. return animationRanges;
  31106. };
  31107. /**
  31108. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31109. */
  31110. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  31111. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31112. if (this._ranges[name] || !source.getAnimationRange(name)) {
  31113. return false;
  31114. }
  31115. var ret = true;
  31116. var frameOffset = this._getHighestAnimationFrame() + 1;
  31117. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  31118. var boneDict = {};
  31119. var sourceBones = source.bones;
  31120. var nBones;
  31121. var i;
  31122. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  31123. boneDict[sourceBones[i].name] = sourceBones[i];
  31124. }
  31125. if (this.bones.length !== sourceBones.length) {
  31126. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  31127. ret = false;
  31128. }
  31129. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  31130. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  31131. var boneName = this.bones[i].name;
  31132. var sourceBone = boneDict[boneName];
  31133. if (sourceBone) {
  31134. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  31135. }
  31136. else {
  31137. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  31138. ret = false;
  31139. }
  31140. }
  31141. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31142. var range = source.getAnimationRange(name);
  31143. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31144. return ret;
  31145. };
  31146. Skeleton.prototype.returnToRest = function () {
  31147. for (var index = 0; index < this.bones.length; index++) {
  31148. this.bones[index].returnToRest();
  31149. }
  31150. };
  31151. Skeleton.prototype._getHighestAnimationFrame = function () {
  31152. var ret = 0;
  31153. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31154. if (this.bones[i].animations[0]) {
  31155. var highest = this.bones[i].animations[0].getHighestFrame();
  31156. if (ret < highest) {
  31157. ret = highest;
  31158. }
  31159. }
  31160. }
  31161. return ret;
  31162. };
  31163. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31164. var range = this.getAnimationRange(name);
  31165. if (!range) {
  31166. return null;
  31167. }
  31168. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31169. };
  31170. Skeleton.prototype._markAsDirty = function () {
  31171. this._isDirty = true;
  31172. };
  31173. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31174. this._meshesWithPoseMatrix.push(mesh);
  31175. };
  31176. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31177. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31178. if (index > -1) {
  31179. this._meshesWithPoseMatrix.splice(index, 1);
  31180. }
  31181. };
  31182. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31183. for (var index = 0; index < this.bones.length; index++) {
  31184. var bone = this.bones[index];
  31185. var parentBone = bone.getParent();
  31186. if (parentBone) {
  31187. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31188. }
  31189. else {
  31190. if (initialSkinMatrix) {
  31191. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31192. }
  31193. else {
  31194. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31195. }
  31196. }
  31197. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31198. }
  31199. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31200. };
  31201. Skeleton.prototype.prepare = function () {
  31202. if (!this._isDirty) {
  31203. return;
  31204. }
  31205. if (this.needInitialSkinMatrix) {
  31206. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31207. var mesh = this._meshesWithPoseMatrix[index];
  31208. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31209. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31210. }
  31211. var poseMatrix = mesh.getPoseMatrix();
  31212. // Prepare bones
  31213. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31214. var bone = this.bones[boneIndex];
  31215. if (!bone.getParent()) {
  31216. var matrix = bone.getBaseMatrix();
  31217. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31218. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31219. }
  31220. }
  31221. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31222. }
  31223. }
  31224. else {
  31225. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31226. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31227. }
  31228. this._computeTransformMatrices(this._transformMatrices, null);
  31229. }
  31230. this._isDirty = false;
  31231. this._scene._activeBones.addCount(this.bones.length, false);
  31232. };
  31233. Skeleton.prototype.getAnimatables = function () {
  31234. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31235. this._animatables = [];
  31236. for (var index = 0; index < this.bones.length; index++) {
  31237. this._animatables.push(this.bones[index]);
  31238. }
  31239. }
  31240. return this._animatables;
  31241. };
  31242. Skeleton.prototype.clone = function (name, id) {
  31243. var result = new Skeleton(name, id || name, this._scene);
  31244. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31245. for (var index = 0; index < this.bones.length; index++) {
  31246. var source = this.bones[index];
  31247. var parentBone = null;
  31248. if (source.getParent()) {
  31249. var parentIndex = this.bones.indexOf(source.getParent());
  31250. parentBone = result.bones[parentIndex];
  31251. }
  31252. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31253. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31254. }
  31255. if (this._ranges) {
  31256. result._ranges = {};
  31257. for (var rangeName in this._ranges) {
  31258. result._ranges[rangeName] = this._ranges[rangeName].clone();
  31259. }
  31260. }
  31261. this._isDirty = true;
  31262. return result;
  31263. };
  31264. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  31265. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  31266. this.bones.forEach(function (bone) {
  31267. bone.animations.forEach(function (animation) {
  31268. animation.enableBlending = true;
  31269. animation.blendingSpeed = blendingSpeed;
  31270. });
  31271. });
  31272. };
  31273. Skeleton.prototype.dispose = function () {
  31274. this._meshesWithPoseMatrix = [];
  31275. // Animations
  31276. this.getScene().stopAnimation(this);
  31277. // Remove from scene
  31278. this.getScene().removeSkeleton(this);
  31279. };
  31280. Skeleton.prototype.serialize = function () {
  31281. var serializationObject = {};
  31282. serializationObject.name = this.name;
  31283. serializationObject.id = this.id;
  31284. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  31285. serializationObject.bones = [];
  31286. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31287. for (var index = 0; index < this.bones.length; index++) {
  31288. var bone = this.bones[index];
  31289. var serializedBone = {
  31290. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  31291. name: bone.name,
  31292. matrix: bone.getLocalMatrix().toArray(),
  31293. rest: bone.getRestPose().toArray()
  31294. };
  31295. serializationObject.bones.push(serializedBone);
  31296. if (bone.length) {
  31297. serializedBone.length = bone.length;
  31298. }
  31299. if (bone.animations && bone.animations.length > 0) {
  31300. serializedBone.animation = bone.animations[0].serialize();
  31301. }
  31302. serializationObject.ranges = [];
  31303. for (var name in this._ranges) {
  31304. var range = {};
  31305. range.name = name;
  31306. range.from = this._ranges[name].from;
  31307. range.to = this._ranges[name].to;
  31308. serializationObject.ranges.push(range);
  31309. }
  31310. }
  31311. return serializationObject;
  31312. };
  31313. Skeleton.Parse = function (parsedSkeleton, scene) {
  31314. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  31315. if (parsedSkeleton.dimensionsAtRest) {
  31316. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  31317. }
  31318. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  31319. var index;
  31320. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  31321. var parsedBone = parsedSkeleton.bones[index];
  31322. var parentBone = null;
  31323. if (parsedBone.parentBoneIndex > -1) {
  31324. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  31325. }
  31326. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  31327. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  31328. if (parsedBone.length) {
  31329. bone.length = parsedBone.length;
  31330. }
  31331. if (parsedBone.animation) {
  31332. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  31333. }
  31334. }
  31335. // placed after bones, so createAnimationRange can cascade down
  31336. if (parsedSkeleton.ranges) {
  31337. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  31338. var data = parsedSkeleton.ranges[index];
  31339. skeleton.createAnimationRange(data.name, data.from, data.to);
  31340. }
  31341. }
  31342. return skeleton;
  31343. };
  31344. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  31345. if (forceUpdate === void 0) { forceUpdate = false; }
  31346. var renderId = this._scene.getRenderId();
  31347. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  31348. this.bones[0].computeAbsoluteTransforms();
  31349. this._lastAbsoluteTransformsUpdateId = renderId;
  31350. }
  31351. };
  31352. Skeleton.prototype.getPoseMatrix = function () {
  31353. var poseMatrix;
  31354. if (this._meshesWithPoseMatrix.length > 0) {
  31355. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  31356. }
  31357. return poseMatrix;
  31358. };
  31359. return Skeleton;
  31360. }());
  31361. BABYLON.Skeleton = Skeleton;
  31362. })(BABYLON || (BABYLON = {}));
  31363. //# sourceMappingURL=babylon.skeleton.js.map
  31364. var BABYLON;
  31365. (function (BABYLON) {
  31366. var PostProcess = (function () {
  31367. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  31368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  31369. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31370. this.name = name;
  31371. this.width = -1;
  31372. this.height = -1;
  31373. /*
  31374. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  31375. Can only be used on a single postprocess or on the last one of a chain.
  31376. */
  31377. this.enablePixelPerfectMode = false;
  31378. this._reusable = false;
  31379. this._textures = new BABYLON.SmartArray(2);
  31380. this._currentRenderTextureInd = 0;
  31381. this._scaleRatio = new BABYLON.Vector2(1, 1);
  31382. // Events
  31383. /**
  31384. * An event triggered when the postprocess is activated.
  31385. * @type {BABYLON.Observable}
  31386. */
  31387. this.onActivateObservable = new BABYLON.Observable();
  31388. /**
  31389. * An event triggered when the postprocess changes its size.
  31390. * @type {BABYLON.Observable}
  31391. */
  31392. this.onSizeChangedObservable = new BABYLON.Observable();
  31393. /**
  31394. * An event triggered when the postprocess applies its effect.
  31395. * @type {BABYLON.Observable}
  31396. */
  31397. this.onApplyObservable = new BABYLON.Observable();
  31398. /**
  31399. * An event triggered before rendering the postprocess
  31400. * @type {BABYLON.Observable}
  31401. */
  31402. this.onBeforeRenderObservable = new BABYLON.Observable();
  31403. /**
  31404. * An event triggered after rendering the postprocess
  31405. * @type {BABYLON.Observable}
  31406. */
  31407. this.onAfterRenderObservable = new BABYLON.Observable();
  31408. if (camera != null) {
  31409. this._camera = camera;
  31410. this._scene = camera.getScene();
  31411. camera.attachPostProcess(this);
  31412. this._engine = this._scene.getEngine();
  31413. }
  31414. else {
  31415. this._engine = engine;
  31416. }
  31417. this._options = options;
  31418. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  31419. this._reusable = reusable || false;
  31420. this._textureType = textureType;
  31421. this._samplers = samplers || [];
  31422. this._samplers.push("textureSampler");
  31423. this._fragmentUrl = fragmentUrl;
  31424. this._parameters = parameters || [];
  31425. this._parameters.push("scale");
  31426. this.updateEffect(defines);
  31427. }
  31428. Object.defineProperty(PostProcess.prototype, "onActivate", {
  31429. set: function (callback) {
  31430. if (this._onActivateObserver) {
  31431. this.onActivateObservable.remove(this._onActivateObserver);
  31432. }
  31433. this._onActivateObserver = this.onActivateObservable.add(callback);
  31434. },
  31435. enumerable: true,
  31436. configurable: true
  31437. });
  31438. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  31439. set: function (callback) {
  31440. if (this._onSizeChangedObserver) {
  31441. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  31442. }
  31443. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  31444. },
  31445. enumerable: true,
  31446. configurable: true
  31447. });
  31448. Object.defineProperty(PostProcess.prototype, "onApply", {
  31449. set: function (callback) {
  31450. if (this._onApplyObserver) {
  31451. this.onApplyObservable.remove(this._onApplyObserver);
  31452. }
  31453. this._onApplyObserver = this.onApplyObservable.add(callback);
  31454. },
  31455. enumerable: true,
  31456. configurable: true
  31457. });
  31458. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  31459. set: function (callback) {
  31460. if (this._onBeforeRenderObserver) {
  31461. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31462. }
  31463. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31464. },
  31465. enumerable: true,
  31466. configurable: true
  31467. });
  31468. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  31469. set: function (callback) {
  31470. if (this._onAfterRenderObserver) {
  31471. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31472. }
  31473. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31474. },
  31475. enumerable: true,
  31476. configurable: true
  31477. });
  31478. PostProcess.prototype.updateEffect = function (defines) {
  31479. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  31480. };
  31481. PostProcess.prototype.isReusable = function () {
  31482. return this._reusable;
  31483. };
  31484. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  31485. PostProcess.prototype.markTextureDirty = function () {
  31486. this.width = -1;
  31487. };
  31488. PostProcess.prototype.activate = function (camera, sourceTexture) {
  31489. camera = camera || this._camera;
  31490. var scene = camera.getScene();
  31491. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  31492. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  31493. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  31494. var desiredWidth = this._options.width || requiredWidth;
  31495. var desiredHeight = this._options.height || requiredHeight;
  31496. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31497. if (!this._options.width) {
  31498. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  31499. }
  31500. if (!this._options.height) {
  31501. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  31502. }
  31503. }
  31504. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  31505. if (this._textures.length > 0) {
  31506. for (var i = 0; i < this._textures.length; i++) {
  31507. this._engine._releaseTexture(this._textures.data[i]);
  31508. }
  31509. this._textures.reset();
  31510. }
  31511. this.width = desiredWidth;
  31512. this.height = desiredHeight;
  31513. var textureSize = { width: this.width, height: this.height };
  31514. var textureOptions = {
  31515. generateMipMaps: false,
  31516. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  31517. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  31518. samplingMode: this.renderTargetSamplingMode,
  31519. type: this._textureType
  31520. };
  31521. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31522. if (this._reusable) {
  31523. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31524. }
  31525. this.onSizeChangedObservable.notifyObservers(this);
  31526. }
  31527. if (this.enablePixelPerfectMode) {
  31528. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  31529. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  31530. }
  31531. else {
  31532. this._scaleRatio.copyFromFloats(1, 1);
  31533. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  31534. }
  31535. this.onActivateObservable.notifyObservers(camera);
  31536. // Clear
  31537. if (this.clearColor) {
  31538. this._engine.clear(this.clearColor, true, true, true);
  31539. }
  31540. else {
  31541. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  31542. }
  31543. if (this._reusable) {
  31544. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  31545. }
  31546. };
  31547. Object.defineProperty(PostProcess.prototype, "isSupported", {
  31548. get: function () {
  31549. return this._effect.isSupported;
  31550. },
  31551. enumerable: true,
  31552. configurable: true
  31553. });
  31554. PostProcess.prototype.apply = function () {
  31555. // Check
  31556. if (!this._effect.isReady())
  31557. return null;
  31558. // States
  31559. this._engine.enableEffect(this._effect);
  31560. this._engine.setState(false);
  31561. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31562. this._engine.setDepthBuffer(false);
  31563. this._engine.setDepthWrite(false);
  31564. // Texture
  31565. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  31566. // Parameters
  31567. this._effect.setVector2("scale", this._scaleRatio);
  31568. this.onApplyObservable.notifyObservers(this._effect);
  31569. return this._effect;
  31570. };
  31571. PostProcess.prototype.dispose = function (camera) {
  31572. camera = camera || this._camera;
  31573. if (this._textures.length > 0) {
  31574. for (var i = 0; i < this._textures.length; i++) {
  31575. this._engine._releaseTexture(this._textures.data[i]);
  31576. }
  31577. this._textures.reset();
  31578. }
  31579. if (!camera) {
  31580. return;
  31581. }
  31582. camera.detachPostProcess(this);
  31583. var index = camera._postProcesses.indexOf(this);
  31584. if (index === 0 && camera._postProcesses.length > 0) {
  31585. this._camera._postProcesses[0].markTextureDirty();
  31586. }
  31587. this.onActivateObservable.clear();
  31588. this.onAfterRenderObservable.clear();
  31589. this.onApplyObservable.clear();
  31590. this.onBeforeRenderObservable.clear();
  31591. this.onSizeChangedObservable.clear();
  31592. };
  31593. return PostProcess;
  31594. }());
  31595. BABYLON.PostProcess = PostProcess;
  31596. })(BABYLON || (BABYLON = {}));
  31597. //# sourceMappingURL=babylon.postProcess.js.map
  31598. var BABYLON;
  31599. (function (BABYLON) {
  31600. var PostProcessManager = (function () {
  31601. function PostProcessManager(scene) {
  31602. this._vertexBuffers = {};
  31603. this._scene = scene;
  31604. }
  31605. PostProcessManager.prototype._prepareBuffers = function () {
  31606. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31607. return;
  31608. }
  31609. // VBO
  31610. var vertices = [];
  31611. vertices.push(1, 1);
  31612. vertices.push(-1, 1);
  31613. vertices.push(-1, -1);
  31614. vertices.push(1, -1);
  31615. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31616. // Indices
  31617. var indices = [];
  31618. indices.push(0);
  31619. indices.push(1);
  31620. indices.push(2);
  31621. indices.push(0);
  31622. indices.push(2);
  31623. indices.push(3);
  31624. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31625. };
  31626. // Methods
  31627. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  31628. var postProcesses = this._scene.activeCamera._postProcesses;
  31629. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31630. return false;
  31631. }
  31632. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  31633. return true;
  31634. };
  31635. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  31636. var engine = this._scene.getEngine();
  31637. for (var index = 0; index < postProcesses.length; index++) {
  31638. if (index < postProcesses.length - 1) {
  31639. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31640. }
  31641. else {
  31642. if (targetTexture) {
  31643. engine.bindFramebuffer(targetTexture);
  31644. }
  31645. else {
  31646. engine.restoreDefaultFramebuffer();
  31647. }
  31648. }
  31649. var pp = postProcesses[index];
  31650. var effect = pp.apply();
  31651. if (effect) {
  31652. pp.onBeforeRenderObservable.notifyObservers(effect);
  31653. // VBOs
  31654. this._prepareBuffers();
  31655. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31656. // Draw order
  31657. engine.draw(true, 0, 6);
  31658. pp.onAfterRenderObservable.notifyObservers(effect);
  31659. }
  31660. }
  31661. // Restore depth buffer
  31662. engine.setDepthBuffer(true);
  31663. engine.setDepthWrite(true);
  31664. };
  31665. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  31666. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  31667. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31668. return;
  31669. }
  31670. var engine = this._scene.getEngine();
  31671. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31672. if (index < len - 1) {
  31673. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31674. }
  31675. else {
  31676. if (targetTexture) {
  31677. engine.bindFramebuffer(targetTexture, faceIndex);
  31678. }
  31679. else {
  31680. engine.restoreDefaultFramebuffer();
  31681. }
  31682. }
  31683. if (doNotPresent) {
  31684. break;
  31685. }
  31686. var pp = postProcesses[index];
  31687. var effect = pp.apply();
  31688. if (effect) {
  31689. pp.onBeforeRenderObservable.notifyObservers(effect);
  31690. // VBOs
  31691. this._prepareBuffers();
  31692. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31693. // Draw order
  31694. engine.draw(true, 0, 6);
  31695. pp.onAfterRenderObservable.notifyObservers(effect);
  31696. }
  31697. }
  31698. // Restore depth buffer
  31699. engine.setDepthBuffer(true);
  31700. engine.setDepthWrite(true);
  31701. };
  31702. PostProcessManager.prototype.dispose = function () {
  31703. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31704. if (buffer) {
  31705. buffer.dispose();
  31706. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31707. }
  31708. if (this._indexBuffer) {
  31709. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31710. this._indexBuffer = null;
  31711. }
  31712. };
  31713. return PostProcessManager;
  31714. }());
  31715. BABYLON.PostProcessManager = PostProcessManager;
  31716. })(BABYLON || (BABYLON = {}));
  31717. //# sourceMappingURL=babylon.postProcessManager.js.map
  31718. var BABYLON;
  31719. (function (BABYLON) {
  31720. var PassPostProcess = (function (_super) {
  31721. __extends(PassPostProcess, _super);
  31722. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  31723. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  31724. }
  31725. return PassPostProcess;
  31726. }(BABYLON.PostProcess));
  31727. BABYLON.PassPostProcess = PassPostProcess;
  31728. })(BABYLON || (BABYLON = {}));
  31729. //# sourceMappingURL=babylon.passPostProcess.js.map
  31730. var BABYLON;
  31731. (function (BABYLON) {
  31732. /**
  31733. * This is a holder class for the physics joint created by the physics plugin.
  31734. * It holds a set of functions to control the underlying joint.
  31735. */
  31736. var PhysicsJoint = (function () {
  31737. function PhysicsJoint(type, jointData) {
  31738. this.type = type;
  31739. this.jointData = jointData;
  31740. jointData.nativeParams = jointData.nativeParams || {};
  31741. }
  31742. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  31743. get: function () {
  31744. return this._physicsJoint;
  31745. },
  31746. set: function (newJoint) {
  31747. if (this._physicsJoint) {
  31748. }
  31749. this._physicsJoint = newJoint;
  31750. },
  31751. enumerable: true,
  31752. configurable: true
  31753. });
  31754. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  31755. set: function (physicsPlugin) {
  31756. this._physicsPlugin = physicsPlugin;
  31757. },
  31758. enumerable: true,
  31759. configurable: true
  31760. });
  31761. /**
  31762. * Execute a function that is physics-plugin specific.
  31763. * @param {Function} func the function that will be executed.
  31764. * It accepts two parameters: the physics world and the physics joint.
  31765. */
  31766. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  31767. func(this._physicsPlugin.world, this._physicsJoint);
  31768. };
  31769. return PhysicsJoint;
  31770. }());
  31771. //TODO check if the native joints are the same
  31772. //Joint Types
  31773. PhysicsJoint.DistanceJoint = 0;
  31774. PhysicsJoint.HingeJoint = 1;
  31775. PhysicsJoint.BallAndSocketJoint = 2;
  31776. PhysicsJoint.WheelJoint = 3;
  31777. PhysicsJoint.SliderJoint = 4;
  31778. //OIMO
  31779. PhysicsJoint.PrismaticJoint = 5;
  31780. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  31781. PhysicsJoint.UniversalJoint = 6;
  31782. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  31783. //Cannon
  31784. //Similar to a Ball-Joint. Different in params
  31785. PhysicsJoint.PointToPointJoint = 8;
  31786. //Cannon only at the moment
  31787. PhysicsJoint.SpringJoint = 9;
  31788. PhysicsJoint.LockJoint = 10;
  31789. BABYLON.PhysicsJoint = PhysicsJoint;
  31790. /**
  31791. * A class representing a physics distance joint.
  31792. */
  31793. var DistanceJoint = (function (_super) {
  31794. __extends(DistanceJoint, _super);
  31795. function DistanceJoint(jointData) {
  31796. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  31797. }
  31798. /**
  31799. * Update the predefined distance.
  31800. */
  31801. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  31802. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  31803. };
  31804. return DistanceJoint;
  31805. }(PhysicsJoint));
  31806. BABYLON.DistanceJoint = DistanceJoint;
  31807. var MotorEnabledJoint = (function (_super) {
  31808. __extends(MotorEnabledJoint, _super);
  31809. function MotorEnabledJoint(type, jointData) {
  31810. return _super.call(this, type, jointData) || this;
  31811. }
  31812. /**
  31813. * Set the motor values.
  31814. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31815. * @param {number} force the force to apply
  31816. * @param {number} maxForce max force for this motor.
  31817. */
  31818. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  31819. this._physicsPlugin.setMotor(this, force, maxForce);
  31820. };
  31821. /**
  31822. * Set the motor's limits.
  31823. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31824. */
  31825. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31826. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31827. };
  31828. return MotorEnabledJoint;
  31829. }(PhysicsJoint));
  31830. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  31831. /**
  31832. * This class represents a single hinge physics joint
  31833. */
  31834. var HingeJoint = (function (_super) {
  31835. __extends(HingeJoint, _super);
  31836. function HingeJoint(jointData) {
  31837. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  31838. }
  31839. /**
  31840. * Set the motor values.
  31841. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31842. * @param {number} force the force to apply
  31843. * @param {number} maxForce max force for this motor.
  31844. */
  31845. HingeJoint.prototype.setMotor = function (force, maxForce) {
  31846. this._physicsPlugin.setMotor(this, force, maxForce);
  31847. };
  31848. /**
  31849. * Set the motor's limits.
  31850. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31851. */
  31852. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31853. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31854. };
  31855. return HingeJoint;
  31856. }(MotorEnabledJoint));
  31857. BABYLON.HingeJoint = HingeJoint;
  31858. /**
  31859. * This class represents a dual hinge physics joint (same as wheel joint)
  31860. */
  31861. var Hinge2Joint = (function (_super) {
  31862. __extends(Hinge2Joint, _super);
  31863. function Hinge2Joint(jointData) {
  31864. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  31865. }
  31866. /**
  31867. * Set the motor values.
  31868. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31869. * @param {number} force the force to apply
  31870. * @param {number} maxForce max force for this motor.
  31871. * @param {motorIndex} the motor's index, 0 or 1.
  31872. */
  31873. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  31874. if (motorIndex === void 0) { motorIndex = 0; }
  31875. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  31876. };
  31877. /**
  31878. * Set the motor limits.
  31879. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31880. * @param {number} upperLimit the upper limit
  31881. * @param {number} lowerLimit lower limit
  31882. * @param {motorIndex} the motor's index, 0 or 1.
  31883. */
  31884. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  31885. if (motorIndex === void 0) { motorIndex = 0; }
  31886. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  31887. };
  31888. return Hinge2Joint;
  31889. }(MotorEnabledJoint));
  31890. BABYLON.Hinge2Joint = Hinge2Joint;
  31891. })(BABYLON || (BABYLON = {}));
  31892. //# sourceMappingURL=babylon.physicsJoint.js.map
  31893. var BABYLON;
  31894. (function (BABYLON) {
  31895. var PhysicsImpostor = (function () {
  31896. function PhysicsImpostor(object, type, _options, _scene) {
  31897. if (_options === void 0) { _options = { mass: 0 }; }
  31898. var _this = this;
  31899. this.object = object;
  31900. this.type = type;
  31901. this._options = _options;
  31902. this._scene = _scene;
  31903. this._bodyUpdateRequired = false;
  31904. this._onBeforePhysicsStepCallbacks = new Array();
  31905. this._onAfterPhysicsStepCallbacks = new Array();
  31906. this._onPhysicsCollideCallbacks = [];
  31907. this._deltaPosition = BABYLON.Vector3.Zero();
  31908. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  31909. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  31910. /**
  31911. * this function is executed by the physics engine.
  31912. */
  31913. this.beforeStep = function () {
  31914. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  31915. //conjugate deltaRotation
  31916. if (_this._deltaRotationConjugated) {
  31917. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  31918. }
  31919. else {
  31920. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  31921. }
  31922. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  31923. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  31924. func(_this);
  31925. });
  31926. };
  31927. /**
  31928. * this function is executed by the physics engine.
  31929. */
  31930. this.afterStep = function () {
  31931. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  31932. func(_this);
  31933. });
  31934. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  31935. _this.object.position.addInPlace(_this._deltaPosition);
  31936. if (_this._deltaRotation) {
  31937. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  31938. }
  31939. };
  31940. //event and body object due to cannon's event-based architecture.
  31941. this.onCollide = function (e) {
  31942. if (!_this._onPhysicsCollideCallbacks.length)
  31943. return;
  31944. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  31945. if (otherImpostor) {
  31946. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  31947. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  31948. }).forEach(function (obj) {
  31949. obj.callback(_this, otherImpostor);
  31950. });
  31951. }
  31952. };
  31953. //sanity check!
  31954. if (!this.object) {
  31955. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  31956. return;
  31957. }
  31958. //legacy support for old syntax.
  31959. if (!this._scene && object.getScene) {
  31960. this._scene = object.getScene();
  31961. }
  31962. this._physicsEngine = this._scene.getPhysicsEngine();
  31963. if (!this._physicsEngine) {
  31964. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  31965. }
  31966. else {
  31967. //set the object's quaternion, if not set
  31968. if (!this.object.rotationQuaternion) {
  31969. if (this.object.rotation) {
  31970. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  31971. }
  31972. else {
  31973. this.object.rotationQuaternion = new BABYLON.Quaternion();
  31974. }
  31975. }
  31976. //default options params
  31977. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  31978. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  31979. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  31980. this._joints = [];
  31981. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  31982. if (!this.object.parent) {
  31983. this._init();
  31984. }
  31985. }
  31986. }
  31987. /**
  31988. * This function will completly initialize this impostor.
  31989. * It will create a new body - but only if this mesh has no parent.
  31990. * If it has, this impostor will not be used other than to define the impostor
  31991. * of the child mesh.
  31992. */
  31993. PhysicsImpostor.prototype._init = function () {
  31994. this._physicsEngine.removeImpostor(this);
  31995. this.physicsBody = null;
  31996. this._parent = this._parent || this._getPhysicsParent();
  31997. if (!this.parent) {
  31998. this._physicsEngine.addImpostor(this);
  31999. }
  32000. };
  32001. PhysicsImpostor.prototype._getPhysicsParent = function () {
  32002. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  32003. var parentMesh = this.object.parent;
  32004. return parentMesh.physicsImpostor;
  32005. }
  32006. return;
  32007. };
  32008. /**
  32009. * Should a new body be generated.
  32010. */
  32011. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  32012. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  32013. };
  32014. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  32015. this.forceUpdate();
  32016. };
  32017. /**
  32018. * Force a regeneration of this or the parent's impostor's body.
  32019. * Use under cautious - This will remove all joints already implemented.
  32020. */
  32021. PhysicsImpostor.prototype.forceUpdate = function () {
  32022. this._init();
  32023. if (this.parent) {
  32024. this.parent.forceUpdate();
  32025. }
  32026. };
  32027. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  32028. /*public get mesh(): AbstractMesh {
  32029. return this._mesh;
  32030. }*/
  32031. /**
  32032. * Gets the body that holds this impostor. Either its own, or its parent.
  32033. */
  32034. get: function () {
  32035. return this._parent ? this._parent.physicsBody : this._physicsBody;
  32036. },
  32037. /**
  32038. * Set the physics body. Used mainly by the physics engine/plugin
  32039. */
  32040. set: function (physicsBody) {
  32041. if (this._physicsBody) {
  32042. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  32043. }
  32044. this._physicsBody = physicsBody;
  32045. this.resetUpdateFlags();
  32046. },
  32047. enumerable: true,
  32048. configurable: true
  32049. });
  32050. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  32051. get: function () {
  32052. return this._parent;
  32053. },
  32054. set: function (value) {
  32055. this._parent = value;
  32056. },
  32057. enumerable: true,
  32058. configurable: true
  32059. });
  32060. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  32061. this._bodyUpdateRequired = false;
  32062. };
  32063. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  32064. if (this.object.getBoundingInfo) {
  32065. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  32066. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  32067. }
  32068. else {
  32069. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  32070. }
  32071. };
  32072. PhysicsImpostor.prototype.getObjectCenter = function () {
  32073. if (this.object.getBoundingInfo) {
  32074. return this.object.getBoundingInfo().boundingBox.center;
  32075. }
  32076. else {
  32077. return this.object.position;
  32078. }
  32079. };
  32080. /**
  32081. * Get a specific parametes from the options parameter.
  32082. */
  32083. PhysicsImpostor.prototype.getParam = function (paramName) {
  32084. return this._options[paramName];
  32085. };
  32086. /**
  32087. * Sets a specific parameter in the options given to the physics plugin
  32088. */
  32089. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32090. this._options[paramName] = value;
  32091. this._bodyUpdateRequired = true;
  32092. };
  32093. /**
  32094. * Specifically change the body's mass option. Won't recreate the physics body object
  32095. */
  32096. PhysicsImpostor.prototype.setMass = function (mass) {
  32097. if (this.getParam("mass") !== mass) {
  32098. this.setParam("mass", mass);
  32099. }
  32100. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32101. };
  32102. PhysicsImpostor.prototype.getLinearVelocity = function () {
  32103. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  32104. };
  32105. /**
  32106. * Set the body's linear velocity.
  32107. */
  32108. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  32109. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  32110. };
  32111. PhysicsImpostor.prototype.getAngularVelocity = function () {
  32112. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  32113. };
  32114. /**
  32115. * Set the body's linear velocity.
  32116. */
  32117. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  32118. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  32119. };
  32120. /**
  32121. * Execute a function with the physics plugin native code.
  32122. * Provide a function the will have two variables - the world object and the physics body object.
  32123. */
  32124. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  32125. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  32126. };
  32127. /**
  32128. * Register a function that will be executed before the physics world is stepping forward.
  32129. */
  32130. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  32131. this._onBeforePhysicsStepCallbacks.push(func);
  32132. };
  32133. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  32134. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  32135. if (index > -1) {
  32136. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  32137. }
  32138. else {
  32139. BABYLON.Tools.Warn("Function to remove was not found");
  32140. }
  32141. };
  32142. /**
  32143. * Register a function that will be executed after the physics step
  32144. */
  32145. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32146. this._onAfterPhysicsStepCallbacks.push(func);
  32147. };
  32148. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32149. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32150. if (index > -1) {
  32151. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32152. }
  32153. else {
  32154. BABYLON.Tools.Warn("Function to remove was not found");
  32155. }
  32156. };
  32157. /**
  32158. * register a function that will be executed when this impostor collides against a different body.
  32159. */
  32160. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32161. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32162. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32163. };
  32164. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32165. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32166. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32167. if (index > -1) {
  32168. this._onPhysicsCollideCallbacks.splice(index, 1);
  32169. }
  32170. else {
  32171. BABYLON.Tools.Warn("Function to remove was not found");
  32172. }
  32173. };
  32174. /**
  32175. * Apply a force
  32176. */
  32177. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32178. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32179. };
  32180. /**
  32181. * Apply an impulse
  32182. */
  32183. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32184. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32185. };
  32186. /**
  32187. * A help function to create a joint.
  32188. */
  32189. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32190. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32191. this.addJoint(otherImpostor, joint);
  32192. };
  32193. /**
  32194. * Add a joint to this impostor with a different impostor.
  32195. */
  32196. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32197. this._joints.push({
  32198. otherImpostor: otherImpostor,
  32199. joint: joint
  32200. });
  32201. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32202. };
  32203. /**
  32204. * Will keep this body still, in a sleep mode.
  32205. */
  32206. PhysicsImpostor.prototype.sleep = function () {
  32207. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32208. };
  32209. /**
  32210. * Wake the body up.
  32211. */
  32212. PhysicsImpostor.prototype.wakeUp = function () {
  32213. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32214. };
  32215. PhysicsImpostor.prototype.clone = function (newObject) {
  32216. if (!newObject)
  32217. return null;
  32218. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32219. };
  32220. PhysicsImpostor.prototype.dispose = function () {
  32221. var _this = this;
  32222. //no dispose if no physics engine is available.
  32223. if (!this._physicsEngine) {
  32224. return;
  32225. }
  32226. this._joints.forEach(function (j) {
  32227. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32228. });
  32229. //dispose the physics body
  32230. this._physicsEngine.removeImpostor(this);
  32231. if (this.parent) {
  32232. this.parent.forceUpdate();
  32233. }
  32234. else {
  32235. }
  32236. };
  32237. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32238. this._deltaPosition.copyFrom(position);
  32239. };
  32240. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32241. if (!this._deltaRotation) {
  32242. this._deltaRotation = new BABYLON.Quaternion();
  32243. }
  32244. this._deltaRotation.copyFrom(rotation);
  32245. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32246. };
  32247. return PhysicsImpostor;
  32248. }());
  32249. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32250. //Impostor types
  32251. PhysicsImpostor.NoImpostor = 0;
  32252. PhysicsImpostor.SphereImpostor = 1;
  32253. PhysicsImpostor.BoxImpostor = 2;
  32254. PhysicsImpostor.PlaneImpostor = 3;
  32255. PhysicsImpostor.MeshImpostor = 4;
  32256. PhysicsImpostor.CylinderImpostor = 7;
  32257. PhysicsImpostor.ParticleImpostor = 8;
  32258. PhysicsImpostor.HeightmapImpostor = 9;
  32259. BABYLON.PhysicsImpostor = PhysicsImpostor;
  32260. })(BABYLON || (BABYLON = {}));
  32261. //# sourceMappingURL=babylon.physicsImpostor.js.map
  32262. var BABYLON;
  32263. (function (BABYLON) {
  32264. var PhysicsEngine = (function () {
  32265. function PhysicsEngine(gravity, _physicsPlugin) {
  32266. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  32267. this._physicsPlugin = _physicsPlugin;
  32268. //new methods and parameters
  32269. this._impostors = [];
  32270. this._joints = [];
  32271. if (!this._physicsPlugin.isSupported()) {
  32272. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  32273. + "Please make sure it is included.");
  32274. }
  32275. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  32276. this.setGravity(gravity);
  32277. this.setTimeStep();
  32278. }
  32279. PhysicsEngine.prototype.setGravity = function (gravity) {
  32280. this.gravity = gravity;
  32281. this._physicsPlugin.setGravity(this.gravity);
  32282. };
  32283. /**
  32284. * Set the time step of the physics engine.
  32285. * default is 1/60.
  32286. * To slow it down, enter 1/600 for example.
  32287. * To speed it up, 1/30
  32288. * @param {number} newTimeStep the new timestep to apply to this world.
  32289. */
  32290. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  32291. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  32292. this._physicsPlugin.setTimeStep(newTimeStep);
  32293. };
  32294. PhysicsEngine.prototype.dispose = function () {
  32295. this._impostors.forEach(function (impostor) {
  32296. impostor.dispose();
  32297. });
  32298. this._physicsPlugin.dispose();
  32299. };
  32300. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  32301. return this._physicsPlugin.name;
  32302. };
  32303. /**
  32304. * Adding a new impostor for the impostor tracking.
  32305. * This will be done by the impostor itself.
  32306. * @param {PhysicsImpostor} impostor the impostor to add
  32307. */
  32308. PhysicsEngine.prototype.addImpostor = function (impostor) {
  32309. impostor.uniqueId = this._impostors.push(impostor);
  32310. //if no parent, generate the body
  32311. if (!impostor.parent) {
  32312. this._physicsPlugin.generatePhysicsBody(impostor);
  32313. }
  32314. };
  32315. /**
  32316. * Remove an impostor from the engine.
  32317. * This impostor and its mesh will not longer be updated by the physics engine.
  32318. * @param {PhysicsImpostor} impostor the impostor to remove
  32319. */
  32320. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  32321. var index = this._impostors.indexOf(impostor);
  32322. if (index > -1) {
  32323. var removed = this._impostors.splice(index, 1);
  32324. //Is it needed?
  32325. if (removed.length) {
  32326. //this will also remove it from the world.
  32327. removed[0].physicsBody = null;
  32328. }
  32329. }
  32330. };
  32331. /**
  32332. * Add a joint to the physics engine
  32333. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  32334. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  32335. * @param {PhysicsJoint} the joint that will connect both impostors.
  32336. */
  32337. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  32338. var impostorJoint = {
  32339. mainImpostor: mainImpostor,
  32340. connectedImpostor: connectedImpostor,
  32341. joint: joint
  32342. };
  32343. joint.physicsPlugin = this._physicsPlugin;
  32344. this._joints.push(impostorJoint);
  32345. this._physicsPlugin.generateJoint(impostorJoint);
  32346. };
  32347. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  32348. var matchingJoints = this._joints.filter(function (impostorJoint) {
  32349. return (impostorJoint.connectedImpostor === connectedImpostor
  32350. && impostorJoint.joint === joint
  32351. && impostorJoint.mainImpostor === mainImpostor);
  32352. });
  32353. if (matchingJoints.length) {
  32354. this._physicsPlugin.removeJoint(matchingJoints[0]);
  32355. }
  32356. };
  32357. /**
  32358. * Called by the scene. no need to call it.
  32359. */
  32360. PhysicsEngine.prototype._step = function (delta) {
  32361. var _this = this;
  32362. //check if any mesh has no body / requires an update
  32363. this._impostors.forEach(function (impostor) {
  32364. if (impostor.isBodyInitRequired()) {
  32365. _this._physicsPlugin.generatePhysicsBody(impostor);
  32366. }
  32367. });
  32368. if (delta > 0.1) {
  32369. delta = 0.1;
  32370. }
  32371. else if (delta <= 0) {
  32372. delta = 1.0 / 60.0;
  32373. }
  32374. this._physicsPlugin.executeStep(delta, this._impostors);
  32375. };
  32376. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  32377. return this._physicsPlugin;
  32378. };
  32379. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  32380. for (var i = 0; i < this._impostors.length; ++i) {
  32381. if (this._impostors[i].object === object) {
  32382. return this._impostors[i];
  32383. }
  32384. }
  32385. };
  32386. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  32387. for (var i = 0; i < this._impostors.length; ++i) {
  32388. if (this._impostors[i].physicsBody === body) {
  32389. return this._impostors[i];
  32390. }
  32391. }
  32392. };
  32393. return PhysicsEngine;
  32394. }());
  32395. // Statics, Legacy support.
  32396. /**
  32397. * @Deprecated
  32398. *
  32399. */
  32400. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  32401. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  32402. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  32403. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  32404. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  32405. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  32406. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  32407. PhysicsEngine.CapsuleImpostor = -1;
  32408. PhysicsEngine.ConeImpostor = -1;
  32409. PhysicsEngine.ConvexHullImpostor = -1;
  32410. PhysicsEngine.Epsilon = 0.001;
  32411. BABYLON.PhysicsEngine = PhysicsEngine;
  32412. })(BABYLON || (BABYLON = {}));
  32413. //# sourceMappingURL=babylon.physicsEngine.js.map
  32414. var BABYLON;
  32415. (function (BABYLON) {
  32416. var VertexData = (function () {
  32417. function VertexData() {
  32418. }
  32419. VertexData.prototype.set = function (data, kind) {
  32420. switch (kind) {
  32421. case BABYLON.VertexBuffer.PositionKind:
  32422. this.positions = data;
  32423. break;
  32424. case BABYLON.VertexBuffer.NormalKind:
  32425. this.normals = data;
  32426. break;
  32427. case BABYLON.VertexBuffer.UVKind:
  32428. this.uvs = data;
  32429. break;
  32430. case BABYLON.VertexBuffer.UV2Kind:
  32431. this.uvs2 = data;
  32432. break;
  32433. case BABYLON.VertexBuffer.UV3Kind:
  32434. this.uvs3 = data;
  32435. break;
  32436. case BABYLON.VertexBuffer.UV4Kind:
  32437. this.uvs4 = data;
  32438. break;
  32439. case BABYLON.VertexBuffer.UV5Kind:
  32440. this.uvs5 = data;
  32441. break;
  32442. case BABYLON.VertexBuffer.UV6Kind:
  32443. this.uvs6 = data;
  32444. break;
  32445. case BABYLON.VertexBuffer.ColorKind:
  32446. this.colors = data;
  32447. break;
  32448. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32449. this.matricesIndices = data;
  32450. break;
  32451. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32452. this.matricesWeights = data;
  32453. break;
  32454. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32455. this.matricesIndicesExtra = data;
  32456. break;
  32457. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32458. this.matricesWeightsExtra = data;
  32459. break;
  32460. }
  32461. };
  32462. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32463. this._applyTo(mesh, updatable);
  32464. };
  32465. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32466. this._applyTo(geometry, updatable);
  32467. };
  32468. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32469. this._update(mesh);
  32470. };
  32471. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32472. this._update(geometry);
  32473. };
  32474. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32475. if (this.positions) {
  32476. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32477. }
  32478. if (this.normals) {
  32479. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32480. }
  32481. if (this.uvs) {
  32482. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32483. }
  32484. if (this.uvs2) {
  32485. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32486. }
  32487. if (this.uvs3) {
  32488. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32489. }
  32490. if (this.uvs4) {
  32491. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32492. }
  32493. if (this.uvs5) {
  32494. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32495. }
  32496. if (this.uvs6) {
  32497. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32498. }
  32499. if (this.colors) {
  32500. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32501. }
  32502. if (this.matricesIndices) {
  32503. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32504. }
  32505. if (this.matricesWeights) {
  32506. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32507. }
  32508. if (this.matricesIndicesExtra) {
  32509. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32510. }
  32511. if (this.matricesWeightsExtra) {
  32512. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32513. }
  32514. if (this.indices) {
  32515. meshOrGeometry.setIndices(this.indices);
  32516. }
  32517. };
  32518. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32519. if (this.positions) {
  32520. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32521. }
  32522. if (this.normals) {
  32523. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32524. }
  32525. if (this.uvs) {
  32526. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32527. }
  32528. if (this.uvs2) {
  32529. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32530. }
  32531. if (this.uvs3) {
  32532. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32533. }
  32534. if (this.uvs4) {
  32535. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32536. }
  32537. if (this.uvs5) {
  32538. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32539. }
  32540. if (this.uvs6) {
  32541. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32542. }
  32543. if (this.colors) {
  32544. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32545. }
  32546. if (this.matricesIndices) {
  32547. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32548. }
  32549. if (this.matricesWeights) {
  32550. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32551. }
  32552. if (this.matricesIndicesExtra) {
  32553. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32554. }
  32555. if (this.matricesWeightsExtra) {
  32556. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32557. }
  32558. if (this.indices) {
  32559. meshOrGeometry.setIndices(this.indices);
  32560. }
  32561. };
  32562. VertexData.prototype.transform = function (matrix) {
  32563. var transformed = BABYLON.Vector3.Zero();
  32564. var index;
  32565. if (this.positions) {
  32566. var position = BABYLON.Vector3.Zero();
  32567. for (index = 0; index < this.positions.length; index += 3) {
  32568. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32569. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32570. this.positions[index] = transformed.x;
  32571. this.positions[index + 1] = transformed.y;
  32572. this.positions[index + 2] = transformed.z;
  32573. }
  32574. }
  32575. if (this.normals) {
  32576. var normal = BABYLON.Vector3.Zero();
  32577. for (index = 0; index < this.normals.length; index += 3) {
  32578. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32579. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32580. this.normals[index] = transformed.x;
  32581. this.normals[index + 1] = transformed.y;
  32582. this.normals[index + 2] = transformed.z;
  32583. }
  32584. }
  32585. };
  32586. VertexData.prototype.merge = function (other) {
  32587. if (other.indices) {
  32588. if (!this.indices) {
  32589. this.indices = [];
  32590. }
  32591. var offset = this.positions ? this.positions.length / 3 : 0;
  32592. for (var index = 0; index < other.indices.length; index++) {
  32593. //TODO check type - if Int32Array!
  32594. this.indices.push(other.indices[index] + offset);
  32595. }
  32596. }
  32597. this.positions = this._mergeElement(this.positions, other.positions);
  32598. this.normals = this._mergeElement(this.normals, other.normals);
  32599. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32600. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32601. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32602. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32603. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32604. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32605. this.colors = this._mergeElement(this.colors, other.colors);
  32606. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32607. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32608. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32609. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32610. };
  32611. VertexData.prototype._mergeElement = function (source, other) {
  32612. if (!other)
  32613. return source;
  32614. if (!source)
  32615. return other;
  32616. var len = other.length + source.length;
  32617. var isSrcTypedArray = source instanceof Float32Array;
  32618. var isOthTypedArray = other instanceof Float32Array;
  32619. // use non-loop method when the source is Float32Array
  32620. if (isSrcTypedArray) {
  32621. var ret32 = new Float32Array(len);
  32622. ret32.set(source);
  32623. ret32.set(other, source.length);
  32624. return ret32;
  32625. }
  32626. else if (!isOthTypedArray) {
  32627. return source.concat(other);
  32628. }
  32629. else {
  32630. var ret = source.slice(0); // copy source to a separate array
  32631. for (var i = 0, len = other.length; i < len; i++) {
  32632. ret.push(other[i]);
  32633. }
  32634. return ret;
  32635. }
  32636. };
  32637. VertexData.prototype.serialize = function () {
  32638. var serializationObject = this.serialize();
  32639. if (this.positions) {
  32640. serializationObject.positions = this.positions;
  32641. }
  32642. if (this.normals) {
  32643. serializationObject.normals = this.normals;
  32644. }
  32645. if (this.uvs) {
  32646. serializationObject.uvs = this.uvs;
  32647. }
  32648. if (this.uvs2) {
  32649. serializationObject.uvs2 = this.uvs2;
  32650. }
  32651. if (this.uvs3) {
  32652. serializationObject.uvs3 = this.uvs3;
  32653. }
  32654. if (this.uvs4) {
  32655. serializationObject.uvs4 = this.uvs4;
  32656. }
  32657. if (this.uvs5) {
  32658. serializationObject.uvs5 = this.uvs5;
  32659. }
  32660. if (this.uvs6) {
  32661. serializationObject.uvs6 = this.uvs6;
  32662. }
  32663. if (this.colors) {
  32664. serializationObject.colors = this.colors;
  32665. }
  32666. if (this.matricesIndices) {
  32667. serializationObject.matricesIndices = this.matricesIndices;
  32668. serializationObject.matricesIndices._isExpanded = true;
  32669. }
  32670. if (this.matricesWeights) {
  32671. serializationObject.matricesWeights = this.matricesWeights;
  32672. }
  32673. if (this.matricesIndicesExtra) {
  32674. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32675. serializationObject.matricesIndicesExtra._isExpanded = true;
  32676. }
  32677. if (this.matricesWeightsExtra) {
  32678. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32679. }
  32680. serializationObject.indices = this.indices;
  32681. return serializationObject;
  32682. };
  32683. // Statics
  32684. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  32685. return VertexData._ExtractFrom(mesh, copyWhenShared);
  32686. };
  32687. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  32688. return VertexData._ExtractFrom(geometry, copyWhenShared);
  32689. };
  32690. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  32691. var result = new VertexData();
  32692. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32693. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  32694. }
  32695. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32696. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  32697. }
  32698. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32699. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  32700. }
  32701. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32702. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  32703. }
  32704. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32705. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  32706. }
  32707. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32708. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  32709. }
  32710. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32711. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  32712. }
  32713. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32714. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  32715. }
  32716. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32717. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  32718. }
  32719. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32720. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  32721. }
  32722. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32723. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  32724. }
  32725. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32726. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  32727. }
  32728. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32729. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  32730. }
  32731. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32732. return result;
  32733. };
  32734. VertexData.CreateRibbon = function (options) {
  32735. var pathArray = options.pathArray;
  32736. var closeArray = options.closeArray || false;
  32737. var closePath = options.closePath || false;
  32738. var invertUV = options.invertUV || false;
  32739. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32740. var offset = options.offset || defaultOffset;
  32741. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32742. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32743. var positions = [];
  32744. var indices = [];
  32745. var normals = [];
  32746. var uvs = [];
  32747. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32748. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32749. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32750. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32751. var minlg; // minimal length among all paths from pathArray
  32752. var lg = []; // array of path lengths : nb of vertex per path
  32753. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32754. var p; // path iterator
  32755. var i; // point iterator
  32756. var j; // point iterator
  32757. // if single path in pathArray
  32758. if (pathArray.length < 2) {
  32759. var ar1 = [];
  32760. var ar2 = [];
  32761. for (i = 0; i < pathArray[0].length - offset; i++) {
  32762. ar1.push(pathArray[0][i]);
  32763. ar2.push(pathArray[0][i + offset]);
  32764. }
  32765. pathArray = [ar1, ar2];
  32766. }
  32767. // positions and horizontal distances (u)
  32768. var idc = 0;
  32769. var closePathCorr = (closePath) ? 1 : 0;
  32770. var path;
  32771. var l;
  32772. minlg = pathArray[0].length;
  32773. var vectlg;
  32774. var dist;
  32775. for (p = 0; p < pathArray.length; p++) {
  32776. uTotalDistance[p] = 0;
  32777. us[p] = [0];
  32778. path = pathArray[p];
  32779. l = path.length;
  32780. minlg = (minlg < l) ? minlg : l;
  32781. j = 0;
  32782. while (j < l) {
  32783. positions.push(path[j].x, path[j].y, path[j].z);
  32784. if (j > 0) {
  32785. vectlg = path[j].subtract(path[j - 1]).length();
  32786. dist = vectlg + uTotalDistance[p];
  32787. us[p].push(dist);
  32788. uTotalDistance[p] = dist;
  32789. }
  32790. j++;
  32791. }
  32792. if (closePath) {
  32793. j--;
  32794. positions.push(path[0].x, path[0].y, path[0].z);
  32795. vectlg = path[j].subtract(path[0]).length();
  32796. dist = vectlg + uTotalDistance[p];
  32797. us[p].push(dist);
  32798. uTotalDistance[p] = dist;
  32799. }
  32800. lg[p] = l + closePathCorr;
  32801. idx[p] = idc;
  32802. idc += (l + closePathCorr);
  32803. }
  32804. // vertical distances (v)
  32805. var path1;
  32806. var path2;
  32807. var vertex1;
  32808. var vertex2;
  32809. for (i = 0; i < minlg + closePathCorr; i++) {
  32810. vTotalDistance[i] = 0;
  32811. vs[i] = [0];
  32812. for (p = 0; p < pathArray.length - 1; p++) {
  32813. path1 = pathArray[p];
  32814. path2 = pathArray[p + 1];
  32815. if (i === minlg) {
  32816. vertex1 = path1[0];
  32817. vertex2 = path2[0];
  32818. }
  32819. else {
  32820. vertex1 = path1[i];
  32821. vertex2 = path2[i];
  32822. }
  32823. vectlg = vertex2.subtract(vertex1).length();
  32824. dist = vectlg + vTotalDistance[i];
  32825. vs[i].push(dist);
  32826. vTotalDistance[i] = dist;
  32827. }
  32828. if (closeArray) {
  32829. path1 = pathArray[p];
  32830. path2 = pathArray[0];
  32831. if (i === minlg) {
  32832. vertex2 = path2[0];
  32833. }
  32834. vectlg = vertex2.subtract(vertex1).length();
  32835. dist = vectlg + vTotalDistance[i];
  32836. vTotalDistance[i] = dist;
  32837. }
  32838. }
  32839. // uvs
  32840. var u;
  32841. var v;
  32842. for (p = 0; p < pathArray.length; p++) {
  32843. for (i = 0; i < minlg + closePathCorr; i++) {
  32844. u = us[p][i] / uTotalDistance[p];
  32845. v = vs[i][p] / vTotalDistance[i];
  32846. if (invertUV) {
  32847. uvs.push(v, u);
  32848. }
  32849. else {
  32850. uvs.push(u, v);
  32851. }
  32852. }
  32853. }
  32854. // indices
  32855. p = 0; // path index
  32856. var pi = 0; // positions array index
  32857. var l1 = lg[p] - 1; // path1 length
  32858. var l2 = lg[p + 1] - 1; // path2 length
  32859. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32860. var shft = idx[1] - idx[0]; // shift
  32861. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32862. while (pi <= min && p < path1nb) {
  32863. // 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
  32864. indices.push(pi, pi + shft, pi + 1);
  32865. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32866. pi += 1;
  32867. if (pi === min) {
  32868. p++;
  32869. if (p === lg.length - 1) {
  32870. shft = idx[0] - idx[p];
  32871. l1 = lg[p] - 1;
  32872. l2 = lg[0] - 1;
  32873. }
  32874. else {
  32875. shft = idx[p + 1] - idx[p];
  32876. l1 = lg[p] - 1;
  32877. l2 = lg[p + 1] - 1;
  32878. }
  32879. pi = idx[p];
  32880. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32881. }
  32882. }
  32883. // normals
  32884. VertexData.ComputeNormals(positions, indices, normals);
  32885. if (closePath) {
  32886. var indexFirst = 0;
  32887. var indexLast = 0;
  32888. for (p = 0; p < pathArray.length; p++) {
  32889. indexFirst = idx[p] * 3;
  32890. if (p + 1 < pathArray.length) {
  32891. indexLast = (idx[p + 1] - 1) * 3;
  32892. }
  32893. else {
  32894. indexLast = normals.length - 3;
  32895. }
  32896. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32897. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32898. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32899. normals[indexLast] = normals[indexFirst];
  32900. normals[indexLast + 1] = normals[indexFirst + 1];
  32901. normals[indexLast + 2] = normals[indexFirst + 2];
  32902. }
  32903. }
  32904. // sides
  32905. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32906. // Result
  32907. var vertexData = new VertexData();
  32908. vertexData.indices = indices;
  32909. vertexData.positions = positions;
  32910. vertexData.normals = normals;
  32911. vertexData.uvs = uvs;
  32912. if (closePath) {
  32913. vertexData._idx = idx;
  32914. }
  32915. return vertexData;
  32916. };
  32917. VertexData.CreateBox = function (options) {
  32918. var normalsSource = [
  32919. new BABYLON.Vector3(0, 0, 1),
  32920. new BABYLON.Vector3(0, 0, -1),
  32921. new BABYLON.Vector3(1, 0, 0),
  32922. new BABYLON.Vector3(-1, 0, 0),
  32923. new BABYLON.Vector3(0, 1, 0),
  32924. new BABYLON.Vector3(0, -1, 0)
  32925. ];
  32926. var indices = [];
  32927. var positions = [];
  32928. var normals = [];
  32929. var uvs = [];
  32930. var width = options.width || options.size || 1;
  32931. var height = options.height || options.size || 1;
  32932. var depth = options.depth || options.size || 1;
  32933. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32934. var faceUV = options.faceUV || new Array(6);
  32935. var faceColors = options.faceColors;
  32936. var colors = [];
  32937. // default face colors and UV if undefined
  32938. for (var f = 0; f < 6; f++) {
  32939. if (faceUV[f] === undefined) {
  32940. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32941. }
  32942. if (faceColors && faceColors[f] === undefined) {
  32943. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32944. }
  32945. }
  32946. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32947. // Create each face in turn.
  32948. for (var index = 0; index < normalsSource.length; index++) {
  32949. var normal = normalsSource[index];
  32950. // Get two vectors perpendicular to the face normal and to each other.
  32951. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32952. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32953. // Six indices (two triangles) per face.
  32954. var verticesLength = positions.length / 3;
  32955. indices.push(verticesLength);
  32956. indices.push(verticesLength + 1);
  32957. indices.push(verticesLength + 2);
  32958. indices.push(verticesLength);
  32959. indices.push(verticesLength + 2);
  32960. indices.push(verticesLength + 3);
  32961. // Four vertices per face.
  32962. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32963. positions.push(vertex.x, vertex.y, vertex.z);
  32964. normals.push(normal.x, normal.y, normal.z);
  32965. uvs.push(faceUV[index].z, faceUV[index].w);
  32966. if (faceColors) {
  32967. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32968. }
  32969. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32970. positions.push(vertex.x, vertex.y, vertex.z);
  32971. normals.push(normal.x, normal.y, normal.z);
  32972. uvs.push(faceUV[index].x, faceUV[index].w);
  32973. if (faceColors) {
  32974. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32975. }
  32976. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32977. positions.push(vertex.x, vertex.y, vertex.z);
  32978. normals.push(normal.x, normal.y, normal.z);
  32979. uvs.push(faceUV[index].x, faceUV[index].y);
  32980. if (faceColors) {
  32981. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32982. }
  32983. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32984. positions.push(vertex.x, vertex.y, vertex.z);
  32985. normals.push(normal.x, normal.y, normal.z);
  32986. uvs.push(faceUV[index].z, faceUV[index].y);
  32987. if (faceColors) {
  32988. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32989. }
  32990. }
  32991. // sides
  32992. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32993. // Result
  32994. var vertexData = new VertexData();
  32995. vertexData.indices = indices;
  32996. vertexData.positions = positions;
  32997. vertexData.normals = normals;
  32998. vertexData.uvs = uvs;
  32999. if (faceColors) {
  33000. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33001. vertexData.colors = totalColors;
  33002. }
  33003. return vertexData;
  33004. };
  33005. VertexData.CreateSphere = function (options) {
  33006. var segments = options.segments || 32;
  33007. var diameterX = options.diameterX || options.diameter || 1;
  33008. var diameterY = options.diameterY || options.diameter || 1;
  33009. var diameterZ = options.diameterZ || options.diameter || 1;
  33010. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33011. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33012. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33013. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33014. var totalZRotationSteps = 2 + segments;
  33015. var totalYRotationSteps = 2 * totalZRotationSteps;
  33016. var indices = [];
  33017. var positions = [];
  33018. var normals = [];
  33019. var uvs = [];
  33020. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33021. var normalizedZ = zRotationStep / totalZRotationSteps;
  33022. var angleZ = normalizedZ * Math.PI * slice;
  33023. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33024. var normalizedY = yRotationStep / totalYRotationSteps;
  33025. var angleY = normalizedY * Math.PI * 2 * arc;
  33026. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33027. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33028. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33029. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33030. var vertex = complete.multiply(radius);
  33031. var normal = complete.divide(radius).normalize();
  33032. positions.push(vertex.x, vertex.y, vertex.z);
  33033. normals.push(normal.x, normal.y, normal.z);
  33034. uvs.push(normalizedY, normalizedZ);
  33035. }
  33036. if (zRotationStep > 0) {
  33037. var verticesCount = positions.length / 3;
  33038. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33039. indices.push((firstIndex));
  33040. indices.push((firstIndex + 1));
  33041. indices.push(firstIndex + totalYRotationSteps + 1);
  33042. indices.push((firstIndex + totalYRotationSteps + 1));
  33043. indices.push((firstIndex + 1));
  33044. indices.push((firstIndex + totalYRotationSteps + 2));
  33045. }
  33046. }
  33047. }
  33048. // Sides
  33049. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33050. // Result
  33051. var vertexData = new VertexData();
  33052. vertexData.indices = indices;
  33053. vertexData.positions = positions;
  33054. vertexData.normals = normals;
  33055. vertexData.uvs = uvs;
  33056. return vertexData;
  33057. };
  33058. // Cylinder and cone
  33059. VertexData.CreateCylinder = function (options) {
  33060. var height = options.height || 2;
  33061. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33062. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33063. var tessellation = options.tessellation || 24;
  33064. var subdivisions = options.subdivisions || 1;
  33065. var hasRings = options.hasRings;
  33066. var enclose = options.enclose;
  33067. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33068. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33069. var faceUV = options.faceUV || new Array(3);
  33070. var faceColors = options.faceColors;
  33071. // default face colors and UV if undefined
  33072. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33073. var ringNb = (hasRings) ? subdivisions : 1;
  33074. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33075. var f;
  33076. for (f = 0; f < surfaceNb; f++) {
  33077. if (faceColors && faceColors[f] === undefined) {
  33078. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33079. }
  33080. }
  33081. for (f = 0; f < surfaceNb; f++) {
  33082. if (faceUV && faceUV[f] === undefined) {
  33083. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33084. }
  33085. }
  33086. var indices = [];
  33087. var positions = [];
  33088. var normals = [];
  33089. var uvs = [];
  33090. var colors = [];
  33091. var angle_step = Math.PI * 2 * arc / tessellation;
  33092. var angle;
  33093. var h;
  33094. var radius;
  33095. var tan = (diameterBottom - diameterTop) / 2 / height;
  33096. var ringVertex = BABYLON.Vector3.Zero();
  33097. var ringNormal = BABYLON.Vector3.Zero();
  33098. var ringFirstVertex = BABYLON.Vector3.Zero();
  33099. var ringFirstNormal = BABYLON.Vector3.Zero();
  33100. var quadNormal = BABYLON.Vector3.Zero();
  33101. var Y = BABYLON.Axis.Y;
  33102. // positions, normals, uvs
  33103. var i;
  33104. var j;
  33105. var r;
  33106. var ringIdx = 1;
  33107. var s = 1; // surface index
  33108. var cs = 0;
  33109. var v = 0;
  33110. for (i = 0; i <= subdivisions; i++) {
  33111. h = i / subdivisions;
  33112. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33113. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33114. for (r = 0; r < ringIdx; r++) {
  33115. if (hasRings) {
  33116. s += r;
  33117. }
  33118. if (enclose) {
  33119. s += 2 * r;
  33120. }
  33121. for (j = 0; j <= tessellation; j++) {
  33122. angle = j * angle_step;
  33123. // position
  33124. ringVertex.x = Math.cos(-angle) * radius;
  33125. ringVertex.y = -height / 2 + h * height;
  33126. ringVertex.z = Math.sin(-angle) * radius;
  33127. // normal
  33128. if (diameterTop === 0 && i === subdivisions) {
  33129. // if no top cap, reuse former normals
  33130. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33131. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33132. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33133. }
  33134. else {
  33135. ringNormal.x = ringVertex.x;
  33136. ringNormal.z = ringVertex.z;
  33137. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33138. ringNormal.normalize();
  33139. }
  33140. // keep first ring vertex values for enclose
  33141. if (j === 0) {
  33142. ringFirstVertex.copyFrom(ringVertex);
  33143. ringFirstNormal.copyFrom(ringNormal);
  33144. }
  33145. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33146. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33147. if (hasRings) {
  33148. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33149. }
  33150. else {
  33151. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33152. }
  33153. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33154. if (faceColors) {
  33155. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33156. }
  33157. }
  33158. // if enclose, add four vertices and their dedicated normals
  33159. if (arc !== 1 && enclose) {
  33160. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33161. positions.push(0, ringVertex.y, 0);
  33162. positions.push(0, ringVertex.y, 0);
  33163. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33164. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33165. quadNormal.normalize();
  33166. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33167. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33168. quadNormal.normalize();
  33169. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33170. if (hasRings) {
  33171. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33172. }
  33173. else {
  33174. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33175. }
  33176. uvs.push(faceUV[s + 1].x, v);
  33177. uvs.push(faceUV[s + 1].z, v);
  33178. if (hasRings) {
  33179. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33180. }
  33181. else {
  33182. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33183. }
  33184. uvs.push(faceUV[s + 2].x, v);
  33185. uvs.push(faceUV[s + 2].z, v);
  33186. if (faceColors) {
  33187. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33188. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33189. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33190. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33191. }
  33192. }
  33193. if (cs !== s) {
  33194. cs = s;
  33195. }
  33196. }
  33197. }
  33198. // indices
  33199. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33200. var s;
  33201. i = 0;
  33202. for (s = 0; s < subdivisions; s++) {
  33203. for (j = 0; j < tessellation; j++) {
  33204. var i0 = i * (e + 1) + j;
  33205. var i1 = (i + 1) * (e + 1) + j;
  33206. var i2 = i * (e + 1) + (j + 1);
  33207. var i3 = (i + 1) * (e + 1) + (j + 1);
  33208. indices.push(i0, i1, i2);
  33209. indices.push(i3, i2, i1);
  33210. }
  33211. if (arc !== 1 && enclose) {
  33212. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33213. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33214. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33215. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33216. }
  33217. i = (hasRings) ? (i + 2) : (i + 1);
  33218. }
  33219. // Caps
  33220. var createCylinderCap = function (isTop) {
  33221. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33222. if (radius === 0) {
  33223. return;
  33224. }
  33225. // Cap positions, normals & uvs
  33226. var angle;
  33227. var circleVector;
  33228. var i;
  33229. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33230. var c;
  33231. if (faceColors) {
  33232. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33233. }
  33234. // cap center
  33235. var vbase = positions.length / 3;
  33236. var offset = isTop ? height / 2 : -height / 2;
  33237. var center = new BABYLON.Vector3(0, offset, 0);
  33238. positions.push(center.x, center.y, center.z);
  33239. normals.push(0, isTop ? 1 : -1, 0);
  33240. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33241. if (faceColors) {
  33242. colors.push(c.r, c.g, c.b, c.a);
  33243. }
  33244. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33245. for (i = 0; i <= tessellation; i++) {
  33246. angle = Math.PI * 2 * i * arc / tessellation;
  33247. var cos = Math.cos(-angle);
  33248. var sin = Math.sin(-angle);
  33249. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33250. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33251. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33252. normals.push(0, isTop ? 1 : -1, 0);
  33253. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33254. if (faceColors) {
  33255. colors.push(c.r, c.g, c.b, c.a);
  33256. }
  33257. }
  33258. // Cap indices
  33259. for (i = 0; i < tessellation; i++) {
  33260. if (!isTop) {
  33261. indices.push(vbase);
  33262. indices.push(vbase + (i + 1));
  33263. indices.push(vbase + (i + 2));
  33264. }
  33265. else {
  33266. indices.push(vbase);
  33267. indices.push(vbase + (i + 2));
  33268. indices.push(vbase + (i + 1));
  33269. }
  33270. }
  33271. };
  33272. // add caps to geometry
  33273. createCylinderCap(false);
  33274. createCylinderCap(true);
  33275. // Sides
  33276. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33277. var vertexData = new VertexData();
  33278. vertexData.indices = indices;
  33279. vertexData.positions = positions;
  33280. vertexData.normals = normals;
  33281. vertexData.uvs = uvs;
  33282. if (faceColors) {
  33283. vertexData.colors = colors;
  33284. }
  33285. return vertexData;
  33286. };
  33287. VertexData.CreateTorus = function (options) {
  33288. var indices = [];
  33289. var positions = [];
  33290. var normals = [];
  33291. var uvs = [];
  33292. var diameter = options.diameter || 1;
  33293. var thickness = options.thickness || 0.5;
  33294. var tessellation = options.tessellation || 16;
  33295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33296. var stride = tessellation + 1;
  33297. for (var i = 0; i <= tessellation; i++) {
  33298. var u = i / tessellation;
  33299. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33300. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33301. for (var j = 0; j <= tessellation; j++) {
  33302. var v = 1 - j / tessellation;
  33303. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33304. var dx = Math.cos(innerAngle);
  33305. var dy = Math.sin(innerAngle);
  33306. // Create a vertex.
  33307. var normal = new BABYLON.Vector3(dx, dy, 0);
  33308. var position = normal.scale(thickness / 2);
  33309. var textureCoordinate = new BABYLON.Vector2(u, v);
  33310. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33311. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33312. positions.push(position.x, position.y, position.z);
  33313. normals.push(normal.x, normal.y, normal.z);
  33314. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33315. // And create indices for two triangles.
  33316. var nextI = (i + 1) % stride;
  33317. var nextJ = (j + 1) % stride;
  33318. indices.push(i * stride + j);
  33319. indices.push(i * stride + nextJ);
  33320. indices.push(nextI * stride + j);
  33321. indices.push(i * stride + nextJ);
  33322. indices.push(nextI * stride + nextJ);
  33323. indices.push(nextI * stride + j);
  33324. }
  33325. }
  33326. // Sides
  33327. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33328. // Result
  33329. var vertexData = new VertexData();
  33330. vertexData.indices = indices;
  33331. vertexData.positions = positions;
  33332. vertexData.normals = normals;
  33333. vertexData.uvs = uvs;
  33334. return vertexData;
  33335. };
  33336. VertexData.CreateLineSystem = function (options) {
  33337. var indices = [];
  33338. var positions = [];
  33339. var lines = options.lines;
  33340. var idx = 0;
  33341. for (var l = 0; l < lines.length; l++) {
  33342. var points = lines[l];
  33343. for (var index = 0; index < points.length; index++) {
  33344. positions.push(points[index].x, points[index].y, points[index].z);
  33345. if (index > 0) {
  33346. indices.push(idx - 1);
  33347. indices.push(idx);
  33348. }
  33349. idx++;
  33350. }
  33351. }
  33352. var vertexData = new VertexData();
  33353. vertexData.indices = indices;
  33354. vertexData.positions = positions;
  33355. return vertexData;
  33356. };
  33357. VertexData.CreateDashedLines = function (options) {
  33358. var dashSize = options.dashSize || 3;
  33359. var gapSize = options.gapSize || 1;
  33360. var dashNb = options.dashNb || 200;
  33361. var points = options.points;
  33362. var positions = new Array();
  33363. var indices = new Array();
  33364. var curvect = BABYLON.Vector3.Zero();
  33365. var lg = 0;
  33366. var nb = 0;
  33367. var shft = 0;
  33368. var dashshft = 0;
  33369. var curshft = 0;
  33370. var idx = 0;
  33371. var i = 0;
  33372. for (i = 0; i < points.length - 1; i++) {
  33373. points[i + 1].subtractToRef(points[i], curvect);
  33374. lg += curvect.length();
  33375. }
  33376. shft = lg / dashNb;
  33377. dashshft = dashSize * shft / (dashSize + gapSize);
  33378. for (i = 0; i < points.length - 1; i++) {
  33379. points[i + 1].subtractToRef(points[i], curvect);
  33380. nb = Math.floor(curvect.length() / shft);
  33381. curvect.normalize();
  33382. for (var j = 0; j < nb; j++) {
  33383. curshft = shft * j;
  33384. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33385. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33386. indices.push(idx, idx + 1);
  33387. idx += 2;
  33388. }
  33389. }
  33390. // Result
  33391. var vertexData = new VertexData();
  33392. vertexData.positions = positions;
  33393. vertexData.indices = indices;
  33394. return vertexData;
  33395. };
  33396. VertexData.CreateGround = function (options) {
  33397. var indices = [];
  33398. var positions = [];
  33399. var normals = [];
  33400. var uvs = [];
  33401. var row, col;
  33402. var width = options.width || 1;
  33403. var height = options.height || 1;
  33404. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33405. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33406. for (row = 0; row <= subdivisionsY; row++) {
  33407. for (col = 0; col <= subdivisionsX; col++) {
  33408. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33409. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33410. positions.push(position.x, position.y, position.z);
  33411. normals.push(normal.x, normal.y, normal.z);
  33412. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  33413. }
  33414. }
  33415. for (row = 0; row < subdivisionsY; row++) {
  33416. for (col = 0; col < subdivisionsX; col++) {
  33417. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33418. indices.push(col + 1 + row * (subdivisionsX + 1));
  33419. indices.push(col + row * (subdivisionsX + 1));
  33420. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33421. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33422. indices.push(col + row * (subdivisionsX + 1));
  33423. }
  33424. }
  33425. // Result
  33426. var vertexData = new VertexData();
  33427. vertexData.indices = indices;
  33428. vertexData.positions = positions;
  33429. vertexData.normals = normals;
  33430. vertexData.uvs = uvs;
  33431. return vertexData;
  33432. };
  33433. VertexData.CreateTiledGround = function (options) {
  33434. var xmin = options.xmin || -1.0;
  33435. var zmin = options.zmin || -1.0;
  33436. var xmax = options.xmax || 1.0;
  33437. var zmax = options.zmax || 1.0;
  33438. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33439. var precision = options.precision || { w: 1, h: 1 };
  33440. var indices = [];
  33441. var positions = [];
  33442. var normals = [];
  33443. var uvs = [];
  33444. var row, col, tileRow, tileCol;
  33445. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33446. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33447. precision.w = (precision.w < 1) ? 1 : precision.w;
  33448. precision.h = (precision.h < 1) ? 1 : precision.h;
  33449. var tileSize = {
  33450. 'w': (xmax - xmin) / subdivisions.w,
  33451. 'h': (zmax - zmin) / subdivisions.h
  33452. };
  33453. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33454. // Indices
  33455. var base = positions.length / 3;
  33456. var rowLength = precision.w + 1;
  33457. for (row = 0; row < precision.h; row++) {
  33458. for (col = 0; col < precision.w; col++) {
  33459. var square = [
  33460. base + col + row * rowLength,
  33461. base + (col + 1) + row * rowLength,
  33462. base + (col + 1) + (row + 1) * rowLength,
  33463. base + col + (row + 1) * rowLength
  33464. ];
  33465. indices.push(square[1]);
  33466. indices.push(square[2]);
  33467. indices.push(square[3]);
  33468. indices.push(square[0]);
  33469. indices.push(square[1]);
  33470. indices.push(square[3]);
  33471. }
  33472. }
  33473. // Position, normals and uvs
  33474. var position = BABYLON.Vector3.Zero();
  33475. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33476. for (row = 0; row <= precision.h; row++) {
  33477. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33478. for (col = 0; col <= precision.w; col++) {
  33479. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33480. position.y = 0;
  33481. positions.push(position.x, position.y, position.z);
  33482. normals.push(normal.x, normal.y, normal.z);
  33483. uvs.push(col / precision.w, row / precision.h);
  33484. }
  33485. }
  33486. }
  33487. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33488. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33489. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33490. }
  33491. }
  33492. // Result
  33493. var vertexData = new VertexData();
  33494. vertexData.indices = indices;
  33495. vertexData.positions = positions;
  33496. vertexData.normals = normals;
  33497. vertexData.uvs = uvs;
  33498. return vertexData;
  33499. };
  33500. VertexData.CreateGroundFromHeightMap = function (options) {
  33501. var indices = [];
  33502. var positions = [];
  33503. var normals = [];
  33504. var uvs = [];
  33505. var row, col;
  33506. // Vertices
  33507. for (row = 0; row <= options.subdivisions; row++) {
  33508. for (col = 0; col <= options.subdivisions; col++) {
  33509. 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));
  33510. // Compute height
  33511. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33512. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33513. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33514. var r = options.buffer[pos] / 255.0;
  33515. var g = options.buffer[pos + 1] / 255.0;
  33516. var b = options.buffer[pos + 2] / 255.0;
  33517. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33518. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33519. // Add vertex
  33520. positions.push(position.x, position.y, position.z);
  33521. normals.push(0, 0, 0);
  33522. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33523. }
  33524. }
  33525. // Indices
  33526. for (row = 0; row < options.subdivisions; row++) {
  33527. for (col = 0; col < options.subdivisions; col++) {
  33528. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33529. indices.push(col + 1 + row * (options.subdivisions + 1));
  33530. indices.push(col + row * (options.subdivisions + 1));
  33531. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33532. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33533. indices.push(col + row * (options.subdivisions + 1));
  33534. }
  33535. }
  33536. // Normals
  33537. VertexData.ComputeNormals(positions, indices, normals);
  33538. // Result
  33539. var vertexData = new VertexData();
  33540. vertexData.indices = indices;
  33541. vertexData.positions = positions;
  33542. vertexData.normals = normals;
  33543. vertexData.uvs = uvs;
  33544. return vertexData;
  33545. };
  33546. VertexData.CreatePlane = function (options) {
  33547. var indices = [];
  33548. var positions = [];
  33549. var normals = [];
  33550. var uvs = [];
  33551. var width = options.width || options.size || 1;
  33552. var height = options.height || options.size || 1;
  33553. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33554. // Vertices
  33555. var halfWidth = width / 2.0;
  33556. var halfHeight = height / 2.0;
  33557. positions.push(-halfWidth, -halfHeight, 0);
  33558. normals.push(0, 0, -1.0);
  33559. uvs.push(0.0, 0.0);
  33560. positions.push(halfWidth, -halfHeight, 0);
  33561. normals.push(0, 0, -1.0);
  33562. uvs.push(1.0, 0.0);
  33563. positions.push(halfWidth, halfHeight, 0);
  33564. normals.push(0, 0, -1.0);
  33565. uvs.push(1.0, 1.0);
  33566. positions.push(-halfWidth, halfHeight, 0);
  33567. normals.push(0, 0, -1.0);
  33568. uvs.push(0.0, 1.0);
  33569. // Indices
  33570. indices.push(0);
  33571. indices.push(1);
  33572. indices.push(2);
  33573. indices.push(0);
  33574. indices.push(2);
  33575. indices.push(3);
  33576. // Sides
  33577. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33578. // Result
  33579. var vertexData = new VertexData();
  33580. vertexData.indices = indices;
  33581. vertexData.positions = positions;
  33582. vertexData.normals = normals;
  33583. vertexData.uvs = uvs;
  33584. return vertexData;
  33585. };
  33586. VertexData.CreateDisc = function (options) {
  33587. var positions = [];
  33588. var indices = [];
  33589. var normals = [];
  33590. var uvs = [];
  33591. var radius = options.radius || 0.5;
  33592. var tessellation = options.tessellation || 64;
  33593. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33594. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33595. // positions and uvs
  33596. positions.push(0, 0, 0); // disc center first
  33597. uvs.push(0.5, 0.5);
  33598. var theta = Math.PI * 2 * arc;
  33599. var step = theta / tessellation;
  33600. for (var a = 0; a < theta; a += step) {
  33601. var x = Math.cos(a);
  33602. var y = Math.sin(a);
  33603. var u = (x + 1) / 2;
  33604. var v = (1 - y) / 2;
  33605. positions.push(radius * x, radius * y, 0);
  33606. uvs.push(u, v);
  33607. }
  33608. if (arc === 1) {
  33609. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33610. uvs.push(uvs[2], uvs[3]);
  33611. }
  33612. //indices
  33613. var vertexNb = positions.length / 3;
  33614. for (var i = 1; i < vertexNb - 1; i++) {
  33615. indices.push(i + 1, 0, i);
  33616. }
  33617. // result
  33618. VertexData.ComputeNormals(positions, indices, normals);
  33619. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33620. var vertexData = new VertexData();
  33621. vertexData.indices = indices;
  33622. vertexData.positions = positions;
  33623. vertexData.normals = normals;
  33624. vertexData.uvs = uvs;
  33625. return vertexData;
  33626. };
  33627. VertexData.CreateIcoSphere = function (options) {
  33628. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33629. var radius = options.radius || 1;
  33630. var flat = (options.flat === undefined) ? true : options.flat;
  33631. var subdivisions = options.subdivisions || 4;
  33632. var radiusX = options.radiusX || radius;
  33633. var radiusY = options.radiusY || radius;
  33634. var radiusZ = options.radiusZ || radius;
  33635. var t = (1 + Math.sqrt(5)) / 2;
  33636. // 12 vertex x,y,z
  33637. var ico_vertices = [
  33638. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33639. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33640. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33641. ];
  33642. // index of 3 vertex makes a face of icopshere
  33643. var ico_indices = [
  33644. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33645. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33646. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33647. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33648. ];
  33649. // vertex for uv have aliased position, not for UV
  33650. var vertices_unalias_id = [
  33651. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33652. // vertex alias
  33653. 0,
  33654. 2,
  33655. 3,
  33656. 3,
  33657. 3,
  33658. 4,
  33659. 7,
  33660. 8,
  33661. 9,
  33662. 9,
  33663. 10,
  33664. 11 // 23: B + 12
  33665. ];
  33666. // uv as integer step (not pixels !)
  33667. var ico_vertexuv = [
  33668. 5, 1, 3, 1, 6, 4, 0, 0,
  33669. 5, 3, 4, 2, 2, 2, 4, 0,
  33670. 2, 0, 1, 1, 6, 0, 6, 2,
  33671. // vertex alias (for same vertex on different faces)
  33672. 0, 4,
  33673. 3, 3,
  33674. 4, 4,
  33675. 3, 1,
  33676. 4, 2,
  33677. 4, 4,
  33678. 0, 2,
  33679. 1, 1,
  33680. 2, 2,
  33681. 3, 3,
  33682. 1, 3,
  33683. 2, 4 // 23: B + 12
  33684. ];
  33685. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33686. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33687. // First island of uv mapping
  33688. // v = 4h 3+ 2
  33689. // v = 3h 9+ 4
  33690. // v = 2h 9+ 5 B
  33691. // v = 1h 9 1 0
  33692. // v = 0h 3 8 7 A
  33693. // u = 0 1 2 3 4 5 6 *a
  33694. // Second island of uv mapping
  33695. // v = 4h 0+ B+ 4+
  33696. // v = 3h A+ 2+
  33697. // v = 2h 7+ 6 3+
  33698. // v = 1h 8+ 3+
  33699. // v = 0h
  33700. // u = 0 1 2 3 4 5 6 *a
  33701. // Face layout on texture UV mapping
  33702. // ============
  33703. // \ 4 /\ 16 / ======
  33704. // \ / \ / /\ 11 /
  33705. // \/ 7 \/ / \ /
  33706. // ======= / 10 \/
  33707. // /\ 17 /\ =======
  33708. // / \ / \ \ 15 /\
  33709. // / 8 \/ 12 \ \ / \
  33710. // ============ \/ 6 \
  33711. // \ 18 /\ ============
  33712. // \ / \ \ 5 /\ 0 /
  33713. // \/ 13 \ \ / \ /
  33714. // ======= \/ 1 \/
  33715. // =============
  33716. // /\ 19 /\ 2 /\
  33717. // / \ / \ / \
  33718. // / 14 \/ 9 \/ 3 \
  33719. // ===================
  33720. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33721. var ustep = 138 / 1024;
  33722. var vstep = 239 / 1024;
  33723. var uoffset = 60 / 1024;
  33724. var voffset = 26 / 1024;
  33725. // Second island should have margin, not to touch the first island
  33726. // avoid any borderline artefact in pixel rounding
  33727. var island_u_offset = -40 / 1024;
  33728. var island_v_offset = +20 / 1024;
  33729. // face is either island 0 or 1 :
  33730. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33731. var island = [
  33732. 0, 0, 0, 0, 1,
  33733. 0, 0, 1, 1, 0,
  33734. 0, 0, 1, 1, 0,
  33735. 0, 1, 1, 1, 0 // 15 - 19
  33736. ];
  33737. var indices = [];
  33738. var positions = [];
  33739. var normals = [];
  33740. var uvs = [];
  33741. var current_indice = 0;
  33742. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33743. var face_vertex_pos = new Array(3);
  33744. var face_vertex_uv = new Array(3);
  33745. var v012;
  33746. for (v012 = 0; v012 < 3; v012++) {
  33747. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33748. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33749. }
  33750. // create all with normals
  33751. for (var face = 0; face < 20; face++) {
  33752. // 3 vertex per face
  33753. for (v012 = 0; v012 < 3; v012++) {
  33754. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33755. var v_id = ico_indices[3 * face + v012];
  33756. // vertex have 3D position (x,y,z)
  33757. 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]);
  33758. // Normalize to get normal, then scale to radius
  33759. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33760. // uv Coordinates from vertex ID
  33761. 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);
  33762. }
  33763. // Subdivide the face (interpolate pos, norm, uv)
  33764. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33765. // - norm is linear interpolation of vertex corner normal
  33766. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33767. // - uv is linear interpolation
  33768. //
  33769. // Topology is as below for sub-divide by 2
  33770. // vertex shown as v0,v1,v2
  33771. // interp index is i1 to progress in range [v0,v1[
  33772. // interp index is i2 to progress in range [v0,v2[
  33773. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33774. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33775. //
  33776. //
  33777. // i2 v2
  33778. // ^ ^
  33779. // / / \
  33780. // / / \
  33781. // / / \
  33782. // / / (0,1) \
  33783. // / #---------\
  33784. // / / \ (0,0)'/ \
  33785. // / / \ / \
  33786. // / / \ / \
  33787. // / / (0,0) \ / (1,0) \
  33788. // / #---------#---------\
  33789. // v0 v1
  33790. //
  33791. // --------------------> i1
  33792. //
  33793. // interp of (i1,i2):
  33794. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33795. // along i1 : lerp(x0,x1, i1/(S-i2))
  33796. //
  33797. // centroid of triangle is needed to get help normal computation
  33798. // (c1,c2) are used for centroid location
  33799. var interp_vertex = function (i1, i2, c1, c2) {
  33800. // vertex is interpolated from
  33801. // - face_vertex_pos[0..2]
  33802. // - face_vertex_uv[0..2]
  33803. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33804. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33805. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33806. pos_interp.normalize();
  33807. var vertex_normal;
  33808. if (flat) {
  33809. // in flat mode, recalculate normal as face centroid normal
  33810. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33811. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33812. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33813. }
  33814. else {
  33815. // in smooth mode, recalculate normal from each single vertex position
  33816. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33817. }
  33818. // Vertex normal need correction due to X,Y,Z radius scaling
  33819. vertex_normal.x /= radiusX;
  33820. vertex_normal.y /= radiusY;
  33821. vertex_normal.z /= radiusZ;
  33822. vertex_normal.normalize();
  33823. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33824. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33825. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33826. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33827. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33828. uvs.push(uv_interp.x, uv_interp.y);
  33829. // push each vertex has member of a face
  33830. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33831. indices.push(current_indice);
  33832. current_indice++;
  33833. };
  33834. for (var i2 = 0; i2 < subdivisions; i2++) {
  33835. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33836. // face : (i1,i2) for /\ :
  33837. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33838. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33839. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33840. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33841. if (i1 + i2 + 1 < subdivisions) {
  33842. // face : (i1,i2)' for \/ :
  33843. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33844. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33845. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33846. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33847. }
  33848. }
  33849. }
  33850. }
  33851. // Sides
  33852. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33853. // Result
  33854. var vertexData = new VertexData();
  33855. vertexData.indices = indices;
  33856. vertexData.positions = positions;
  33857. vertexData.normals = normals;
  33858. vertexData.uvs = uvs;
  33859. return vertexData;
  33860. };
  33861. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33862. VertexData.CreatePolyhedron = function (options) {
  33863. // provided polyhedron types :
  33864. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33865. // 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)
  33866. var polyhedra = [];
  33867. 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]] };
  33868. 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]] };
  33869. polyhedra[2] = {
  33870. 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]],
  33871. 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]]
  33872. };
  33873. polyhedra[3] = {
  33874. 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]],
  33875. 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]]
  33876. };
  33877. polyhedra[4] = {
  33878. 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]],
  33879. 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]]
  33880. };
  33881. 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]] };
  33882. 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]] };
  33883. 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]] };
  33884. 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]] };
  33885. 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]] };
  33886. 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]] };
  33887. 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]] };
  33888. 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]] };
  33889. 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]] };
  33890. polyhedra[14] = {
  33891. 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]],
  33892. 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]]
  33893. };
  33894. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33895. var size = options.size;
  33896. var sizeX = options.sizeX || size || 1;
  33897. var sizeY = options.sizeY || size || 1;
  33898. var sizeZ = options.sizeZ || size || 1;
  33899. var data = options.custom || polyhedra[type];
  33900. var nbfaces = data.face.length;
  33901. var faceUV = options.faceUV || new Array(nbfaces);
  33902. var faceColors = options.faceColors;
  33903. var flat = (options.flat === undefined) ? true : options.flat;
  33904. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33905. var positions = [];
  33906. var indices = [];
  33907. var normals = [];
  33908. var uvs = [];
  33909. var colors = [];
  33910. var index = 0;
  33911. var faceIdx = 0; // face cursor in the array "indexes"
  33912. var indexes = [];
  33913. var i = 0;
  33914. var f = 0;
  33915. var u, v, ang, x, y, tmp;
  33916. // default face colors and UV if undefined
  33917. if (flat) {
  33918. for (f = 0; f < nbfaces; f++) {
  33919. if (faceColors && faceColors[f] === undefined) {
  33920. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33921. }
  33922. if (faceUV && faceUV[f] === undefined) {
  33923. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33924. }
  33925. }
  33926. }
  33927. if (!flat) {
  33928. for (i = 0; i < data.vertex.length; i++) {
  33929. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33930. uvs.push(0, 0);
  33931. }
  33932. for (f = 0; f < nbfaces; f++) {
  33933. for (i = 0; i < data.face[f].length - 2; i++) {
  33934. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33935. }
  33936. }
  33937. }
  33938. else {
  33939. for (f = 0; f < nbfaces; f++) {
  33940. var fl = data.face[f].length; // number of vertices of the current face
  33941. ang = 2 * Math.PI / fl;
  33942. x = 0.5 * Math.tan(ang / 2);
  33943. y = 0.5;
  33944. // positions, uvs, colors
  33945. for (i = 0; i < fl; i++) {
  33946. // positions
  33947. 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);
  33948. indexes.push(index);
  33949. index++;
  33950. // uvs
  33951. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33952. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33953. uvs.push(u, v);
  33954. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33955. y = x * Math.sin(ang) + y * Math.cos(ang);
  33956. x = tmp;
  33957. // colors
  33958. if (faceColors) {
  33959. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33960. }
  33961. }
  33962. // indices from indexes
  33963. for (i = 0; i < fl - 2; i++) {
  33964. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33965. }
  33966. faceIdx += fl;
  33967. }
  33968. }
  33969. VertexData.ComputeNormals(positions, indices, normals);
  33970. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33971. var vertexData = new VertexData();
  33972. vertexData.positions = positions;
  33973. vertexData.indices = indices;
  33974. vertexData.normals = normals;
  33975. vertexData.uvs = uvs;
  33976. if (faceColors && flat) {
  33977. vertexData.colors = colors;
  33978. }
  33979. return vertexData;
  33980. };
  33981. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33982. VertexData.CreateTorusKnot = function (options) {
  33983. var indices = [];
  33984. var positions = [];
  33985. var normals = [];
  33986. var uvs = [];
  33987. var radius = options.radius || 2;
  33988. var tube = options.tube || 0.5;
  33989. var radialSegments = options.radialSegments || 32;
  33990. var tubularSegments = options.tubularSegments || 32;
  33991. var p = options.p || 2;
  33992. var q = options.q || 3;
  33993. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33994. // Helper
  33995. var getPos = function (angle) {
  33996. var cu = Math.cos(angle);
  33997. var su = Math.sin(angle);
  33998. var quOverP = q / p * angle;
  33999. var cs = Math.cos(quOverP);
  34000. var tx = radius * (2 + cs) * 0.5 * cu;
  34001. var ty = radius * (2 + cs) * su * 0.5;
  34002. var tz = radius * Math.sin(quOverP) * 0.5;
  34003. return new BABYLON.Vector3(tx, ty, tz);
  34004. };
  34005. // Vertices
  34006. var i;
  34007. var j;
  34008. for (i = 0; i <= radialSegments; i++) {
  34009. var modI = i % radialSegments;
  34010. var u = modI / radialSegments * 2 * p * Math.PI;
  34011. var p1 = getPos(u);
  34012. var p2 = getPos(u + 0.01);
  34013. var tang = p2.subtract(p1);
  34014. var n = p2.add(p1);
  34015. var bitan = BABYLON.Vector3.Cross(tang, n);
  34016. n = BABYLON.Vector3.Cross(bitan, tang);
  34017. bitan.normalize();
  34018. n.normalize();
  34019. for (j = 0; j < tubularSegments; j++) {
  34020. var modJ = j % tubularSegments;
  34021. var v = modJ / tubularSegments * 2 * Math.PI;
  34022. var cx = -tube * Math.cos(v);
  34023. var cy = tube * Math.sin(v);
  34024. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34025. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34026. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34027. uvs.push(i / radialSegments);
  34028. uvs.push(j / tubularSegments);
  34029. }
  34030. }
  34031. for (i = 0; i < radialSegments; i++) {
  34032. for (j = 0; j < tubularSegments; j++) {
  34033. var jNext = (j + 1) % tubularSegments;
  34034. var a = i * tubularSegments + j;
  34035. var b = (i + 1) * tubularSegments + j;
  34036. var c = (i + 1) * tubularSegments + jNext;
  34037. var d = i * tubularSegments + jNext;
  34038. indices.push(d);
  34039. indices.push(b);
  34040. indices.push(a);
  34041. indices.push(d);
  34042. indices.push(c);
  34043. indices.push(b);
  34044. }
  34045. }
  34046. // Normals
  34047. VertexData.ComputeNormals(positions, indices, normals);
  34048. // Sides
  34049. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34050. // Result
  34051. var vertexData = new VertexData();
  34052. vertexData.indices = indices;
  34053. vertexData.positions = positions;
  34054. vertexData.normals = normals;
  34055. vertexData.uvs = uvs;
  34056. return vertexData;
  34057. };
  34058. // Tools
  34059. /**
  34060. * @param {any} - positions (number[] or Float32Array)
  34061. * @param {any} - indices (number[] or Uint16Array)
  34062. * @param {any} - normals (number[] or Float32Array)
  34063. */
  34064. VertexData.ComputeNormals = function (positions, indices, normals) {
  34065. var index = 0;
  34066. var p1p2x = 0.0;
  34067. var p1p2y = 0.0;
  34068. var p1p2z = 0.0;
  34069. var p3p2x = 0.0;
  34070. var p3p2y = 0.0;
  34071. var p3p2z = 0.0;
  34072. var faceNormalx = 0.0;
  34073. var faceNormaly = 0.0;
  34074. var faceNormalz = 0.0;
  34075. var length = 0.0;
  34076. var i1 = 0;
  34077. var i2 = 0;
  34078. var i3 = 0;
  34079. for (index = 0; index < positions.length; index++) {
  34080. normals[index] = 0.0;
  34081. }
  34082. // indice triplet = 1 face
  34083. var nbFaces = indices.length / 3;
  34084. for (index = 0; index < nbFaces; index++) {
  34085. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  34086. i2 = indices[index * 3 + 1];
  34087. i3 = indices[index * 3 + 2];
  34088. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  34089. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  34090. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  34091. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  34092. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  34093. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  34094. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  34095. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  34096. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  34097. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34098. length = (length === 0) ? 1.0 : length;
  34099. faceNormalx /= length; // normalize this normal
  34100. faceNormaly /= length;
  34101. faceNormalz /= length;
  34102. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  34103. normals[i1 * 3 + 1] += faceNormaly;
  34104. normals[i1 * 3 + 2] += faceNormalz;
  34105. normals[i2 * 3] += faceNormalx;
  34106. normals[i2 * 3 + 1] += faceNormaly;
  34107. normals[i2 * 3 + 2] += faceNormalz;
  34108. normals[i3 * 3] += faceNormalx;
  34109. normals[i3 * 3 + 1] += faceNormaly;
  34110. normals[i3 * 3 + 2] += faceNormalz;
  34111. }
  34112. // last normalization of each normal
  34113. for (index = 0; index < normals.length / 3; index++) {
  34114. faceNormalx = normals[index * 3];
  34115. faceNormaly = normals[index * 3 + 1];
  34116. faceNormalz = normals[index * 3 + 2];
  34117. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34118. length = (length === 0) ? 1.0 : length;
  34119. faceNormalx /= length;
  34120. faceNormaly /= length;
  34121. faceNormalz /= length;
  34122. normals[index * 3] = faceNormalx;
  34123. normals[index * 3 + 1] = faceNormaly;
  34124. normals[index * 3 + 2] = faceNormalz;
  34125. }
  34126. };
  34127. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  34128. var li = indices.length;
  34129. var ln = normals.length;
  34130. var i;
  34131. var n;
  34132. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34133. switch (sideOrientation) {
  34134. case BABYLON.Mesh.FRONTSIDE:
  34135. // nothing changed
  34136. break;
  34137. case BABYLON.Mesh.BACKSIDE:
  34138. var tmp;
  34139. // indices
  34140. for (i = 0; i < li; i += 3) {
  34141. tmp = indices[i];
  34142. indices[i] = indices[i + 2];
  34143. indices[i + 2] = tmp;
  34144. }
  34145. // normals
  34146. for (n = 0; n < ln; n++) {
  34147. normals[n] = -normals[n];
  34148. }
  34149. break;
  34150. case BABYLON.Mesh.DOUBLESIDE:
  34151. // positions
  34152. var lp = positions.length;
  34153. var l = lp / 3;
  34154. for (var p = 0; p < lp; p++) {
  34155. positions[lp + p] = positions[p];
  34156. }
  34157. // indices
  34158. for (i = 0; i < li; i += 3) {
  34159. indices[i + li] = indices[i + 2] + l;
  34160. indices[i + 1 + li] = indices[i + 1] + l;
  34161. indices[i + 2 + li] = indices[i] + l;
  34162. }
  34163. // normals
  34164. for (n = 0; n < ln; n++) {
  34165. normals[ln + n] = -normals[n];
  34166. }
  34167. // uvs
  34168. var lu = uvs.length;
  34169. for (var u = 0; u < lu; u++) {
  34170. uvs[u + lu] = uvs[u];
  34171. }
  34172. break;
  34173. }
  34174. };
  34175. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34176. var vertexData = new VertexData();
  34177. // positions
  34178. var positions = parsedVertexData.positions;
  34179. if (positions) {
  34180. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34181. }
  34182. // normals
  34183. var normals = parsedVertexData.normals;
  34184. if (normals) {
  34185. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34186. }
  34187. // uvs
  34188. var uvs = parsedVertexData.uvs;
  34189. if (uvs) {
  34190. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34191. }
  34192. // uv2s
  34193. var uv2s = parsedVertexData.uv2s;
  34194. if (uv2s) {
  34195. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34196. }
  34197. // uv3s
  34198. var uv3s = parsedVertexData.uv3s;
  34199. if (uv3s) {
  34200. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34201. }
  34202. // uv4s
  34203. var uv4s = parsedVertexData.uv4s;
  34204. if (uv4s) {
  34205. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34206. }
  34207. // uv5s
  34208. var uv5s = parsedVertexData.uv5s;
  34209. if (uv5s) {
  34210. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34211. }
  34212. // uv6s
  34213. var uv6s = parsedVertexData.uv6s;
  34214. if (uv6s) {
  34215. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34216. }
  34217. // colors
  34218. var colors = parsedVertexData.colors;
  34219. if (colors) {
  34220. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34221. }
  34222. // matricesIndices
  34223. var matricesIndices = parsedVertexData.matricesIndices;
  34224. if (matricesIndices) {
  34225. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34226. }
  34227. // matricesWeights
  34228. var matricesWeights = parsedVertexData.matricesWeights;
  34229. if (matricesWeights) {
  34230. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34231. }
  34232. // indices
  34233. var indices = parsedVertexData.indices;
  34234. if (indices) {
  34235. vertexData.indices = indices;
  34236. }
  34237. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34238. };
  34239. return VertexData;
  34240. }());
  34241. BABYLON.VertexData = VertexData;
  34242. })(BABYLON || (BABYLON = {}));
  34243. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34244. var BABYLON;
  34245. (function (BABYLON) {
  34246. var Tags = (function () {
  34247. function Tags() {
  34248. }
  34249. Tags.EnableFor = function (obj) {
  34250. obj._tags = obj._tags || {};
  34251. obj.hasTags = function () {
  34252. return Tags.HasTags(obj);
  34253. };
  34254. obj.addTags = function (tagsString) {
  34255. return Tags.AddTagsTo(obj, tagsString);
  34256. };
  34257. obj.removeTags = function (tagsString) {
  34258. return Tags.RemoveTagsFrom(obj, tagsString);
  34259. };
  34260. obj.matchesTagsQuery = function (tagsQuery) {
  34261. return Tags.MatchesQuery(obj, tagsQuery);
  34262. };
  34263. };
  34264. Tags.DisableFor = function (obj) {
  34265. delete obj._tags;
  34266. delete obj.hasTags;
  34267. delete obj.addTags;
  34268. delete obj.removeTags;
  34269. delete obj.matchesTagsQuery;
  34270. };
  34271. Tags.HasTags = function (obj) {
  34272. if (!obj._tags) {
  34273. return false;
  34274. }
  34275. return !BABYLON.Tools.IsEmpty(obj._tags);
  34276. };
  34277. Tags.GetTags = function (obj, asString) {
  34278. if (asString === void 0) { asString = true; }
  34279. if (!obj._tags) {
  34280. return null;
  34281. }
  34282. if (asString) {
  34283. var tagsArray = [];
  34284. for (var tag in obj._tags) {
  34285. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  34286. tagsArray.push(tag);
  34287. }
  34288. }
  34289. return tagsArray.join(" ");
  34290. }
  34291. else {
  34292. return obj._tags;
  34293. }
  34294. };
  34295. // the tags 'true' and 'false' are reserved and cannot be used as tags
  34296. // a tag cannot start with '||', '&&', and '!'
  34297. // it cannot contain whitespaces
  34298. Tags.AddTagsTo = function (obj, tagsString) {
  34299. if (!tagsString) {
  34300. return;
  34301. }
  34302. if (typeof tagsString !== "string") {
  34303. return;
  34304. }
  34305. var tags = tagsString.split(" ");
  34306. tags.forEach(function (tag, index, array) {
  34307. Tags._AddTagTo(obj, tag);
  34308. });
  34309. };
  34310. Tags._AddTagTo = function (obj, tag) {
  34311. tag = tag.trim();
  34312. if (tag === "" || tag === "true" || tag === "false") {
  34313. return;
  34314. }
  34315. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  34316. return;
  34317. }
  34318. Tags.EnableFor(obj);
  34319. obj._tags[tag] = true;
  34320. };
  34321. Tags.RemoveTagsFrom = function (obj, tagsString) {
  34322. if (!Tags.HasTags(obj)) {
  34323. return;
  34324. }
  34325. var tags = tagsString.split(" ");
  34326. for (var t in tags) {
  34327. Tags._RemoveTagFrom(obj, tags[t]);
  34328. }
  34329. };
  34330. Tags._RemoveTagFrom = function (obj, tag) {
  34331. delete obj._tags[tag];
  34332. };
  34333. Tags.MatchesQuery = function (obj, tagsQuery) {
  34334. if (tagsQuery === undefined) {
  34335. return true;
  34336. }
  34337. if (tagsQuery === "") {
  34338. return Tags.HasTags(obj);
  34339. }
  34340. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  34341. };
  34342. return Tags;
  34343. }());
  34344. BABYLON.Tags = Tags;
  34345. })(BABYLON || (BABYLON = {}));
  34346. //# sourceMappingURL=babylon.tags.js.map
  34347. var BABYLON;
  34348. (function (BABYLON) {
  34349. var Internals;
  34350. (function (Internals) {
  34351. var AndOrNotEvaluator = (function () {
  34352. function AndOrNotEvaluator() {
  34353. }
  34354. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  34355. if (!query.match(/\([^\(\)]*\)/g)) {
  34356. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  34357. }
  34358. else {
  34359. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  34360. // remove parenthesis
  34361. r = r.slice(1, r.length - 1);
  34362. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  34363. });
  34364. }
  34365. if (query === "true") {
  34366. return true;
  34367. }
  34368. if (query === "false") {
  34369. return false;
  34370. }
  34371. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  34372. };
  34373. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  34374. evaluateCallback = evaluateCallback || (function (r) {
  34375. return r === "true" ? true : false;
  34376. });
  34377. var result;
  34378. var or = parenthesisContent.split("||");
  34379. for (var i in or) {
  34380. if (or.hasOwnProperty(i)) {
  34381. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  34382. var and = ori.split("&&");
  34383. if (and.length > 1) {
  34384. for (var j = 0; j < and.length; ++j) {
  34385. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  34386. if (andj !== "true" && andj !== "false") {
  34387. if (andj[0] === "!") {
  34388. result = !evaluateCallback(andj.substring(1));
  34389. }
  34390. else {
  34391. result = evaluateCallback(andj);
  34392. }
  34393. }
  34394. else {
  34395. result = andj === "true" ? true : false;
  34396. }
  34397. if (!result) {
  34398. ori = "false";
  34399. break;
  34400. }
  34401. }
  34402. }
  34403. if (result || ori === "true") {
  34404. result = true;
  34405. break;
  34406. }
  34407. // result equals false (or undefined)
  34408. if (ori !== "true" && ori !== "false") {
  34409. if (ori[0] === "!") {
  34410. result = !evaluateCallback(ori.substring(1));
  34411. }
  34412. else {
  34413. result = evaluateCallback(ori);
  34414. }
  34415. }
  34416. else {
  34417. result = ori === "true" ? true : false;
  34418. }
  34419. }
  34420. }
  34421. // the whole parenthesis scope is replaced by 'true' or 'false'
  34422. return result ? "true" : "false";
  34423. };
  34424. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  34425. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  34426. // remove whitespaces
  34427. r = r.replace(/[\s]/g, function () { return ""; });
  34428. return r.length % 2 ? "!" : "";
  34429. });
  34430. booleanString = booleanString.trim();
  34431. if (booleanString === "!true") {
  34432. booleanString = "false";
  34433. }
  34434. else if (booleanString === "!false") {
  34435. booleanString = "true";
  34436. }
  34437. return booleanString;
  34438. };
  34439. return AndOrNotEvaluator;
  34440. }());
  34441. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  34442. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34443. })(BABYLON || (BABYLON = {}));
  34444. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  34445. var BABYLON;
  34446. (function (BABYLON) {
  34447. var PostProcessRenderPass = (function () {
  34448. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  34449. this._enabled = true;
  34450. this._refCount = 0;
  34451. this._name = name;
  34452. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  34453. this.setRenderList(renderList);
  34454. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  34455. this._renderTexture.onAfterRenderObservable.add(afterRender);
  34456. this._scene = scene;
  34457. this._renderList = renderList;
  34458. }
  34459. // private
  34460. PostProcessRenderPass.prototype._incRefCount = function () {
  34461. if (this._refCount === 0) {
  34462. this._scene.customRenderTargets.push(this._renderTexture);
  34463. }
  34464. return ++this._refCount;
  34465. };
  34466. PostProcessRenderPass.prototype._decRefCount = function () {
  34467. this._refCount--;
  34468. if (this._refCount <= 0) {
  34469. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  34470. }
  34471. return this._refCount;
  34472. };
  34473. PostProcessRenderPass.prototype._update = function () {
  34474. this.setRenderList(this._renderList);
  34475. };
  34476. // public
  34477. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  34478. this._renderTexture.renderList = renderList;
  34479. };
  34480. PostProcessRenderPass.prototype.getRenderTexture = function () {
  34481. return this._renderTexture;
  34482. };
  34483. return PostProcessRenderPass;
  34484. }());
  34485. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  34486. })(BABYLON || (BABYLON = {}));
  34487. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  34488. var BABYLON;
  34489. (function (BABYLON) {
  34490. var PostProcessRenderEffect = (function () {
  34491. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  34492. this._engine = engine;
  34493. this._name = name;
  34494. this._singleInstance = singleInstance || true;
  34495. this._getPostProcess = getPostProcess;
  34496. this._cameras = [];
  34497. this._indicesForCamera = [];
  34498. this._postProcesses = {};
  34499. this._renderPasses = {};
  34500. this._renderEffectAsPasses = {};
  34501. }
  34502. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  34503. get: function () {
  34504. for (var index in this._postProcesses) {
  34505. if (!this._postProcesses[index].isSupported) {
  34506. return false;
  34507. }
  34508. }
  34509. return true;
  34510. },
  34511. enumerable: true,
  34512. configurable: true
  34513. });
  34514. PostProcessRenderEffect.prototype._update = function () {
  34515. for (var renderPassName in this._renderPasses) {
  34516. this._renderPasses[renderPassName]._update();
  34517. }
  34518. };
  34519. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  34520. this._renderPasses[renderPass._name] = renderPass;
  34521. this._linkParameters();
  34522. };
  34523. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  34524. delete this._renderPasses[renderPass._name];
  34525. this._linkParameters();
  34526. };
  34527. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  34528. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  34529. this._linkParameters();
  34530. };
  34531. PostProcessRenderEffect.prototype.getPass = function (passName) {
  34532. for (var renderPassName in this._renderPasses) {
  34533. if (renderPassName === passName) {
  34534. return this._renderPasses[passName];
  34535. }
  34536. }
  34537. };
  34538. PostProcessRenderEffect.prototype.emptyPasses = function () {
  34539. this._renderPasses = {};
  34540. this._linkParameters();
  34541. };
  34542. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  34543. var cameraKey;
  34544. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34545. for (var i = 0; i < _cam.length; i++) {
  34546. var camera = _cam[i];
  34547. var cameraName = camera.name;
  34548. if (this._singleInstance) {
  34549. cameraKey = 0;
  34550. }
  34551. else {
  34552. cameraKey = cameraName;
  34553. }
  34554. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  34555. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  34556. if (!this._indicesForCamera[cameraName]) {
  34557. this._indicesForCamera[cameraName] = [];
  34558. }
  34559. this._indicesForCamera[cameraName].push(index);
  34560. if (this._cameras.indexOf(camera) === -1) {
  34561. this._cameras[cameraName] = camera;
  34562. }
  34563. for (var passName in this._renderPasses) {
  34564. this._renderPasses[passName]._incRefCount();
  34565. }
  34566. }
  34567. this._linkParameters();
  34568. };
  34569. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  34570. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34571. for (var i = 0; i < _cam.length; i++) {
  34572. var camera = _cam[i];
  34573. var cameraName = camera.name;
  34574. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34575. var index = this._cameras.indexOf(cameraName);
  34576. this._indicesForCamera.splice(index, 1);
  34577. this._cameras.splice(index, 1);
  34578. for (var passName in this._renderPasses) {
  34579. this._renderPasses[passName]._decRefCount();
  34580. }
  34581. }
  34582. };
  34583. PostProcessRenderEffect.prototype._enable = function (cameras) {
  34584. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34585. for (var i = 0; i < _cam.length; i++) {
  34586. var camera = _cam[i];
  34587. var cameraName = camera.name;
  34588. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  34589. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  34590. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  34591. }
  34592. }
  34593. for (var passName in this._renderPasses) {
  34594. this._renderPasses[passName]._incRefCount();
  34595. }
  34596. }
  34597. };
  34598. PostProcessRenderEffect.prototype._disable = function (cameras) {
  34599. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34600. for (var i = 0; i < _cam.length; i++) {
  34601. var camera = _cam[i];
  34602. var cameraName = camera.Name;
  34603. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34604. for (var passName in this._renderPasses) {
  34605. this._renderPasses[passName]._decRefCount();
  34606. }
  34607. }
  34608. };
  34609. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  34610. if (this._singleInstance) {
  34611. return this._postProcesses[0];
  34612. }
  34613. else {
  34614. return this._postProcesses[camera.name];
  34615. }
  34616. };
  34617. PostProcessRenderEffect.prototype._linkParameters = function () {
  34618. var _this = this;
  34619. for (var index in this._postProcesses) {
  34620. if (this.applyParameters) {
  34621. this.applyParameters(this._postProcesses[index]);
  34622. }
  34623. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  34624. _this._linkTextures(effect);
  34625. });
  34626. }
  34627. };
  34628. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  34629. for (var renderPassName in this._renderPasses) {
  34630. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  34631. }
  34632. for (var renderEffectName in this._renderEffectAsPasses) {
  34633. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  34634. }
  34635. };
  34636. return PostProcessRenderEffect;
  34637. }());
  34638. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  34639. })(BABYLON || (BABYLON = {}));
  34640. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  34641. var BABYLON;
  34642. (function (BABYLON) {
  34643. var PostProcessRenderPipeline = (function () {
  34644. function PostProcessRenderPipeline(engine, name) {
  34645. this._engine = engine;
  34646. this._name = name;
  34647. this._renderEffects = {};
  34648. this._renderEffectsForIsolatedPass = {};
  34649. this._cameras = [];
  34650. }
  34651. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  34652. get: function () {
  34653. for (var renderEffectName in this._renderEffects) {
  34654. if (!this._renderEffects[renderEffectName].isSupported) {
  34655. return false;
  34656. }
  34657. }
  34658. return true;
  34659. },
  34660. enumerable: true,
  34661. configurable: true
  34662. });
  34663. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  34664. this._renderEffects[renderEffect._name] = renderEffect;
  34665. };
  34666. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  34667. var renderEffects = this._renderEffects[renderEffectName];
  34668. if (!renderEffects) {
  34669. return;
  34670. }
  34671. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34672. };
  34673. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  34674. var renderEffects = this._renderEffects[renderEffectName];
  34675. if (!renderEffects) {
  34676. return;
  34677. }
  34678. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34679. };
  34680. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  34681. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34682. var indicesToDelete = [];
  34683. var i;
  34684. for (i = 0; i < _cam.length; i++) {
  34685. var camera = _cam[i];
  34686. var cameraName = camera.name;
  34687. if (this._cameras.indexOf(camera) === -1) {
  34688. this._cameras[cameraName] = camera;
  34689. }
  34690. else if (unique) {
  34691. indicesToDelete.push(i);
  34692. }
  34693. }
  34694. for (i = 0; i < indicesToDelete.length; i++) {
  34695. cameras.splice(indicesToDelete[i], 1);
  34696. }
  34697. for (var renderEffectName in this._renderEffects) {
  34698. this._renderEffects[renderEffectName]._attachCameras(_cam);
  34699. }
  34700. };
  34701. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  34702. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34703. for (var renderEffectName in this._renderEffects) {
  34704. this._renderEffects[renderEffectName]._detachCameras(_cam);
  34705. }
  34706. for (var i = 0; i < _cam.length; i++) {
  34707. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  34708. }
  34709. };
  34710. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  34711. var _this = this;
  34712. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34713. var pass = null;
  34714. var renderEffectName;
  34715. for (renderEffectName in this._renderEffects) {
  34716. pass = this._renderEffects[renderEffectName].getPass(passName);
  34717. if (pass != null) {
  34718. break;
  34719. }
  34720. }
  34721. if (pass === null) {
  34722. return;
  34723. }
  34724. for (renderEffectName in this._renderEffects) {
  34725. this._renderEffects[renderEffectName]._disable(_cam);
  34726. }
  34727. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  34728. for (var i = 0; i < _cam.length; i++) {
  34729. var camera = _cam[i];
  34730. var cameraName = camera.name;
  34731. 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); });
  34732. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  34733. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  34734. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  34735. }
  34736. };
  34737. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  34738. var _this = this;
  34739. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34740. for (var i = 0; i < _cam.length; i++) {
  34741. var camera = _cam[i];
  34742. var cameraName = camera.name;
  34743. 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); });
  34744. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  34745. }
  34746. for (var renderEffectName in this._renderEffects) {
  34747. this._renderEffects[renderEffectName]._enable(_cam);
  34748. }
  34749. };
  34750. PostProcessRenderPipeline.prototype._update = function () {
  34751. for (var renderEffectName in this._renderEffects) {
  34752. this._renderEffects[renderEffectName]._update();
  34753. }
  34754. for (var i = 0; i < this._cameras.length; i++) {
  34755. var cameraName = this._cameras[i].name;
  34756. if (this._renderEffectsForIsolatedPass[cameraName]) {
  34757. this._renderEffectsForIsolatedPass[cameraName]._update();
  34758. }
  34759. }
  34760. };
  34761. PostProcessRenderPipeline.prototype.dispose = function () {
  34762. // Must be implemented by children
  34763. };
  34764. return PostProcessRenderPipeline;
  34765. }());
  34766. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  34767. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  34768. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  34769. })(BABYLON || (BABYLON = {}));
  34770. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  34771. var BABYLON;
  34772. (function (BABYLON) {
  34773. var PostProcessRenderPipelineManager = (function () {
  34774. function PostProcessRenderPipelineManager() {
  34775. this._renderPipelines = {};
  34776. }
  34777. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  34778. this._renderPipelines[renderPipeline._name] = renderPipeline;
  34779. };
  34780. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  34781. var renderPipeline = this._renderPipelines[renderPipelineName];
  34782. if (!renderPipeline) {
  34783. return;
  34784. }
  34785. renderPipeline._attachCameras(cameras, unique);
  34786. };
  34787. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  34788. var renderPipeline = this._renderPipelines[renderPipelineName];
  34789. if (!renderPipeline) {
  34790. return;
  34791. }
  34792. renderPipeline._detachCameras(cameras);
  34793. };
  34794. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34795. var renderPipeline = this._renderPipelines[renderPipelineName];
  34796. if (!renderPipeline) {
  34797. return;
  34798. }
  34799. renderPipeline._enableEffect(renderEffectName, cameras);
  34800. };
  34801. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34802. var renderPipeline = this._renderPipelines[renderPipelineName];
  34803. if (!renderPipeline) {
  34804. return;
  34805. }
  34806. renderPipeline._disableEffect(renderEffectName, cameras);
  34807. };
  34808. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  34809. var renderPipeline = this._renderPipelines[renderPipelineName];
  34810. if (!renderPipeline) {
  34811. return;
  34812. }
  34813. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  34814. };
  34815. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  34816. var renderPipeline = this._renderPipelines[renderPipelineName];
  34817. if (!renderPipeline) {
  34818. return;
  34819. }
  34820. renderPipeline._disableDisplayOnlyPass(cameras);
  34821. };
  34822. PostProcessRenderPipelineManager.prototype.update = function () {
  34823. for (var renderPipelineName in this._renderPipelines) {
  34824. var pipeline = this._renderPipelines[renderPipelineName];
  34825. if (!pipeline.isSupported) {
  34826. pipeline.dispose();
  34827. delete this._renderPipelines[renderPipelineName];
  34828. }
  34829. else {
  34830. pipeline._update();
  34831. }
  34832. }
  34833. };
  34834. return PostProcessRenderPipelineManager;
  34835. }());
  34836. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  34837. })(BABYLON || (BABYLON = {}));
  34838. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  34839. var BABYLON;
  34840. (function (BABYLON) {
  34841. var BoundingBoxRenderer = (function () {
  34842. function BoundingBoxRenderer(scene) {
  34843. this.frontColor = new BABYLON.Color3(1, 1, 1);
  34844. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  34845. this.showBackLines = true;
  34846. this.renderList = new BABYLON.SmartArray(32);
  34847. this._vertexBuffers = {};
  34848. this._scene = scene;
  34849. }
  34850. BoundingBoxRenderer.prototype._prepareRessources = function () {
  34851. if (this._colorShader) {
  34852. return;
  34853. }
  34854. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  34855. attributes: [BABYLON.VertexBuffer.PositionKind],
  34856. uniforms: ["worldViewProjection", "color"]
  34857. });
  34858. var engine = this._scene.getEngine();
  34859. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  34860. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  34861. 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]);
  34862. };
  34863. BoundingBoxRenderer.prototype.reset = function () {
  34864. this.renderList.reset();
  34865. };
  34866. BoundingBoxRenderer.prototype.render = function () {
  34867. if (this.renderList.length === 0) {
  34868. return;
  34869. }
  34870. this._prepareRessources();
  34871. if (!this._colorShader.isReady()) {
  34872. return;
  34873. }
  34874. var engine = this._scene.getEngine();
  34875. engine.setDepthWrite(false);
  34876. this._colorShader._preBind();
  34877. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34878. var boundingBox = this.renderList.data[boundingBoxIndex];
  34879. var min = boundingBox.minimum;
  34880. var max = boundingBox.maximum;
  34881. var diff = max.subtract(min);
  34882. var median = min.add(diff.scale(0.5));
  34883. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  34884. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  34885. .multiply(boundingBox.getWorldMatrix());
  34886. // VBOs
  34887. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  34888. if (this.showBackLines) {
  34889. // Back
  34890. engine.setDepthFunctionToGreaterOrEqual();
  34891. this._scene.resetCachedMaterial();
  34892. this._colorShader.setColor4("color", this.backColor.toColor4());
  34893. this._colorShader.bind(worldMatrix);
  34894. // Draw order
  34895. engine.draw(false, 0, 24);
  34896. }
  34897. // Front
  34898. engine.setDepthFunctionToLess();
  34899. this._scene.resetCachedMaterial();
  34900. this._colorShader.setColor4("color", this.frontColor.toColor4());
  34901. this._colorShader.bind(worldMatrix);
  34902. // Draw order
  34903. engine.draw(false, 0, 24);
  34904. }
  34905. this._colorShader.unbind();
  34906. engine.setDepthFunctionToLessOrEqual();
  34907. engine.setDepthWrite(true);
  34908. };
  34909. BoundingBoxRenderer.prototype.dispose = function () {
  34910. if (!this._colorShader) {
  34911. return;
  34912. }
  34913. this._colorShader.dispose();
  34914. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34915. if (buffer) {
  34916. buffer.dispose();
  34917. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34918. }
  34919. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34920. };
  34921. return BoundingBoxRenderer;
  34922. }());
  34923. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  34924. })(BABYLON || (BABYLON = {}));
  34925. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  34926. var BABYLON;
  34927. (function (BABYLON) {
  34928. var Condition = (function () {
  34929. function Condition(actionManager) {
  34930. this._actionManager = actionManager;
  34931. }
  34932. Condition.prototype.isValid = function () {
  34933. return true;
  34934. };
  34935. Condition.prototype._getProperty = function (propertyPath) {
  34936. return this._actionManager._getProperty(propertyPath);
  34937. };
  34938. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34939. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34940. };
  34941. Condition.prototype.serialize = function () {
  34942. };
  34943. Condition.prototype._serialize = function (serializedCondition) {
  34944. return {
  34945. type: 2,
  34946. children: [],
  34947. name: serializedCondition.name,
  34948. properties: serializedCondition.properties
  34949. };
  34950. };
  34951. return Condition;
  34952. }());
  34953. BABYLON.Condition = Condition;
  34954. var ValueCondition = (function (_super) {
  34955. __extends(ValueCondition, _super);
  34956. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  34957. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  34958. var _this = _super.call(this, actionManager) || this;
  34959. _this.propertyPath = propertyPath;
  34960. _this.value = value;
  34961. _this.operator = operator;
  34962. _this._target = target;
  34963. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  34964. _this._property = _this._getProperty(_this.propertyPath);
  34965. return _this;
  34966. }
  34967. Object.defineProperty(ValueCondition, "IsEqual", {
  34968. get: function () {
  34969. return ValueCondition._IsEqual;
  34970. },
  34971. enumerable: true,
  34972. configurable: true
  34973. });
  34974. Object.defineProperty(ValueCondition, "IsDifferent", {
  34975. get: function () {
  34976. return ValueCondition._IsDifferent;
  34977. },
  34978. enumerable: true,
  34979. configurable: true
  34980. });
  34981. Object.defineProperty(ValueCondition, "IsGreater", {
  34982. get: function () {
  34983. return ValueCondition._IsGreater;
  34984. },
  34985. enumerable: true,
  34986. configurable: true
  34987. });
  34988. Object.defineProperty(ValueCondition, "IsLesser", {
  34989. get: function () {
  34990. return ValueCondition._IsLesser;
  34991. },
  34992. enumerable: true,
  34993. configurable: true
  34994. });
  34995. // Methods
  34996. ValueCondition.prototype.isValid = function () {
  34997. switch (this.operator) {
  34998. case ValueCondition.IsGreater:
  34999. return this._effectiveTarget[this._property] > this.value;
  35000. case ValueCondition.IsLesser:
  35001. return this._effectiveTarget[this._property] < this.value;
  35002. case ValueCondition.IsEqual:
  35003. case ValueCondition.IsDifferent:
  35004. var check;
  35005. if (this.value.equals) {
  35006. check = this.value.equals(this._effectiveTarget[this._property]);
  35007. }
  35008. else {
  35009. check = this.value === this._effectiveTarget[this._property];
  35010. }
  35011. return this.operator === ValueCondition.IsEqual ? check : !check;
  35012. }
  35013. return false;
  35014. };
  35015. ValueCondition.prototype.serialize = function () {
  35016. return this._serialize({
  35017. name: "ValueCondition",
  35018. properties: [
  35019. BABYLON.Action._GetTargetProperty(this._target),
  35020. { name: "propertyPath", value: this.propertyPath },
  35021. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35022. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35023. ]
  35024. });
  35025. };
  35026. ValueCondition.GetOperatorName = function (operator) {
  35027. switch (operator) {
  35028. case ValueCondition._IsEqual: return "IsEqual";
  35029. case ValueCondition._IsDifferent: return "IsDifferent";
  35030. case ValueCondition._IsGreater: return "IsGreater";
  35031. case ValueCondition._IsLesser: return "IsLesser";
  35032. default: return "";
  35033. }
  35034. };
  35035. return ValueCondition;
  35036. }(Condition));
  35037. // Statics
  35038. ValueCondition._IsEqual = 0;
  35039. ValueCondition._IsDifferent = 1;
  35040. ValueCondition._IsGreater = 2;
  35041. ValueCondition._IsLesser = 3;
  35042. BABYLON.ValueCondition = ValueCondition;
  35043. var PredicateCondition = (function (_super) {
  35044. __extends(PredicateCondition, _super);
  35045. function PredicateCondition(actionManager, predicate) {
  35046. var _this = _super.call(this, actionManager) || this;
  35047. _this.predicate = predicate;
  35048. return _this;
  35049. }
  35050. PredicateCondition.prototype.isValid = function () {
  35051. return this.predicate();
  35052. };
  35053. return PredicateCondition;
  35054. }(Condition));
  35055. BABYLON.PredicateCondition = PredicateCondition;
  35056. var StateCondition = (function (_super) {
  35057. __extends(StateCondition, _super);
  35058. function StateCondition(actionManager, target, value) {
  35059. var _this = _super.call(this, actionManager) || this;
  35060. _this.value = value;
  35061. _this._target = target;
  35062. return _this;
  35063. }
  35064. // Methods
  35065. StateCondition.prototype.isValid = function () {
  35066. return this._target.state === this.value;
  35067. };
  35068. StateCondition.prototype.serialize = function () {
  35069. return this._serialize({
  35070. name: "StateCondition",
  35071. properties: [
  35072. BABYLON.Action._GetTargetProperty(this._target),
  35073. { name: "value", value: this.value }
  35074. ]
  35075. });
  35076. };
  35077. return StateCondition;
  35078. }(Condition));
  35079. BABYLON.StateCondition = StateCondition;
  35080. })(BABYLON || (BABYLON = {}));
  35081. //# sourceMappingURL=babylon.condition.js.map
  35082. var BABYLON;
  35083. (function (BABYLON) {
  35084. var Action = (function () {
  35085. function Action(triggerOptions, condition) {
  35086. this.triggerOptions = triggerOptions;
  35087. if (triggerOptions.parameter) {
  35088. this.trigger = triggerOptions.trigger;
  35089. this._triggerParameter = triggerOptions.parameter;
  35090. }
  35091. else {
  35092. this.trigger = triggerOptions;
  35093. }
  35094. this._nextActiveAction = this;
  35095. this._condition = condition;
  35096. }
  35097. // Methods
  35098. Action.prototype._prepare = function () {
  35099. };
  35100. Action.prototype.getTriggerParameter = function () {
  35101. return this._triggerParameter;
  35102. };
  35103. Action.prototype._executeCurrent = function (evt) {
  35104. if (this._nextActiveAction._condition) {
  35105. var condition = this._nextActiveAction._condition;
  35106. var currentRenderId = this._actionManager.getScene().getRenderId();
  35107. // We cache the current evaluation for the current frame
  35108. if (condition._evaluationId === currentRenderId) {
  35109. if (!condition._currentResult) {
  35110. return;
  35111. }
  35112. }
  35113. else {
  35114. condition._evaluationId = currentRenderId;
  35115. if (!condition.isValid()) {
  35116. condition._currentResult = false;
  35117. return;
  35118. }
  35119. condition._currentResult = true;
  35120. }
  35121. }
  35122. this._nextActiveAction.execute(evt);
  35123. this.skipToNextActiveAction();
  35124. };
  35125. Action.prototype.execute = function (evt) {
  35126. };
  35127. Action.prototype.skipToNextActiveAction = function () {
  35128. if (this._nextActiveAction._child) {
  35129. if (!this._nextActiveAction._child._actionManager) {
  35130. this._nextActiveAction._child._actionManager = this._actionManager;
  35131. }
  35132. this._nextActiveAction = this._nextActiveAction._child;
  35133. }
  35134. else {
  35135. this._nextActiveAction = this;
  35136. }
  35137. };
  35138. Action.prototype.then = function (action) {
  35139. this._child = action;
  35140. action._actionManager = this._actionManager;
  35141. action._prepare();
  35142. return action;
  35143. };
  35144. Action.prototype._getProperty = function (propertyPath) {
  35145. return this._actionManager._getProperty(propertyPath);
  35146. };
  35147. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35148. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35149. };
  35150. Action.prototype.serialize = function (parent) {
  35151. };
  35152. // Called by BABYLON.Action objects in serialize(...). Internal use
  35153. Action.prototype._serialize = function (serializedAction, parent) {
  35154. var serializationObject = {
  35155. type: 1,
  35156. children: [],
  35157. name: serializedAction.name,
  35158. properties: serializedAction.properties || []
  35159. };
  35160. // Serialize child
  35161. if (this._child) {
  35162. this._child.serialize(serializationObject);
  35163. }
  35164. // Check if "this" has a condition
  35165. if (this._condition) {
  35166. var serializedCondition = this._condition.serialize();
  35167. serializedCondition.children.push(serializationObject);
  35168. if (parent) {
  35169. parent.children.push(serializedCondition);
  35170. }
  35171. return serializedCondition;
  35172. }
  35173. if (parent) {
  35174. parent.children.push(serializationObject);
  35175. }
  35176. return serializationObject;
  35177. };
  35178. return Action;
  35179. }());
  35180. Action._SerializeValueAsString = function (value) {
  35181. if (typeof value === "number") {
  35182. return value.toString();
  35183. }
  35184. if (typeof value === "boolean") {
  35185. return value ? "true" : "false";
  35186. }
  35187. if (value instanceof BABYLON.Vector2) {
  35188. return value.x + ", " + value.y;
  35189. }
  35190. if (value instanceof BABYLON.Vector3) {
  35191. return value.x + ", " + value.y + ", " + value.z;
  35192. }
  35193. if (value instanceof BABYLON.Color3) {
  35194. return value.r + ", " + value.g + ", " + value.b;
  35195. }
  35196. if (value instanceof BABYLON.Color4) {
  35197. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35198. }
  35199. return value; // string
  35200. };
  35201. Action._GetTargetProperty = function (target) {
  35202. return {
  35203. name: "target",
  35204. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35205. : target instanceof BABYLON.Light ? "LightProperties"
  35206. : target instanceof BABYLON.Camera ? "CameraProperties"
  35207. : "SceneProperties",
  35208. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35209. };
  35210. };
  35211. BABYLON.Action = Action;
  35212. })(BABYLON || (BABYLON = {}));
  35213. //# sourceMappingURL=babylon.action.js.map
  35214. var BABYLON;
  35215. (function (BABYLON) {
  35216. /**
  35217. * ActionEvent is the event beint sent when an action is triggered.
  35218. */
  35219. var ActionEvent = (function () {
  35220. /**
  35221. * @constructor
  35222. * @param source The mesh or sprite that triggered the action.
  35223. * @param pointerX The X mouse cursor position at the time of the event
  35224. * @param pointerY The Y mouse cursor position at the time of the event
  35225. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35226. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35227. */
  35228. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35229. this.source = source;
  35230. this.pointerX = pointerX;
  35231. this.pointerY = pointerY;
  35232. this.meshUnderPointer = meshUnderPointer;
  35233. this.sourceEvent = sourceEvent;
  35234. this.additionalData = additionalData;
  35235. }
  35236. /**
  35237. * Helper function to auto-create an ActionEvent from a source mesh.
  35238. * @param source The source mesh that triggered the event
  35239. * @param evt {Event} The original (browser) event
  35240. */
  35241. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35242. var scene = source.getScene();
  35243. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35244. };
  35245. /**
  35246. * Helper function to auto-create an ActionEvent from a source mesh.
  35247. * @param source The source sprite that triggered the event
  35248. * @param scene Scene associated with the sprite
  35249. * @param evt {Event} The original (browser) event
  35250. */
  35251. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35252. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35253. };
  35254. /**
  35255. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35256. * @param scene the scene where the event occurred
  35257. * @param evt {Event} The original (browser) event
  35258. */
  35259. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35260. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35261. };
  35262. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35263. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35264. };
  35265. return ActionEvent;
  35266. }());
  35267. BABYLON.ActionEvent = ActionEvent;
  35268. /**
  35269. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35270. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35271. */
  35272. var ActionManager = (function () {
  35273. function ActionManager(scene) {
  35274. // Members
  35275. this.actions = new Array();
  35276. this.hoverCursor = '';
  35277. this._scene = scene;
  35278. scene._actionManagers.push(this);
  35279. }
  35280. Object.defineProperty(ActionManager, "NothingTrigger", {
  35281. get: function () {
  35282. return ActionManager._NothingTrigger;
  35283. },
  35284. enumerable: true,
  35285. configurable: true
  35286. });
  35287. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35288. get: function () {
  35289. return ActionManager._OnPickTrigger;
  35290. },
  35291. enumerable: true,
  35292. configurable: true
  35293. });
  35294. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35295. get: function () {
  35296. return ActionManager._OnLeftPickTrigger;
  35297. },
  35298. enumerable: true,
  35299. configurable: true
  35300. });
  35301. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35302. get: function () {
  35303. return ActionManager._OnRightPickTrigger;
  35304. },
  35305. enumerable: true,
  35306. configurable: true
  35307. });
  35308. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35309. get: function () {
  35310. return ActionManager._OnCenterPickTrigger;
  35311. },
  35312. enumerable: true,
  35313. configurable: true
  35314. });
  35315. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35316. get: function () {
  35317. return ActionManager._OnPickDownTrigger;
  35318. },
  35319. enumerable: true,
  35320. configurable: true
  35321. });
  35322. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35323. get: function () {
  35324. return ActionManager._OnPickUpTrigger;
  35325. },
  35326. enumerable: true,
  35327. configurable: true
  35328. });
  35329. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35330. /// This trigger will only be raised if you also declared a OnPickDown
  35331. get: function () {
  35332. return ActionManager._OnPickOutTrigger;
  35333. },
  35334. enumerable: true,
  35335. configurable: true
  35336. });
  35337. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35338. get: function () {
  35339. return ActionManager._OnLongPressTrigger;
  35340. },
  35341. enumerable: true,
  35342. configurable: true
  35343. });
  35344. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35345. get: function () {
  35346. return ActionManager._OnPointerOverTrigger;
  35347. },
  35348. enumerable: true,
  35349. configurable: true
  35350. });
  35351. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35352. get: function () {
  35353. return ActionManager._OnPointerOutTrigger;
  35354. },
  35355. enumerable: true,
  35356. configurable: true
  35357. });
  35358. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35359. get: function () {
  35360. return ActionManager._OnEveryFrameTrigger;
  35361. },
  35362. enumerable: true,
  35363. configurable: true
  35364. });
  35365. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35366. get: function () {
  35367. return ActionManager._OnIntersectionEnterTrigger;
  35368. },
  35369. enumerable: true,
  35370. configurable: true
  35371. });
  35372. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35373. get: function () {
  35374. return ActionManager._OnIntersectionExitTrigger;
  35375. },
  35376. enumerable: true,
  35377. configurable: true
  35378. });
  35379. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35380. get: function () {
  35381. return ActionManager._OnKeyDownTrigger;
  35382. },
  35383. enumerable: true,
  35384. configurable: true
  35385. });
  35386. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35387. get: function () {
  35388. return ActionManager._OnKeyUpTrigger;
  35389. },
  35390. enumerable: true,
  35391. configurable: true
  35392. });
  35393. // Methods
  35394. ActionManager.prototype.dispose = function () {
  35395. var index = this._scene._actionManagers.indexOf(this);
  35396. if (index > -1) {
  35397. this._scene._actionManagers.splice(index, 1);
  35398. }
  35399. };
  35400. ActionManager.prototype.getScene = function () {
  35401. return this._scene;
  35402. };
  35403. /**
  35404. * Does this action manager handles actions of any of the given triggers
  35405. * @param {number[]} triggers - the triggers to be tested
  35406. * @return {boolean} whether one (or more) of the triggers is handeled
  35407. */
  35408. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35409. for (var index = 0; index < this.actions.length; index++) {
  35410. var action = this.actions[index];
  35411. if (triggers.indexOf(action.trigger) > -1) {
  35412. return true;
  35413. }
  35414. }
  35415. return false;
  35416. };
  35417. /**
  35418. * Does this action manager handles actions of a given trigger
  35419. * @param {number} trigger - the trigger to be tested
  35420. * @return {boolean} whether the trigger is handeled
  35421. */
  35422. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35423. for (var index = 0; index < this.actions.length; index++) {
  35424. var action = this.actions[index];
  35425. if (action.trigger === trigger) {
  35426. return true;
  35427. }
  35428. }
  35429. return false;
  35430. };
  35431. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35432. /**
  35433. * Does this action manager has pointer triggers
  35434. * @return {boolean} whether or not it has pointer triggers
  35435. */
  35436. get: function () {
  35437. for (var index = 0; index < this.actions.length; index++) {
  35438. var action = this.actions[index];
  35439. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35440. return true;
  35441. }
  35442. }
  35443. return false;
  35444. },
  35445. enumerable: true,
  35446. configurable: true
  35447. });
  35448. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35449. /**
  35450. * Does this action manager has pick triggers
  35451. * @return {boolean} whether or not it has pick triggers
  35452. */
  35453. get: function () {
  35454. for (var index = 0; index < this.actions.length; index++) {
  35455. var action = this.actions[index];
  35456. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35457. return true;
  35458. }
  35459. }
  35460. return false;
  35461. },
  35462. enumerable: true,
  35463. configurable: true
  35464. });
  35465. /**
  35466. * Registers an action to this action manager
  35467. * @param {BABYLON.Action} action - the action to be registered
  35468. * @return {BABYLON.Action} the action amended (prepared) after registration
  35469. */
  35470. ActionManager.prototype.registerAction = function (action) {
  35471. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35472. if (this.getScene().actionManager !== this) {
  35473. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35474. return null;
  35475. }
  35476. }
  35477. this.actions.push(action);
  35478. action._actionManager = this;
  35479. action._prepare();
  35480. return action;
  35481. };
  35482. /**
  35483. * Process a specific trigger
  35484. * @param {number} trigger - the trigger to process
  35485. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35486. */
  35487. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35488. for (var index = 0; index < this.actions.length; index++) {
  35489. var action = this.actions[index];
  35490. if (action.trigger === trigger) {
  35491. if (trigger === ActionManager.OnKeyUpTrigger
  35492. || trigger === ActionManager.OnKeyDownTrigger) {
  35493. var parameter = action.getTriggerParameter();
  35494. if (parameter) {
  35495. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35496. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35497. if (actualkey !== parameter.toLowerCase()) {
  35498. continue;
  35499. }
  35500. }
  35501. }
  35502. action._executeCurrent(evt);
  35503. }
  35504. }
  35505. };
  35506. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35507. var properties = propertyPath.split(".");
  35508. for (var index = 0; index < properties.length - 1; index++) {
  35509. target = target[properties[index]];
  35510. }
  35511. return target;
  35512. };
  35513. ActionManager.prototype._getProperty = function (propertyPath) {
  35514. var properties = propertyPath.split(".");
  35515. return properties[properties.length - 1];
  35516. };
  35517. ActionManager.prototype.serialize = function (name) {
  35518. var root = {
  35519. children: [],
  35520. name: name,
  35521. type: 3,
  35522. properties: [] // Empty for root but required
  35523. };
  35524. for (var i = 0; i < this.actions.length; i++) {
  35525. var triggerObject = {
  35526. type: 0,
  35527. children: [],
  35528. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35529. properties: []
  35530. };
  35531. var triggerOptions = this.actions[i].triggerOptions;
  35532. if (triggerOptions && typeof triggerOptions !== "number") {
  35533. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35534. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35535. }
  35536. else {
  35537. var parameter = {};
  35538. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35539. if (triggerOptions.parameter.mesh) {
  35540. parameter._meshId = triggerOptions.parameter.mesh.id;
  35541. }
  35542. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35543. }
  35544. }
  35545. // Serialize child action, recursively
  35546. this.actions[i].serialize(triggerObject);
  35547. // Add serialized trigger
  35548. root.children.push(triggerObject);
  35549. }
  35550. return root;
  35551. };
  35552. ActionManager.Parse = function (parsedActions, object, scene) {
  35553. var actionManager = new BABYLON.ActionManager(scene);
  35554. if (object === null)
  35555. scene.actionManager = actionManager;
  35556. else
  35557. object.actionManager = actionManager;
  35558. // instanciate a new object
  35559. var instanciate = function (name, params) {
  35560. var newInstance = Object.create(BABYLON[name].prototype);
  35561. newInstance.constructor.apply(newInstance, params);
  35562. return newInstance;
  35563. };
  35564. var parseParameter = function (name, value, target, propertyPath) {
  35565. if (propertyPath === null) {
  35566. // String, boolean or float
  35567. var floatValue = parseFloat(value);
  35568. if (value === "true" || value === "false")
  35569. return value === "true";
  35570. else
  35571. return isNaN(floatValue) ? value : floatValue;
  35572. }
  35573. var effectiveTarget = propertyPath.split(".");
  35574. var values = value.split(",");
  35575. // Get effective Target
  35576. for (var i = 0; i < effectiveTarget.length; i++) {
  35577. target = target[effectiveTarget[i]];
  35578. }
  35579. // Return appropriate value with its type
  35580. if (typeof (target) === "boolean")
  35581. return values[0] === "true";
  35582. if (typeof (target) === "string")
  35583. return values[0];
  35584. // Parameters with multiple values such as Vector3 etc.
  35585. var split = new Array();
  35586. for (var i = 0; i < values.length; i++)
  35587. split.push(parseFloat(values[i]));
  35588. if (target instanceof BABYLON.Vector3)
  35589. return BABYLON.Vector3.FromArray(split);
  35590. if (target instanceof BABYLON.Vector4)
  35591. return BABYLON.Vector4.FromArray(split);
  35592. if (target instanceof BABYLON.Color3)
  35593. return BABYLON.Color3.FromArray(split);
  35594. if (target instanceof BABYLON.Color4)
  35595. return BABYLON.Color4.FromArray(split);
  35596. return parseFloat(values[0]);
  35597. };
  35598. // traverse graph per trigger
  35599. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35600. if (combineArray === void 0) { combineArray = null; }
  35601. if (parsedAction.detached)
  35602. return;
  35603. var parameters = new Array();
  35604. var target = null;
  35605. var propertyPath = null;
  35606. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35607. // Parameters
  35608. if (parsedAction.type === 2)
  35609. parameters.push(actionManager);
  35610. else
  35611. parameters.push(trigger);
  35612. if (combine) {
  35613. var actions = new Array();
  35614. for (var j = 0; j < parsedAction.combine.length; j++) {
  35615. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35616. }
  35617. parameters.push(actions);
  35618. }
  35619. else {
  35620. for (var i = 0; i < parsedAction.properties.length; i++) {
  35621. var value = parsedAction.properties[i].value;
  35622. var name = parsedAction.properties[i].name;
  35623. var targetType = parsedAction.properties[i].targetType;
  35624. if (name === "target")
  35625. if (targetType !== null && targetType === "SceneProperties")
  35626. value = target = scene;
  35627. else
  35628. value = target = scene.getNodeByName(value);
  35629. else if (name === "parent")
  35630. value = scene.getNodeByName(value);
  35631. else if (name === "sound")
  35632. value = scene.getSoundByName(value);
  35633. else if (name !== "propertyPath") {
  35634. if (parsedAction.type === 2 && name === "operator")
  35635. value = BABYLON.ValueCondition[value];
  35636. else
  35637. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35638. }
  35639. else {
  35640. propertyPath = value;
  35641. }
  35642. parameters.push(value);
  35643. }
  35644. }
  35645. if (combineArray === null) {
  35646. parameters.push(condition);
  35647. }
  35648. else {
  35649. parameters.push(null);
  35650. }
  35651. // If interpolate value action
  35652. if (parsedAction.name === "InterpolateValueAction") {
  35653. var param = parameters[parameters.length - 2];
  35654. parameters[parameters.length - 1] = param;
  35655. parameters[parameters.length - 2] = condition;
  35656. }
  35657. // Action or condition(s) and not CombineAction
  35658. var newAction = instanciate(parsedAction.name, parameters);
  35659. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35660. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35661. if (action)
  35662. action.then(nothing);
  35663. else
  35664. actionManager.registerAction(nothing);
  35665. action = nothing;
  35666. }
  35667. if (combineArray === null) {
  35668. if (newAction instanceof BABYLON.Condition) {
  35669. condition = newAction;
  35670. newAction = action;
  35671. }
  35672. else {
  35673. condition = null;
  35674. if (action)
  35675. action.then(newAction);
  35676. else
  35677. actionManager.registerAction(newAction);
  35678. }
  35679. }
  35680. else {
  35681. combineArray.push(newAction);
  35682. }
  35683. for (var i = 0; i < parsedAction.children.length; i++)
  35684. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35685. };
  35686. // triggers
  35687. for (var i = 0; i < parsedActions.children.length; i++) {
  35688. var triggerParams;
  35689. var trigger = parsedActions.children[i];
  35690. if (trigger.properties.length > 0) {
  35691. var param = trigger.properties[0].value;
  35692. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35693. if (value._meshId) {
  35694. value.mesh = scene.getMeshByID(value._meshId);
  35695. }
  35696. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35697. }
  35698. else
  35699. triggerParams = BABYLON.ActionManager[trigger.name];
  35700. for (var j = 0; j < trigger.children.length; j++) {
  35701. if (!trigger.detached)
  35702. traverse(trigger.children[j], triggerParams, null, null);
  35703. }
  35704. }
  35705. };
  35706. ActionManager.GetTriggerName = function (trigger) {
  35707. switch (trigger) {
  35708. case 0: return "NothingTrigger";
  35709. case 1: return "OnPickTrigger";
  35710. case 2: return "OnLeftPickTrigger";
  35711. case 3: return "OnRightPickTrigger";
  35712. case 4: return "OnCenterPickTrigger";
  35713. case 5: return "OnPickDownTrigger";
  35714. case 6: return "OnPickUpTrigger";
  35715. case 7: return "OnLongPressTrigger";
  35716. case 8: return "OnPointerOverTrigger";
  35717. case 9: return "OnPointerOutTrigger";
  35718. case 10: return "OnEveryFrameTrigger";
  35719. case 11: return "OnIntersectionEnterTrigger";
  35720. case 12: return "OnIntersectionExitTrigger";
  35721. case 13: return "OnKeyDownTrigger";
  35722. case 14: return "OnKeyUpTrigger";
  35723. case 15: return "OnPickOutTrigger";
  35724. default: return "";
  35725. }
  35726. };
  35727. return ActionManager;
  35728. }());
  35729. // Statics
  35730. ActionManager._NothingTrigger = 0;
  35731. ActionManager._OnPickTrigger = 1;
  35732. ActionManager._OnLeftPickTrigger = 2;
  35733. ActionManager._OnRightPickTrigger = 3;
  35734. ActionManager._OnCenterPickTrigger = 4;
  35735. ActionManager._OnPickDownTrigger = 5;
  35736. ActionManager._OnPickUpTrigger = 6;
  35737. ActionManager._OnLongPressTrigger = 7;
  35738. ActionManager._OnPointerOverTrigger = 8;
  35739. ActionManager._OnPointerOutTrigger = 9;
  35740. ActionManager._OnEveryFrameTrigger = 10;
  35741. ActionManager._OnIntersectionEnterTrigger = 11;
  35742. ActionManager._OnIntersectionExitTrigger = 12;
  35743. ActionManager._OnKeyDownTrigger = 13;
  35744. ActionManager._OnKeyUpTrigger = 14;
  35745. ActionManager._OnPickOutTrigger = 15;
  35746. ActionManager.DragMovementThreshold = 10; // in pixels
  35747. ActionManager.LongPressDelay = 500; // in milliseconds
  35748. BABYLON.ActionManager = ActionManager;
  35749. })(BABYLON || (BABYLON = {}));
  35750. //# sourceMappingURL=babylon.actionManager.js.map
  35751. var BABYLON;
  35752. (function (BABYLON) {
  35753. var InterpolateValueAction = (function (_super) {
  35754. __extends(InterpolateValueAction, _super);
  35755. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35756. if (duration === void 0) { duration = 1000; }
  35757. var _this = _super.call(this, triggerOptions, condition) || this;
  35758. _this.propertyPath = propertyPath;
  35759. _this.value = value;
  35760. _this.duration = duration;
  35761. _this.stopOtherAnimations = stopOtherAnimations;
  35762. _this.onInterpolationDone = onInterpolationDone;
  35763. _this._target = _this._effectiveTarget = target;
  35764. return _this;
  35765. }
  35766. InterpolateValueAction.prototype._prepare = function () {
  35767. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35768. this._property = this._getProperty(this.propertyPath);
  35769. };
  35770. InterpolateValueAction.prototype.execute = function () {
  35771. var scene = this._actionManager.getScene();
  35772. var keys = [
  35773. {
  35774. frame: 0,
  35775. value: this._effectiveTarget[this._property]
  35776. }, {
  35777. frame: 100,
  35778. value: this.value
  35779. }
  35780. ];
  35781. var dataType;
  35782. if (typeof this.value === "number") {
  35783. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35784. }
  35785. else if (this.value instanceof BABYLON.Color3) {
  35786. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35787. }
  35788. else if (this.value instanceof BABYLON.Vector3) {
  35789. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35790. }
  35791. else if (this.value instanceof BABYLON.Matrix) {
  35792. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35793. }
  35794. else if (this.value instanceof BABYLON.Quaternion) {
  35795. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35796. }
  35797. else {
  35798. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35799. return;
  35800. }
  35801. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35802. animation.setKeys(keys);
  35803. if (this.stopOtherAnimations) {
  35804. scene.stopAnimation(this._effectiveTarget);
  35805. }
  35806. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35807. };
  35808. InterpolateValueAction.prototype.serialize = function (parent) {
  35809. return _super.prototype._serialize.call(this, {
  35810. name: "InterpolateValueAction",
  35811. properties: [
  35812. BABYLON.Action._GetTargetProperty(this._target),
  35813. { name: "propertyPath", value: this.propertyPath },
  35814. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35815. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35816. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35817. ]
  35818. }, parent);
  35819. };
  35820. return InterpolateValueAction;
  35821. }(BABYLON.Action));
  35822. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35823. })(BABYLON || (BABYLON = {}));
  35824. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  35825. var BABYLON;
  35826. (function (BABYLON) {
  35827. var SwitchBooleanAction = (function (_super) {
  35828. __extends(SwitchBooleanAction, _super);
  35829. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35830. var _this = _super.call(this, triggerOptions, condition) || this;
  35831. _this.propertyPath = propertyPath;
  35832. _this._target = _this._effectiveTarget = target;
  35833. return _this;
  35834. }
  35835. SwitchBooleanAction.prototype._prepare = function () {
  35836. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35837. this._property = this._getProperty(this.propertyPath);
  35838. };
  35839. SwitchBooleanAction.prototype.execute = function () {
  35840. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35841. };
  35842. SwitchBooleanAction.prototype.serialize = function (parent) {
  35843. return _super.prototype._serialize.call(this, {
  35844. name: "SwitchBooleanAction",
  35845. properties: [
  35846. BABYLON.Action._GetTargetProperty(this._target),
  35847. { name: "propertyPath", value: this.propertyPath }
  35848. ]
  35849. }, parent);
  35850. };
  35851. return SwitchBooleanAction;
  35852. }(BABYLON.Action));
  35853. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35854. var SetStateAction = (function (_super) {
  35855. __extends(SetStateAction, _super);
  35856. function SetStateAction(triggerOptions, target, value, condition) {
  35857. var _this = _super.call(this, triggerOptions, condition) || this;
  35858. _this.value = value;
  35859. _this._target = target;
  35860. return _this;
  35861. }
  35862. SetStateAction.prototype.execute = function () {
  35863. this._target.state = this.value;
  35864. };
  35865. SetStateAction.prototype.serialize = function (parent) {
  35866. return _super.prototype._serialize.call(this, {
  35867. name: "SetStateAction",
  35868. properties: [
  35869. BABYLON.Action._GetTargetProperty(this._target),
  35870. { name: "value", value: this.value }
  35871. ]
  35872. }, parent);
  35873. };
  35874. return SetStateAction;
  35875. }(BABYLON.Action));
  35876. BABYLON.SetStateAction = SetStateAction;
  35877. var SetValueAction = (function (_super) {
  35878. __extends(SetValueAction, _super);
  35879. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35880. var _this = _super.call(this, triggerOptions, condition) || this;
  35881. _this.propertyPath = propertyPath;
  35882. _this.value = value;
  35883. _this._target = _this._effectiveTarget = target;
  35884. return _this;
  35885. }
  35886. SetValueAction.prototype._prepare = function () {
  35887. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35888. this._property = this._getProperty(this.propertyPath);
  35889. };
  35890. SetValueAction.prototype.execute = function () {
  35891. this._effectiveTarget[this._property] = this.value;
  35892. if (this._target.markAsDirty) {
  35893. this._target.markAsDirty(this._property);
  35894. }
  35895. };
  35896. SetValueAction.prototype.serialize = function (parent) {
  35897. return _super.prototype._serialize.call(this, {
  35898. name: "SetValueAction",
  35899. properties: [
  35900. BABYLON.Action._GetTargetProperty(this._target),
  35901. { name: "propertyPath", value: this.propertyPath },
  35902. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35903. ]
  35904. }, parent);
  35905. };
  35906. return SetValueAction;
  35907. }(BABYLON.Action));
  35908. BABYLON.SetValueAction = SetValueAction;
  35909. var IncrementValueAction = (function (_super) {
  35910. __extends(IncrementValueAction, _super);
  35911. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  35912. var _this = _super.call(this, triggerOptions, condition) || this;
  35913. _this.propertyPath = propertyPath;
  35914. _this.value = value;
  35915. _this._target = _this._effectiveTarget = target;
  35916. return _this;
  35917. }
  35918. IncrementValueAction.prototype._prepare = function () {
  35919. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35920. this._property = this._getProperty(this.propertyPath);
  35921. if (typeof this._effectiveTarget[this._property] !== "number") {
  35922. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  35923. }
  35924. };
  35925. IncrementValueAction.prototype.execute = function () {
  35926. this._effectiveTarget[this._property] += this.value;
  35927. if (this._target.markAsDirty) {
  35928. this._target.markAsDirty(this._property);
  35929. }
  35930. };
  35931. IncrementValueAction.prototype.serialize = function (parent) {
  35932. return _super.prototype._serialize.call(this, {
  35933. name: "IncrementValueAction",
  35934. properties: [
  35935. BABYLON.Action._GetTargetProperty(this._target),
  35936. { name: "propertyPath", value: this.propertyPath },
  35937. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35938. ]
  35939. }, parent);
  35940. };
  35941. return IncrementValueAction;
  35942. }(BABYLON.Action));
  35943. BABYLON.IncrementValueAction = IncrementValueAction;
  35944. var PlayAnimationAction = (function (_super) {
  35945. __extends(PlayAnimationAction, _super);
  35946. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  35947. var _this = _super.call(this, triggerOptions, condition) || this;
  35948. _this.from = from;
  35949. _this.to = to;
  35950. _this.loop = loop;
  35951. _this._target = target;
  35952. return _this;
  35953. }
  35954. PlayAnimationAction.prototype._prepare = function () {
  35955. };
  35956. PlayAnimationAction.prototype.execute = function () {
  35957. var scene = this._actionManager.getScene();
  35958. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  35959. };
  35960. PlayAnimationAction.prototype.serialize = function (parent) {
  35961. return _super.prototype._serialize.call(this, {
  35962. name: "PlayAnimationAction",
  35963. properties: [
  35964. BABYLON.Action._GetTargetProperty(this._target),
  35965. { name: "from", value: String(this.from) },
  35966. { name: "to", value: String(this.to) },
  35967. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  35968. ]
  35969. }, parent);
  35970. };
  35971. return PlayAnimationAction;
  35972. }(BABYLON.Action));
  35973. BABYLON.PlayAnimationAction = PlayAnimationAction;
  35974. var StopAnimationAction = (function (_super) {
  35975. __extends(StopAnimationAction, _super);
  35976. function StopAnimationAction(triggerOptions, target, condition) {
  35977. var _this = _super.call(this, triggerOptions, condition) || this;
  35978. _this._target = target;
  35979. return _this;
  35980. }
  35981. StopAnimationAction.prototype._prepare = function () {
  35982. };
  35983. StopAnimationAction.prototype.execute = function () {
  35984. var scene = this._actionManager.getScene();
  35985. scene.stopAnimation(this._target);
  35986. };
  35987. StopAnimationAction.prototype.serialize = function (parent) {
  35988. return _super.prototype._serialize.call(this, {
  35989. name: "StopAnimationAction",
  35990. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  35991. }, parent);
  35992. };
  35993. return StopAnimationAction;
  35994. }(BABYLON.Action));
  35995. BABYLON.StopAnimationAction = StopAnimationAction;
  35996. var DoNothingAction = (function (_super) {
  35997. __extends(DoNothingAction, _super);
  35998. function DoNothingAction(triggerOptions, condition) {
  35999. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36000. return _super.call(this, triggerOptions, condition) || this;
  36001. }
  36002. DoNothingAction.prototype.execute = function () {
  36003. };
  36004. DoNothingAction.prototype.serialize = function (parent) {
  36005. return _super.prototype._serialize.call(this, {
  36006. name: "DoNothingAction",
  36007. properties: []
  36008. }, parent);
  36009. };
  36010. return DoNothingAction;
  36011. }(BABYLON.Action));
  36012. BABYLON.DoNothingAction = DoNothingAction;
  36013. var CombineAction = (function (_super) {
  36014. __extends(CombineAction, _super);
  36015. function CombineAction(triggerOptions, children, condition) {
  36016. var _this = _super.call(this, triggerOptions, condition) || this;
  36017. _this.children = children;
  36018. return _this;
  36019. }
  36020. CombineAction.prototype._prepare = function () {
  36021. for (var index = 0; index < this.children.length; index++) {
  36022. this.children[index]._actionManager = this._actionManager;
  36023. this.children[index]._prepare();
  36024. }
  36025. };
  36026. CombineAction.prototype.execute = function (evt) {
  36027. for (var index = 0; index < this.children.length; index++) {
  36028. this.children[index].execute(evt);
  36029. }
  36030. };
  36031. CombineAction.prototype.serialize = function (parent) {
  36032. var serializationObject = _super.prototype._serialize.call(this, {
  36033. name: "CombineAction",
  36034. properties: [],
  36035. combine: []
  36036. }, parent);
  36037. for (var i = 0; i < this.children.length; i++) {
  36038. serializationObject.combine.push(this.children[i].serialize(null));
  36039. }
  36040. return serializationObject;
  36041. };
  36042. return CombineAction;
  36043. }(BABYLON.Action));
  36044. BABYLON.CombineAction = CombineAction;
  36045. var ExecuteCodeAction = (function (_super) {
  36046. __extends(ExecuteCodeAction, _super);
  36047. function ExecuteCodeAction(triggerOptions, func, condition) {
  36048. var _this = _super.call(this, triggerOptions, condition) || this;
  36049. _this.func = func;
  36050. return _this;
  36051. }
  36052. ExecuteCodeAction.prototype.execute = function (evt) {
  36053. this.func(evt);
  36054. };
  36055. return ExecuteCodeAction;
  36056. }(BABYLON.Action));
  36057. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36058. var SetParentAction = (function (_super) {
  36059. __extends(SetParentAction, _super);
  36060. function SetParentAction(triggerOptions, target, parent, condition) {
  36061. var _this = _super.call(this, triggerOptions, condition) || this;
  36062. _this._target = target;
  36063. _this._parent = parent;
  36064. return _this;
  36065. }
  36066. SetParentAction.prototype._prepare = function () {
  36067. };
  36068. SetParentAction.prototype.execute = function () {
  36069. if (this._target.parent === this._parent) {
  36070. return;
  36071. }
  36072. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36073. invertParentWorldMatrix.invert();
  36074. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36075. this._target.parent = this._parent;
  36076. };
  36077. SetParentAction.prototype.serialize = function (parent) {
  36078. return _super.prototype._serialize.call(this, {
  36079. name: "SetParentAction",
  36080. properties: [
  36081. BABYLON.Action._GetTargetProperty(this._target),
  36082. BABYLON.Action._GetTargetProperty(this._parent),
  36083. ]
  36084. }, parent);
  36085. };
  36086. return SetParentAction;
  36087. }(BABYLON.Action));
  36088. BABYLON.SetParentAction = SetParentAction;
  36089. var PlaySoundAction = (function (_super) {
  36090. __extends(PlaySoundAction, _super);
  36091. function PlaySoundAction(triggerOptions, sound, condition) {
  36092. var _this = _super.call(this, triggerOptions, condition) || this;
  36093. _this._sound = sound;
  36094. return _this;
  36095. }
  36096. PlaySoundAction.prototype._prepare = function () {
  36097. };
  36098. PlaySoundAction.prototype.execute = function () {
  36099. if (this._sound !== undefined)
  36100. this._sound.play();
  36101. };
  36102. PlaySoundAction.prototype.serialize = function (parent) {
  36103. return _super.prototype._serialize.call(this, {
  36104. name: "PlaySoundAction",
  36105. properties: [{ name: "sound", value: this._sound.name }]
  36106. }, parent);
  36107. };
  36108. return PlaySoundAction;
  36109. }(BABYLON.Action));
  36110. BABYLON.PlaySoundAction = PlaySoundAction;
  36111. var StopSoundAction = (function (_super) {
  36112. __extends(StopSoundAction, _super);
  36113. function StopSoundAction(triggerOptions, sound, condition) {
  36114. var _this = _super.call(this, triggerOptions, condition) || this;
  36115. _this._sound = sound;
  36116. return _this;
  36117. }
  36118. StopSoundAction.prototype._prepare = function () {
  36119. };
  36120. StopSoundAction.prototype.execute = function () {
  36121. if (this._sound !== undefined)
  36122. this._sound.stop();
  36123. };
  36124. StopSoundAction.prototype.serialize = function (parent) {
  36125. return _super.prototype._serialize.call(this, {
  36126. name: "StopSoundAction",
  36127. properties: [{ name: "sound", value: this._sound.name }]
  36128. }, parent);
  36129. };
  36130. return StopSoundAction;
  36131. }(BABYLON.Action));
  36132. BABYLON.StopSoundAction = StopSoundAction;
  36133. })(BABYLON || (BABYLON = {}));
  36134. //# sourceMappingURL=babylon.directActions.js.map
  36135. var BABYLON;
  36136. (function (BABYLON) {
  36137. var Geometry = (function () {
  36138. function Geometry(id, scene, vertexData, updatable, mesh) {
  36139. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36140. this._totalVertices = 0;
  36141. this._isDisposed = false;
  36142. this.id = id;
  36143. this._engine = scene.getEngine();
  36144. this._meshes = [];
  36145. this._scene = scene;
  36146. //Init vertex buffer cache
  36147. this._vertexBuffers = {};
  36148. this._indices = [];
  36149. // vertexData
  36150. if (vertexData) {
  36151. this.setAllVerticesData(vertexData, updatable);
  36152. }
  36153. else {
  36154. this._totalVertices = 0;
  36155. this._indices = [];
  36156. }
  36157. // applyToMesh
  36158. if (mesh) {
  36159. if (mesh instanceof BABYLON.LinesMesh) {
  36160. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  36161. this.updateExtend();
  36162. }
  36163. this.applyToMesh(mesh);
  36164. mesh.computeWorldMatrix(true);
  36165. }
  36166. }
  36167. Object.defineProperty(Geometry.prototype, "boundingBias", {
  36168. /**
  36169. * 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
  36170. * @returns The Bias Vector
  36171. */
  36172. get: function () {
  36173. return this._boundingBias;
  36174. },
  36175. set: function (value) {
  36176. if (this._boundingBias && this._boundingBias.equals(value)) {
  36177. return;
  36178. }
  36179. this._boundingBias = value.clone();
  36180. this.updateBoundingInfo(true, null);
  36181. },
  36182. enumerable: true,
  36183. configurable: true
  36184. });
  36185. Object.defineProperty(Geometry.prototype, "extend", {
  36186. get: function () {
  36187. return this._extend;
  36188. },
  36189. enumerable: true,
  36190. configurable: true
  36191. });
  36192. Geometry.prototype.getScene = function () {
  36193. return this._scene;
  36194. };
  36195. Geometry.prototype.getEngine = function () {
  36196. return this._engine;
  36197. };
  36198. Geometry.prototype.isReady = function () {
  36199. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  36200. };
  36201. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  36202. get: function () {
  36203. for (var index = 0; index < this._meshes.length; index++) {
  36204. if (!this._meshes[index].doNotSerialize) {
  36205. return false;
  36206. }
  36207. }
  36208. return true;
  36209. },
  36210. enumerable: true,
  36211. configurable: true
  36212. });
  36213. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36214. vertexData.applyToGeometry(this, updatable);
  36215. this.notifyUpdate();
  36216. };
  36217. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  36218. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  36219. this.setVerticesBuffer(buffer);
  36220. };
  36221. Geometry.prototype.setVerticesBuffer = function (buffer) {
  36222. var kind = buffer.getKind();
  36223. if (this._vertexBuffers[kind]) {
  36224. this._vertexBuffers[kind].dispose();
  36225. }
  36226. this._vertexBuffers[kind] = buffer;
  36227. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36228. var data = buffer.getData();
  36229. var stride = buffer.getStrideSize();
  36230. this._totalVertices = data.length / stride;
  36231. this.updateExtend(data, stride);
  36232. var meshes = this._meshes;
  36233. var numOfMeshes = meshes.length;
  36234. for (var index = 0; index < numOfMeshes; index++) {
  36235. var mesh = meshes[index];
  36236. mesh._resetPointsArrayCache();
  36237. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36238. mesh._createGlobalSubMesh();
  36239. mesh.computeWorldMatrix(true);
  36240. }
  36241. }
  36242. this.notifyUpdate(kind);
  36243. };
  36244. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  36245. var vertexBuffer = this.getVertexBuffer(kind);
  36246. if (!vertexBuffer) {
  36247. return;
  36248. }
  36249. vertexBuffer.updateDirectly(data, offset);
  36250. this.notifyUpdate(kind);
  36251. };
  36252. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  36253. var vertexBuffer = this.getVertexBuffer(kind);
  36254. if (!vertexBuffer) {
  36255. return;
  36256. }
  36257. vertexBuffer.update(data);
  36258. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36259. var stride = vertexBuffer.getStrideSize();
  36260. this._totalVertices = data.length / stride;
  36261. this.updateBoundingInfo(updateExtends, data);
  36262. }
  36263. this.notifyUpdate(kind);
  36264. };
  36265. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  36266. if (updateExtends) {
  36267. this.updateExtend(data);
  36268. }
  36269. var meshes = this._meshes;
  36270. var numOfMeshes = meshes.length;
  36271. for (var index = 0; index < numOfMeshes; index++) {
  36272. var mesh = meshes[index];
  36273. mesh._resetPointsArrayCache();
  36274. if (updateExtends) {
  36275. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36276. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36277. var subMesh = mesh.subMeshes[subIndex];
  36278. subMesh.refreshBoundingInfo();
  36279. }
  36280. }
  36281. }
  36282. };
  36283. Geometry.prototype.getTotalVertices = function () {
  36284. if (!this.isReady()) {
  36285. return 0;
  36286. }
  36287. return this._totalVertices;
  36288. };
  36289. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  36290. var vertexBuffer = this.getVertexBuffer(kind);
  36291. if (!vertexBuffer) {
  36292. return null;
  36293. }
  36294. var orig = vertexBuffer.getData();
  36295. if (!copyWhenShared || this._meshes.length === 1) {
  36296. return orig;
  36297. }
  36298. else {
  36299. var len = orig.length;
  36300. var copy = [];
  36301. for (var i = 0; i < len; i++) {
  36302. copy.push(orig[i]);
  36303. }
  36304. return copy;
  36305. }
  36306. };
  36307. Geometry.prototype.getVertexBuffer = function (kind) {
  36308. if (!this.isReady()) {
  36309. return null;
  36310. }
  36311. return this._vertexBuffers[kind];
  36312. };
  36313. Geometry.prototype.getVertexBuffers = function () {
  36314. if (!this.isReady()) {
  36315. return null;
  36316. }
  36317. return this._vertexBuffers;
  36318. };
  36319. Geometry.prototype.isVerticesDataPresent = function (kind) {
  36320. if (!this._vertexBuffers) {
  36321. if (this._delayInfo) {
  36322. return this._delayInfo.indexOf(kind) !== -1;
  36323. }
  36324. return false;
  36325. }
  36326. return this._vertexBuffers[kind] !== undefined;
  36327. };
  36328. Geometry.prototype.getVerticesDataKinds = function () {
  36329. var result = [];
  36330. var kind;
  36331. if (!this._vertexBuffers && this._delayInfo) {
  36332. for (kind in this._delayInfo) {
  36333. result.push(kind);
  36334. }
  36335. }
  36336. else {
  36337. for (kind in this._vertexBuffers) {
  36338. result.push(kind);
  36339. }
  36340. }
  36341. return result;
  36342. };
  36343. Geometry.prototype.setIndices = function (indices, totalVertices) {
  36344. if (this._indexBuffer) {
  36345. this._engine._releaseBuffer(this._indexBuffer);
  36346. }
  36347. this._indices = indices;
  36348. if (this._meshes.length !== 0 && this._indices) {
  36349. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36350. }
  36351. if (totalVertices !== undefined) {
  36352. this._totalVertices = totalVertices;
  36353. }
  36354. var meshes = this._meshes;
  36355. var numOfMeshes = meshes.length;
  36356. for (var index = 0; index < numOfMeshes; index++) {
  36357. meshes[index]._createGlobalSubMesh();
  36358. }
  36359. this.notifyUpdate();
  36360. };
  36361. Geometry.prototype.getTotalIndices = function () {
  36362. if (!this.isReady()) {
  36363. return 0;
  36364. }
  36365. return this._indices.length;
  36366. };
  36367. Geometry.prototype.getIndices = function (copyWhenShared) {
  36368. if (!this.isReady()) {
  36369. return null;
  36370. }
  36371. var orig = this._indices;
  36372. if (!copyWhenShared || this._meshes.length === 1) {
  36373. return orig;
  36374. }
  36375. else {
  36376. var len = orig.length;
  36377. var copy = [];
  36378. for (var i = 0; i < len; i++) {
  36379. copy.push(orig[i]);
  36380. }
  36381. return copy;
  36382. }
  36383. };
  36384. Geometry.prototype.getIndexBuffer = function () {
  36385. if (!this.isReady()) {
  36386. return null;
  36387. }
  36388. return this._indexBuffer;
  36389. };
  36390. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  36391. var meshes = this._meshes;
  36392. var index = meshes.indexOf(mesh);
  36393. if (index === -1) {
  36394. return;
  36395. }
  36396. for (var kind in this._vertexBuffers) {
  36397. this._vertexBuffers[kind].dispose();
  36398. }
  36399. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  36400. this._indexBuffer = null;
  36401. }
  36402. meshes.splice(index, 1);
  36403. mesh._geometry = null;
  36404. if (meshes.length === 0 && shouldDispose) {
  36405. this.dispose();
  36406. }
  36407. };
  36408. Geometry.prototype.applyToMesh = function (mesh) {
  36409. if (mesh._geometry === this) {
  36410. return;
  36411. }
  36412. var previousGeometry = mesh._geometry;
  36413. if (previousGeometry) {
  36414. previousGeometry.releaseForMesh(mesh);
  36415. }
  36416. var meshes = this._meshes;
  36417. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  36418. mesh._geometry = this;
  36419. this._scene.pushGeometry(this);
  36420. meshes.push(mesh);
  36421. if (this.isReady()) {
  36422. this._applyToMesh(mesh);
  36423. }
  36424. else {
  36425. mesh._boundingInfo = this._boundingInfo;
  36426. }
  36427. };
  36428. Geometry.prototype.updateExtend = function (data, stride) {
  36429. if (data === void 0) { data = null; }
  36430. if (!data) {
  36431. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  36432. }
  36433. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  36434. };
  36435. Geometry.prototype._applyToMesh = function (mesh) {
  36436. var numOfMeshes = this._meshes.length;
  36437. // vertexBuffers
  36438. for (var kind in this._vertexBuffers) {
  36439. if (numOfMeshes === 1) {
  36440. this._vertexBuffers[kind].create();
  36441. }
  36442. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  36443. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36444. mesh._resetPointsArrayCache();
  36445. if (!this._extend) {
  36446. this.updateExtend(this._vertexBuffers[kind].getData());
  36447. }
  36448. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36449. mesh._createGlobalSubMesh();
  36450. //bounding info was just created again, world matrix should be applied again.
  36451. mesh._updateBoundingInfo();
  36452. }
  36453. }
  36454. // indexBuffer
  36455. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  36456. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36457. }
  36458. if (this._indexBuffer) {
  36459. this._indexBuffer.references = numOfMeshes;
  36460. }
  36461. };
  36462. Geometry.prototype.notifyUpdate = function (kind) {
  36463. if (this.onGeometryUpdated) {
  36464. this.onGeometryUpdated(this, kind);
  36465. }
  36466. };
  36467. Geometry.prototype.load = function (scene, onLoaded) {
  36468. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36469. return;
  36470. }
  36471. if (this.isReady()) {
  36472. if (onLoaded) {
  36473. onLoaded();
  36474. }
  36475. return;
  36476. }
  36477. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36478. this._queueLoad(scene, onLoaded);
  36479. };
  36480. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36481. var _this = this;
  36482. scene._addPendingData(this);
  36483. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  36484. _this._delayLoadingFunction(JSON.parse(data), _this);
  36485. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36486. _this._delayInfo = [];
  36487. scene._removePendingData(_this);
  36488. var meshes = _this._meshes;
  36489. var numOfMeshes = meshes.length;
  36490. for (var index = 0; index < numOfMeshes; index++) {
  36491. _this._applyToMesh(meshes[index]);
  36492. }
  36493. if (onLoaded) {
  36494. onLoaded();
  36495. }
  36496. }, function () { }, scene.database);
  36497. };
  36498. /**
  36499. * Invert the geometry to move from a right handed system to a left handed one.
  36500. */
  36501. Geometry.prototype.toLeftHanded = function () {
  36502. // Flip faces
  36503. var tIndices = this.getIndices(false);
  36504. if (tIndices != null && tIndices.length > 0) {
  36505. for (var i = 0; i < tIndices.length; i += 3) {
  36506. var tTemp = tIndices[i + 0];
  36507. tIndices[i + 0] = tIndices[i + 2];
  36508. tIndices[i + 2] = tTemp;
  36509. }
  36510. this.setIndices(tIndices);
  36511. }
  36512. // Negate position.z
  36513. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36514. if (tPositions != null && tPositions.length > 0) {
  36515. for (var i = 0; i < tPositions.length; i += 3) {
  36516. tPositions[i + 2] = -tPositions[i + 2];
  36517. }
  36518. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36519. }
  36520. // Negate normal.z
  36521. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36522. if (tNormals != null && tNormals.length > 0) {
  36523. for (var i = 0; i < tNormals.length; i += 3) {
  36524. tNormals[i + 2] = -tNormals[i + 2];
  36525. }
  36526. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36527. }
  36528. };
  36529. Geometry.prototype.isDisposed = function () {
  36530. return this._isDisposed;
  36531. };
  36532. Geometry.prototype.dispose = function () {
  36533. var meshes = this._meshes;
  36534. var numOfMeshes = meshes.length;
  36535. var index;
  36536. for (index = 0; index < numOfMeshes; index++) {
  36537. this.releaseForMesh(meshes[index]);
  36538. }
  36539. this._meshes = [];
  36540. for (var kind in this._vertexBuffers) {
  36541. this._vertexBuffers[kind].dispose();
  36542. }
  36543. this._vertexBuffers = {};
  36544. this._totalVertices = 0;
  36545. if (this._indexBuffer) {
  36546. this._engine._releaseBuffer(this._indexBuffer);
  36547. }
  36548. this._indexBuffer = null;
  36549. this._indices = [];
  36550. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36551. this.delayLoadingFile = null;
  36552. this._delayLoadingFunction = null;
  36553. this._delayInfo = [];
  36554. this._boundingInfo = null;
  36555. this._scene.removeGeometry(this);
  36556. this._isDisposed = true;
  36557. };
  36558. Geometry.prototype.copy = function (id) {
  36559. var vertexData = new BABYLON.VertexData();
  36560. vertexData.indices = [];
  36561. var indices = this.getIndices();
  36562. for (var index = 0; index < indices.length; index++) {
  36563. vertexData.indices.push(indices[index]);
  36564. }
  36565. var updatable = false;
  36566. var stopChecking = false;
  36567. var kind;
  36568. for (kind in this._vertexBuffers) {
  36569. // using slice() to make a copy of the array and not just reference it
  36570. var data = this.getVerticesData(kind);
  36571. if (data instanceof Float32Array) {
  36572. vertexData.set(new Float32Array(data), kind);
  36573. }
  36574. else {
  36575. vertexData.set(data.slice(0), kind);
  36576. }
  36577. if (!stopChecking) {
  36578. updatable = this.getVertexBuffer(kind).isUpdatable();
  36579. stopChecking = !updatable;
  36580. }
  36581. }
  36582. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  36583. geometry.delayLoadState = this.delayLoadState;
  36584. geometry.delayLoadingFile = this.delayLoadingFile;
  36585. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36586. for (kind in this._delayInfo) {
  36587. geometry._delayInfo = geometry._delayInfo || [];
  36588. geometry._delayInfo.push(kind);
  36589. }
  36590. // Bounding info
  36591. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36592. return geometry;
  36593. };
  36594. Geometry.prototype.serialize = function () {
  36595. var serializationObject = {};
  36596. serializationObject.id = this.id;
  36597. if (BABYLON.Tags.HasTags(this)) {
  36598. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36599. }
  36600. return serializationObject;
  36601. };
  36602. Geometry.prototype.serializeVerticeData = function () {
  36603. var serializationObject = this.serialize();
  36604. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36605. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36606. }
  36607. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36608. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36609. }
  36610. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36611. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36612. }
  36613. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36614. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  36615. }
  36616. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36617. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  36618. }
  36619. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36620. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  36621. }
  36622. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36623. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  36624. }
  36625. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36626. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  36627. }
  36628. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36629. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36630. }
  36631. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36632. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36633. serializationObject.matricesIndices._isExpanded = true;
  36634. }
  36635. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36636. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  36637. }
  36638. serializationObject.indices = this.getIndices();
  36639. return serializationObject;
  36640. };
  36641. // Statics
  36642. Geometry.ExtractFromMesh = function (mesh, id) {
  36643. var geometry = mesh._geometry;
  36644. if (!geometry) {
  36645. return null;
  36646. }
  36647. return geometry.copy(id);
  36648. };
  36649. /**
  36650. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36651. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36652. * Be aware Math.random() could cause collisions, but:
  36653. * "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"
  36654. */
  36655. Geometry.RandomId = function () {
  36656. return BABYLON.Tools.RandomId();
  36657. };
  36658. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  36659. var scene = mesh.getScene();
  36660. // Geometry
  36661. var geometryId = parsedGeometry.geometryId;
  36662. if (geometryId) {
  36663. var geometry = scene.getGeometryByID(geometryId);
  36664. if (geometry) {
  36665. geometry.applyToMesh(mesh);
  36666. }
  36667. }
  36668. else if (parsedGeometry instanceof ArrayBuffer) {
  36669. var binaryInfo = mesh._binaryInfo;
  36670. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36671. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36672. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36673. }
  36674. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36675. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36676. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36677. }
  36678. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36679. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36680. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36681. }
  36682. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36683. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36684. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36685. }
  36686. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36687. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36688. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36689. }
  36690. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36691. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36692. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36693. }
  36694. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36695. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36696. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36697. }
  36698. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36699. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36700. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36701. }
  36702. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36703. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36704. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36705. }
  36706. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36707. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36708. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36709. }
  36710. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36711. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36712. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36713. }
  36714. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36715. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36716. mesh.setIndices(indicesData);
  36717. }
  36718. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36719. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36720. mesh.subMeshes = [];
  36721. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36722. var materialIndex = subMeshesData[(i * 5) + 0];
  36723. var verticesStart = subMeshesData[(i * 5) + 1];
  36724. var verticesCount = subMeshesData[(i * 5) + 2];
  36725. var indexStart = subMeshesData[(i * 5) + 3];
  36726. var indexCount = subMeshesData[(i * 5) + 4];
  36727. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36728. }
  36729. }
  36730. }
  36731. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36732. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  36733. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  36734. if (parsedGeometry.uvs) {
  36735. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  36736. }
  36737. if (parsedGeometry.uvs2) {
  36738. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  36739. }
  36740. if (parsedGeometry.uvs3) {
  36741. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  36742. }
  36743. if (parsedGeometry.uvs4) {
  36744. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  36745. }
  36746. if (parsedGeometry.uvs5) {
  36747. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  36748. }
  36749. if (parsedGeometry.uvs6) {
  36750. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  36751. }
  36752. if (parsedGeometry.colors) {
  36753. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  36754. }
  36755. if (parsedGeometry.matricesIndices) {
  36756. if (!parsedGeometry.matricesIndices._isExpanded) {
  36757. var floatIndices = [];
  36758. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36759. var matricesIndex = parsedGeometry.matricesIndices[i];
  36760. floatIndices.push(matricesIndex & 0x000000FF);
  36761. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36762. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36763. floatIndices.push(matricesIndex >> 24);
  36764. }
  36765. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  36766. }
  36767. else {
  36768. delete parsedGeometry.matricesIndices._isExpanded;
  36769. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  36770. }
  36771. }
  36772. if (parsedGeometry.matricesIndicesExtra) {
  36773. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36774. var floatIndices = [];
  36775. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36776. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36777. floatIndices.push(matricesIndex & 0x000000FF);
  36778. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36779. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36780. floatIndices.push(matricesIndex >> 24);
  36781. }
  36782. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  36783. }
  36784. else {
  36785. delete parsedGeometry.matricesIndices._isExpanded;
  36786. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  36787. }
  36788. }
  36789. if (parsedGeometry.matricesWeights) {
  36790. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  36791. }
  36792. if (parsedGeometry.matricesWeightsExtra) {
  36793. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  36794. }
  36795. mesh.setIndices(parsedGeometry.indices);
  36796. }
  36797. // SubMeshes
  36798. if (parsedGeometry.subMeshes) {
  36799. mesh.subMeshes = [];
  36800. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36801. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36802. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36803. }
  36804. }
  36805. // Flat shading
  36806. if (mesh._shouldGenerateFlatShading) {
  36807. mesh.convertToFlatShadedMesh();
  36808. delete mesh._shouldGenerateFlatShading;
  36809. }
  36810. // Update
  36811. mesh.computeWorldMatrix(true);
  36812. // Octree
  36813. if (scene['_selectionOctree']) {
  36814. scene['_selectionOctree'].addMesh(mesh);
  36815. }
  36816. };
  36817. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36818. if (scene.getGeometryByID(parsedVertexData.id)) {
  36819. return null; // null since geometry could be something else than a box...
  36820. }
  36821. var geometry = new Geometry(parsedVertexData.id, scene);
  36822. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36823. if (parsedVertexData.delayLoadingFile) {
  36824. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36825. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36826. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36827. geometry._delayInfo = [];
  36828. if (parsedVertexData.hasUVs) {
  36829. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36830. }
  36831. if (parsedVertexData.hasUVs2) {
  36832. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36833. }
  36834. if (parsedVertexData.hasUVs3) {
  36835. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36836. }
  36837. if (parsedVertexData.hasUVs4) {
  36838. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36839. }
  36840. if (parsedVertexData.hasUVs5) {
  36841. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36842. }
  36843. if (parsedVertexData.hasUVs6) {
  36844. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36845. }
  36846. if (parsedVertexData.hasColors) {
  36847. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36848. }
  36849. if (parsedVertexData.hasMatricesIndices) {
  36850. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36851. }
  36852. if (parsedVertexData.hasMatricesWeights) {
  36853. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36854. }
  36855. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36856. }
  36857. else {
  36858. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36859. }
  36860. scene.pushGeometry(geometry, true);
  36861. return geometry;
  36862. };
  36863. return Geometry;
  36864. }());
  36865. BABYLON.Geometry = Geometry;
  36866. /////// Primitives //////////////////////////////////////////////
  36867. (function (Geometry) {
  36868. var Primitives;
  36869. (function (Primitives) {
  36870. /// Abstract class
  36871. var _Primitive = (function (_super) {
  36872. __extends(_Primitive, _super);
  36873. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  36874. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  36875. _this._canBeRegenerated = _canBeRegenerated;
  36876. _this._beingRegenerated = true;
  36877. _this.regenerate();
  36878. _this._beingRegenerated = false;
  36879. return _this;
  36880. }
  36881. _Primitive.prototype.canBeRegenerated = function () {
  36882. return this._canBeRegenerated;
  36883. };
  36884. _Primitive.prototype.regenerate = function () {
  36885. if (!this._canBeRegenerated) {
  36886. return;
  36887. }
  36888. this._beingRegenerated = true;
  36889. this.setAllVerticesData(this._regenerateVertexData(), false);
  36890. this._beingRegenerated = false;
  36891. };
  36892. _Primitive.prototype.asNewGeometry = function (id) {
  36893. return _super.prototype.copy.call(this, id);
  36894. };
  36895. // overrides
  36896. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  36897. if (!this._beingRegenerated) {
  36898. return;
  36899. }
  36900. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36901. };
  36902. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  36903. if (!this._beingRegenerated) {
  36904. return;
  36905. }
  36906. _super.prototype.setVerticesData.call(this, kind, data, false);
  36907. };
  36908. // to override
  36909. // protected
  36910. _Primitive.prototype._regenerateVertexData = function () {
  36911. throw new Error("Abstract method");
  36912. };
  36913. _Primitive.prototype.copy = function (id) {
  36914. throw new Error("Must be overriden in sub-classes.");
  36915. };
  36916. _Primitive.prototype.serialize = function () {
  36917. var serializationObject = _super.prototype.serialize.call(this);
  36918. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36919. return serializationObject;
  36920. };
  36921. return _Primitive;
  36922. }(Geometry));
  36923. Primitives._Primitive = _Primitive;
  36924. var Ribbon = (function (_super) {
  36925. __extends(Ribbon, _super);
  36926. // Members
  36927. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  36928. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36929. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36930. _this.pathArray = pathArray;
  36931. _this.closeArray = closeArray;
  36932. _this.closePath = closePath;
  36933. _this.offset = offset;
  36934. _this.side = side;
  36935. return _this;
  36936. }
  36937. Ribbon.prototype._regenerateVertexData = function () {
  36938. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36939. };
  36940. Ribbon.prototype.copy = function (id) {
  36941. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  36942. };
  36943. return Ribbon;
  36944. }(_Primitive));
  36945. Primitives.Ribbon = Ribbon;
  36946. var Box = (function (_super) {
  36947. __extends(Box, _super);
  36948. // Members
  36949. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  36950. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36951. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36952. _this.size = size;
  36953. _this.side = side;
  36954. return _this;
  36955. }
  36956. Box.prototype._regenerateVertexData = function () {
  36957. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36958. };
  36959. Box.prototype.copy = function (id) {
  36960. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36961. };
  36962. Box.prototype.serialize = function () {
  36963. var serializationObject = _super.prototype.serialize.call(this);
  36964. serializationObject.size = this.size;
  36965. return serializationObject;
  36966. };
  36967. Box.Parse = function (parsedBox, scene) {
  36968. if (scene.getGeometryByID(parsedBox.id)) {
  36969. return null; // null since geometry could be something else than a box...
  36970. }
  36971. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36972. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36973. scene.pushGeometry(box, true);
  36974. return box;
  36975. };
  36976. return Box;
  36977. }(_Primitive));
  36978. Primitives.Box = Box;
  36979. var Sphere = (function (_super) {
  36980. __extends(Sphere, _super);
  36981. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  36982. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36983. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36984. _this.segments = segments;
  36985. _this.diameter = diameter;
  36986. _this.side = side;
  36987. return _this;
  36988. }
  36989. Sphere.prototype._regenerateVertexData = function () {
  36990. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36991. };
  36992. Sphere.prototype.copy = function (id) {
  36993. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36994. };
  36995. Sphere.prototype.serialize = function () {
  36996. var serializationObject = _super.prototype.serialize.call(this);
  36997. serializationObject.segments = this.segments;
  36998. serializationObject.diameter = this.diameter;
  36999. return serializationObject;
  37000. };
  37001. Sphere.Parse = function (parsedSphere, scene) {
  37002. if (scene.getGeometryByID(parsedSphere.id)) {
  37003. return null; // null since geometry could be something else than a sphere...
  37004. }
  37005. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  37006. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  37007. scene.pushGeometry(sphere, true);
  37008. return sphere;
  37009. };
  37010. return Sphere;
  37011. }(_Primitive));
  37012. Primitives.Sphere = Sphere;
  37013. var Disc = (function (_super) {
  37014. __extends(Disc, _super);
  37015. // Members
  37016. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  37017. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37018. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37019. _this.radius = radius;
  37020. _this.tessellation = tessellation;
  37021. _this.side = side;
  37022. return _this;
  37023. }
  37024. Disc.prototype._regenerateVertexData = function () {
  37025. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  37026. };
  37027. Disc.prototype.copy = function (id) {
  37028. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  37029. };
  37030. return Disc;
  37031. }(_Primitive));
  37032. Primitives.Disc = Disc;
  37033. var Cylinder = (function (_super) {
  37034. __extends(Cylinder, _super);
  37035. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  37036. if (subdivisions === void 0) { subdivisions = 1; }
  37037. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37038. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37039. _this.height = height;
  37040. _this.diameterTop = diameterTop;
  37041. _this.diameterBottom = diameterBottom;
  37042. _this.tessellation = tessellation;
  37043. _this.subdivisions = subdivisions;
  37044. _this.side = side;
  37045. return _this;
  37046. }
  37047. Cylinder.prototype._regenerateVertexData = function () {
  37048. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  37049. };
  37050. Cylinder.prototype.copy = function (id) {
  37051. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  37052. };
  37053. Cylinder.prototype.serialize = function () {
  37054. var serializationObject = _super.prototype.serialize.call(this);
  37055. serializationObject.height = this.height;
  37056. serializationObject.diameterTop = this.diameterTop;
  37057. serializationObject.diameterBottom = this.diameterBottom;
  37058. serializationObject.tessellation = this.tessellation;
  37059. return serializationObject;
  37060. };
  37061. Cylinder.Parse = function (parsedCylinder, scene) {
  37062. if (scene.getGeometryByID(parsedCylinder.id)) {
  37063. return null; // null since geometry could be something else than a cylinder...
  37064. }
  37065. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  37066. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  37067. scene.pushGeometry(cylinder, true);
  37068. return cylinder;
  37069. };
  37070. return Cylinder;
  37071. }(_Primitive));
  37072. Primitives.Cylinder = Cylinder;
  37073. var Torus = (function (_super) {
  37074. __extends(Torus, _super);
  37075. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  37076. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37077. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37078. _this.diameter = diameter;
  37079. _this.thickness = thickness;
  37080. _this.tessellation = tessellation;
  37081. _this.side = side;
  37082. return _this;
  37083. }
  37084. Torus.prototype._regenerateVertexData = function () {
  37085. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  37086. };
  37087. Torus.prototype.copy = function (id) {
  37088. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  37089. };
  37090. Torus.prototype.serialize = function () {
  37091. var serializationObject = _super.prototype.serialize.call(this);
  37092. serializationObject.diameter = this.diameter;
  37093. serializationObject.thickness = this.thickness;
  37094. serializationObject.tessellation = this.tessellation;
  37095. return serializationObject;
  37096. };
  37097. Torus.Parse = function (parsedTorus, scene) {
  37098. if (scene.getGeometryByID(parsedTorus.id)) {
  37099. return null; // null since geometry could be something else than a torus...
  37100. }
  37101. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  37102. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  37103. scene.pushGeometry(torus, true);
  37104. return torus;
  37105. };
  37106. return Torus;
  37107. }(_Primitive));
  37108. Primitives.Torus = Torus;
  37109. var Ground = (function (_super) {
  37110. __extends(Ground, _super);
  37111. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  37112. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37113. _this.width = width;
  37114. _this.height = height;
  37115. _this.subdivisions = subdivisions;
  37116. return _this;
  37117. }
  37118. Ground.prototype._regenerateVertexData = function () {
  37119. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  37120. };
  37121. Ground.prototype.copy = function (id) {
  37122. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  37123. };
  37124. Ground.prototype.serialize = function () {
  37125. var serializationObject = _super.prototype.serialize.call(this);
  37126. serializationObject.width = this.width;
  37127. serializationObject.height = this.height;
  37128. serializationObject.subdivisions = this.subdivisions;
  37129. return serializationObject;
  37130. };
  37131. Ground.Parse = function (parsedGround, scene) {
  37132. if (scene.getGeometryByID(parsedGround.id)) {
  37133. return null; // null since geometry could be something else than a ground...
  37134. }
  37135. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  37136. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  37137. scene.pushGeometry(ground, true);
  37138. return ground;
  37139. };
  37140. return Ground;
  37141. }(_Primitive));
  37142. Primitives.Ground = Ground;
  37143. var TiledGround = (function (_super) {
  37144. __extends(TiledGround, _super);
  37145. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  37146. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37147. _this.xmin = xmin;
  37148. _this.zmin = zmin;
  37149. _this.xmax = xmax;
  37150. _this.zmax = zmax;
  37151. _this.subdivisions = subdivisions;
  37152. _this.precision = precision;
  37153. return _this;
  37154. }
  37155. TiledGround.prototype._regenerateVertexData = function () {
  37156. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37157. };
  37158. TiledGround.prototype.copy = function (id) {
  37159. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37160. };
  37161. return TiledGround;
  37162. }(_Primitive));
  37163. Primitives.TiledGround = TiledGround;
  37164. var Plane = (function (_super) {
  37165. __extends(Plane, _super);
  37166. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  37167. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37168. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37169. _this.size = size;
  37170. _this.side = side;
  37171. return _this;
  37172. }
  37173. Plane.prototype._regenerateVertexData = function () {
  37174. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37175. };
  37176. Plane.prototype.copy = function (id) {
  37177. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37178. };
  37179. Plane.prototype.serialize = function () {
  37180. var serializationObject = _super.prototype.serialize.call(this);
  37181. serializationObject.size = this.size;
  37182. return serializationObject;
  37183. };
  37184. Plane.Parse = function (parsedPlane, scene) {
  37185. if (scene.getGeometryByID(parsedPlane.id)) {
  37186. return null; // null since geometry could be something else than a ground...
  37187. }
  37188. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37189. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37190. scene.pushGeometry(plane, true);
  37191. return plane;
  37192. };
  37193. return Plane;
  37194. }(_Primitive));
  37195. Primitives.Plane = Plane;
  37196. var TorusKnot = (function (_super) {
  37197. __extends(TorusKnot, _super);
  37198. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  37199. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37200. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37201. _this.radius = radius;
  37202. _this.tube = tube;
  37203. _this.radialSegments = radialSegments;
  37204. _this.tubularSegments = tubularSegments;
  37205. _this.p = p;
  37206. _this.q = q;
  37207. _this.side = side;
  37208. return _this;
  37209. }
  37210. TorusKnot.prototype._regenerateVertexData = function () {
  37211. 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 });
  37212. };
  37213. TorusKnot.prototype.copy = function (id) {
  37214. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37215. };
  37216. TorusKnot.prototype.serialize = function () {
  37217. var serializationObject = _super.prototype.serialize.call(this);
  37218. serializationObject.radius = this.radius;
  37219. serializationObject.tube = this.tube;
  37220. serializationObject.radialSegments = this.radialSegments;
  37221. serializationObject.tubularSegments = this.tubularSegments;
  37222. serializationObject.p = this.p;
  37223. serializationObject.q = this.q;
  37224. return serializationObject;
  37225. };
  37226. ;
  37227. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  37228. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37229. return null; // null since geometry could be something else than a ground...
  37230. }
  37231. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37232. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37233. scene.pushGeometry(torusKnot, true);
  37234. return torusKnot;
  37235. };
  37236. return TorusKnot;
  37237. }(_Primitive));
  37238. Primitives.TorusKnot = TorusKnot;
  37239. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  37240. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  37241. })(BABYLON || (BABYLON = {}));
  37242. //# sourceMappingURL=babylon.geometry.js.map
  37243. var BABYLON;
  37244. (function (BABYLON) {
  37245. var GroundMesh = (function (_super) {
  37246. __extends(GroundMesh, _super);
  37247. function GroundMesh(name, scene) {
  37248. var _this = _super.call(this, name, scene) || this;
  37249. _this.generateOctree = false;
  37250. _this._worldInverse = new BABYLON.Matrix();
  37251. return _this;
  37252. }
  37253. GroundMesh.prototype.getClassName = function () {
  37254. return "GroundMesh";
  37255. };
  37256. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37257. get: function () {
  37258. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37259. },
  37260. enumerable: true,
  37261. configurable: true
  37262. });
  37263. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37264. get: function () {
  37265. return this._subdivisionsX;
  37266. },
  37267. enumerable: true,
  37268. configurable: true
  37269. });
  37270. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37271. get: function () {
  37272. return this._subdivisionsY;
  37273. },
  37274. enumerable: true,
  37275. configurable: true
  37276. });
  37277. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37278. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37279. this._subdivisionsX = chunksCount;
  37280. this._subdivisionsY = chunksCount;
  37281. this.subdivide(chunksCount);
  37282. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37283. };
  37284. /**
  37285. * Returns a height (y) value in the Worl system :
  37286. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37287. * Returns the ground y position if (x, z) are outside the ground surface.
  37288. * Not pertinent if the ground is rotated.
  37289. */
  37290. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37291. // express x and y in the ground local system
  37292. x -= this.position.x;
  37293. z -= this.position.z;
  37294. x /= this.scaling.x;
  37295. z /= this.scaling.z;
  37296. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37297. return this.position.y;
  37298. }
  37299. if (!this._heightQuads || this._heightQuads.length == 0) {
  37300. this._initHeightQuads();
  37301. this._computeHeightQuads();
  37302. }
  37303. var facet = this._getFacetAt(x, z);
  37304. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37305. // return y in the World system
  37306. return y * this.scaling.y + this.position.y;
  37307. };
  37308. /**
  37309. * Returns a normalized vector (Vector3) orthogonal to the ground
  37310. * at the ground coordinates (x, z) expressed in the World system.
  37311. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  37312. * Not pertinent if the ground is rotated.
  37313. */
  37314. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37315. var normal = new BABYLON.Vector3(0, 1, 0);
  37316. this.getNormalAtCoordinatesToRef(x, z, normal);
  37317. return normal;
  37318. };
  37319. /**
  37320. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37321. * at the ground coordinates (x, z) expressed in the World system.
  37322. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37323. * Not pertinent if the ground is rotated.
  37324. */
  37325. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37326. // express x and y in the ground local system
  37327. x -= this.position.x;
  37328. z -= this.position.z;
  37329. x /= this.scaling.x;
  37330. z /= this.scaling.z;
  37331. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37332. return;
  37333. }
  37334. if (!this._heightQuads || this._heightQuads.length == 0) {
  37335. this._initHeightQuads();
  37336. this._computeHeightQuads();
  37337. }
  37338. var facet = this._getFacetAt(x, z);
  37339. ref.x = facet.x;
  37340. ref.y = facet.y;
  37341. ref.z = facet.z;
  37342. };
  37343. /**
  37344. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37345. * if the ground has been updated.
  37346. * This can be used in the render loop
  37347. */
  37348. GroundMesh.prototype.updateCoordinateHeights = function () {
  37349. if (!this._heightQuads || this._heightQuads.length == 0) {
  37350. this._initHeightQuads();
  37351. }
  37352. this._computeHeightQuads();
  37353. };
  37354. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37355. GroundMesh.prototype._getFacetAt = function (x, z) {
  37356. // retrieve col and row from x, z coordinates in the ground local system
  37357. var subdivisionsX = this._subdivisionsX;
  37358. var subdivisionsY = this._subdivisionsY;
  37359. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37360. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37361. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37362. var facet;
  37363. if (z < quad.slope.x * x + quad.slope.y) {
  37364. facet = quad.facet1;
  37365. }
  37366. else {
  37367. facet = quad.facet2;
  37368. }
  37369. return facet;
  37370. };
  37371. // Creates and populates the heightMap array with "facet" elements :
  37372. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37373. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37374. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37375. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37376. GroundMesh.prototype._initHeightQuads = function () {
  37377. var subdivisionsX = this._subdivisionsX;
  37378. var subdivisionsY = this._subdivisionsY;
  37379. this._heightQuads = new Array();
  37380. for (var row = 0; row < subdivisionsY; row++) {
  37381. for (var col = 0; col < subdivisionsX; col++) {
  37382. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  37383. this._heightQuads[row * subdivisionsX + col] = quad;
  37384. }
  37385. }
  37386. };
  37387. // Compute each quad element values and update the the heightMap array :
  37388. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37389. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37390. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37391. GroundMesh.prototype._computeHeightQuads = function () {
  37392. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37393. var v1 = BABYLON.Tmp.Vector3[3];
  37394. var v2 = BABYLON.Tmp.Vector3[2];
  37395. var v3 = BABYLON.Tmp.Vector3[1];
  37396. var v4 = BABYLON.Tmp.Vector3[0];
  37397. var v1v2 = BABYLON.Tmp.Vector3[4];
  37398. var v1v3 = BABYLON.Tmp.Vector3[5];
  37399. var v1v4 = BABYLON.Tmp.Vector3[6];
  37400. var norm1 = BABYLON.Tmp.Vector3[7];
  37401. var norm2 = BABYLON.Tmp.Vector3[8];
  37402. var i = 0;
  37403. var j = 0;
  37404. var k = 0;
  37405. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37406. var h = 0;
  37407. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37408. var d2 = 0;
  37409. var subdivisionsX = this._subdivisionsX;
  37410. var subdivisionsY = this._subdivisionsY;
  37411. for (var row = 0; row < subdivisionsY; row++) {
  37412. for (var col = 0; col < subdivisionsX; col++) {
  37413. i = col * 3;
  37414. j = row * (subdivisionsX + 1) * 3;
  37415. k = (row + 1) * (subdivisionsX + 1) * 3;
  37416. v1.x = positions[j + i];
  37417. v1.y = positions[j + i + 1];
  37418. v1.z = positions[j + i + 2];
  37419. v2.x = positions[j + i + 3];
  37420. v2.y = positions[j + i + 4];
  37421. v2.z = positions[j + i + 5];
  37422. v3.x = positions[k + i];
  37423. v3.y = positions[k + i + 1];
  37424. v3.z = positions[k + i + 2];
  37425. v4.x = positions[k + i + 3];
  37426. v4.y = positions[k + i + 4];
  37427. v4.z = positions[k + i + 5];
  37428. // 2D slope V1V4
  37429. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37430. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37431. // facet equations :
  37432. // we compute each facet normal vector
  37433. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37434. // we compute the value d by applying the equation to v1 which belongs to the plane
  37435. // then we store the facet equation in a Vector4
  37436. v2.subtractToRef(v1, v1v2);
  37437. v3.subtractToRef(v1, v1v3);
  37438. v4.subtractToRef(v1, v1v4);
  37439. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37440. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37441. norm1.normalize();
  37442. norm2.normalize();
  37443. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37444. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37445. var quad = this._heightQuads[row * subdivisionsX + col];
  37446. quad.slope.copyFromFloats(cd, h);
  37447. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37448. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37449. }
  37450. }
  37451. };
  37452. return GroundMesh;
  37453. }(BABYLON.Mesh));
  37454. BABYLON.GroundMesh = GroundMesh;
  37455. })(BABYLON || (BABYLON = {}));
  37456. //# sourceMappingURL=babylon.groundMesh.js.map
  37457. var BABYLON;
  37458. (function (BABYLON) {
  37459. var LinesMesh = (function (_super) {
  37460. __extends(LinesMesh, _super);
  37461. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  37462. if (parent === void 0) { parent = null; }
  37463. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  37464. _this.color = new BABYLON.Color3(1, 1, 1);
  37465. _this.alpha = 1;
  37466. _this._positionBuffer = {};
  37467. if (source) {
  37468. _this.color = source.color.clone();
  37469. _this.alpha = source.alpha;
  37470. }
  37471. _this._intersectionThreshold = 0.1;
  37472. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  37473. attributes: [BABYLON.VertexBuffer.PositionKind],
  37474. uniforms: ["worldViewProjection", "color"],
  37475. needAlphaBlending: true
  37476. });
  37477. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37478. return _this;
  37479. }
  37480. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37481. /**
  37482. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37483. * This margin is expressed in world space coordinates, so its value may vary.
  37484. * Default value is 0.1
  37485. * @returns the intersection Threshold value.
  37486. */
  37487. get: function () {
  37488. return this._intersectionThreshold;
  37489. },
  37490. /**
  37491. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37492. * This margin is expressed in world space coordinates, so its value may vary.
  37493. * @param value the new threshold to apply
  37494. */
  37495. set: function (value) {
  37496. if (this._intersectionThreshold === value) {
  37497. return;
  37498. }
  37499. this._intersectionThreshold = value;
  37500. if (this.geometry) {
  37501. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37502. }
  37503. },
  37504. enumerable: true,
  37505. configurable: true
  37506. });
  37507. LinesMesh.prototype.getClassName = function () {
  37508. return "LinesMesh";
  37509. };
  37510. Object.defineProperty(LinesMesh.prototype, "material", {
  37511. get: function () {
  37512. return this._colorShader;
  37513. },
  37514. enumerable: true,
  37515. configurable: true
  37516. });
  37517. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37518. get: function () {
  37519. return false;
  37520. },
  37521. enumerable: true,
  37522. configurable: true
  37523. });
  37524. LinesMesh.prototype.createInstance = function (name) {
  37525. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37526. return null;
  37527. };
  37528. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37529. var engine = this.getScene().getEngine();
  37530. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37531. // VBOs
  37532. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37533. // Color
  37534. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37535. };
  37536. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37537. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37538. return;
  37539. }
  37540. var engine = this.getScene().getEngine();
  37541. // Draw order
  37542. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37543. };
  37544. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37545. this._colorShader.dispose();
  37546. _super.prototype.dispose.call(this, doNotRecurse);
  37547. };
  37548. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37549. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37550. };
  37551. return LinesMesh;
  37552. }(BABYLON.Mesh));
  37553. BABYLON.LinesMesh = LinesMesh;
  37554. })(BABYLON || (BABYLON = {}));
  37555. //# sourceMappingURL=babylon.linesMesh.js.map
  37556. var BABYLON;
  37557. (function (BABYLON) {
  37558. var DefaultLoadingScreen = (function () {
  37559. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  37560. if (_loadingText === void 0) { _loadingText = ""; }
  37561. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  37562. var _this = this;
  37563. this._renderingCanvas = _renderingCanvas;
  37564. this._loadingText = _loadingText;
  37565. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  37566. // Resize
  37567. this._resizeLoadingUI = function () {
  37568. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  37569. _this._loadingDiv.style.position = "absolute";
  37570. _this._loadingDiv.style.left = canvasRect.left + "px";
  37571. _this._loadingDiv.style.top = canvasRect.top + "px";
  37572. _this._loadingDiv.style.width = canvasRect.width + "px";
  37573. _this._loadingDiv.style.height = canvasRect.height + "px";
  37574. };
  37575. }
  37576. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  37577. var _this = this;
  37578. if (this._loadingDiv) {
  37579. // Do not add a loading screen if there is already one
  37580. return;
  37581. }
  37582. this._loadingDiv = document.createElement("div");
  37583. this._loadingDiv.id = "babylonjsLoadingDiv";
  37584. this._loadingDiv.style.opacity = "0";
  37585. this._loadingDiv.style.transition = "opacity 1.5s ease";
  37586. // Loading text
  37587. this._loadingTextDiv = document.createElement("div");
  37588. this._loadingTextDiv.style.position = "absolute";
  37589. this._loadingTextDiv.style.left = "0";
  37590. this._loadingTextDiv.style.top = "50%";
  37591. this._loadingTextDiv.style.marginTop = "80px";
  37592. this._loadingTextDiv.style.width = "100%";
  37593. this._loadingTextDiv.style.height = "20px";
  37594. this._loadingTextDiv.style.fontFamily = "Arial";
  37595. this._loadingTextDiv.style.fontSize = "14px";
  37596. this._loadingTextDiv.style.color = "white";
  37597. this._loadingTextDiv.style.textAlign = "center";
  37598. this._loadingTextDiv.innerHTML = "Loading";
  37599. this._loadingDiv.appendChild(this._loadingTextDiv);
  37600. //set the predefined text
  37601. this._loadingTextDiv.innerHTML = this._loadingText;
  37602. // Loading img
  37603. var imgBack = new Image();
  37604. 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==";
  37605. imgBack.style.position = "absolute";
  37606. imgBack.style.left = "50%";
  37607. imgBack.style.top = "50%";
  37608. imgBack.style.marginLeft = "-50px";
  37609. imgBack.style.marginTop = "-50px";
  37610. imgBack.style.transition = "transform 1.0s ease";
  37611. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  37612. var deg = 360;
  37613. var onTransitionEnd = function () {
  37614. deg += 360;
  37615. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  37616. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  37617. };
  37618. imgBack.addEventListener("transitionend", onTransitionEnd);
  37619. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  37620. this._loadingDiv.appendChild(imgBack);
  37621. // front image
  37622. var imgFront = new Image();
  37623. 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=";
  37624. imgFront.style.position = "absolute";
  37625. imgFront.style.left = "50%";
  37626. imgFront.style.top = "50%";
  37627. imgFront.style.marginLeft = "-50px";
  37628. imgFront.style.marginTop = "-50px";
  37629. this._loadingDiv.appendChild(imgFront);
  37630. this._resizeLoadingUI();
  37631. window.addEventListener("resize", this._resizeLoadingUI);
  37632. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37633. document.body.appendChild(this._loadingDiv);
  37634. setTimeout(function () {
  37635. _this._loadingDiv.style.opacity = "1";
  37636. imgBack.style.transform = "rotateZ(360deg)";
  37637. imgBack.style.webkitTransform = "rotateZ(360deg)";
  37638. }, 0);
  37639. };
  37640. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  37641. var _this = this;
  37642. if (!this._loadingDiv) {
  37643. return;
  37644. }
  37645. var onTransitionEnd = function () {
  37646. if (!_this._loadingDiv) {
  37647. return;
  37648. }
  37649. document.body.removeChild(_this._loadingDiv);
  37650. window.removeEventListener("resize", _this._resizeLoadingUI);
  37651. _this._loadingDiv = null;
  37652. };
  37653. this._loadingDiv.style.opacity = "0";
  37654. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  37655. };
  37656. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  37657. set: function (text) {
  37658. this._loadingText = text;
  37659. if (this._loadingTextDiv) {
  37660. this._loadingTextDiv.innerHTML = this._loadingText;
  37661. }
  37662. },
  37663. enumerable: true,
  37664. configurable: true
  37665. });
  37666. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  37667. get: function () {
  37668. return this._loadingDivBackgroundColor;
  37669. },
  37670. set: function (color) {
  37671. this._loadingDivBackgroundColor = color;
  37672. if (!this._loadingDiv) {
  37673. return;
  37674. }
  37675. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37676. },
  37677. enumerable: true,
  37678. configurable: true
  37679. });
  37680. return DefaultLoadingScreen;
  37681. }());
  37682. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  37683. })(BABYLON || (BABYLON = {}));
  37684. //# sourceMappingURL=babylon.loadingScreen.js.map
  37685. var BABYLON;
  37686. (function (BABYLON) {
  37687. var AudioEngine = (function () {
  37688. function AudioEngine() {
  37689. this._audioContext = null;
  37690. this._audioContextInitialized = false;
  37691. this.canUseWebAudio = false;
  37692. this.WarnedWebAudioUnsupported = false;
  37693. this.unlocked = false;
  37694. this.isMP3supported = false;
  37695. this.isOGGsupported = false;
  37696. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  37697. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  37698. this.canUseWebAudio = true;
  37699. }
  37700. var audioElem = document.createElement('audio');
  37701. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  37702. this.isMP3supported = true;
  37703. }
  37704. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  37705. this.isOGGsupported = true;
  37706. }
  37707. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  37708. this._unlockiOSaudio();
  37709. }
  37710. else {
  37711. this.unlocked = true;
  37712. }
  37713. }
  37714. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  37715. get: function () {
  37716. if (!this._audioContextInitialized) {
  37717. this._initializeAudioContext();
  37718. }
  37719. return this._audioContext;
  37720. },
  37721. enumerable: true,
  37722. configurable: true
  37723. });
  37724. AudioEngine.prototype._unlockiOSaudio = function () {
  37725. var _this = this;
  37726. var unlockaudio = function () {
  37727. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  37728. var source = _this.audioContext.createBufferSource();
  37729. source.buffer = buffer;
  37730. source.connect(_this.audioContext.destination);
  37731. source.start(0);
  37732. setTimeout(function () {
  37733. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  37734. _this.unlocked = true;
  37735. window.removeEventListener('touchend', unlockaudio, false);
  37736. if (_this.onAudioUnlocked) {
  37737. _this.onAudioUnlocked();
  37738. }
  37739. }
  37740. }, 0);
  37741. };
  37742. window.addEventListener('touchend', unlockaudio, false);
  37743. };
  37744. AudioEngine.prototype._initializeAudioContext = function () {
  37745. try {
  37746. if (this.canUseWebAudio) {
  37747. this._audioContext = new AudioContext();
  37748. // create a global volume gain node
  37749. this.masterGain = this._audioContext.createGain();
  37750. this.masterGain.gain.value = 1;
  37751. this.masterGain.connect(this._audioContext.destination);
  37752. this._audioContextInitialized = true;
  37753. }
  37754. }
  37755. catch (e) {
  37756. this.canUseWebAudio = false;
  37757. BABYLON.Tools.Error("Web Audio: " + e.message);
  37758. }
  37759. };
  37760. AudioEngine.prototype.dispose = function () {
  37761. if (this.canUseWebAudio && this._audioContextInitialized) {
  37762. if (this._connectedAnalyser) {
  37763. this._connectedAnalyser.stopDebugCanvas();
  37764. this._connectedAnalyser.dispose();
  37765. this.masterGain.disconnect();
  37766. this.masterGain.connect(this._audioContext.destination);
  37767. this._connectedAnalyser = null;
  37768. }
  37769. this.masterGain.gain.value = 1;
  37770. }
  37771. this.WarnedWebAudioUnsupported = false;
  37772. };
  37773. AudioEngine.prototype.getGlobalVolume = function () {
  37774. if (this.canUseWebAudio && this._audioContextInitialized) {
  37775. return this.masterGain.gain.value;
  37776. }
  37777. else {
  37778. return -1;
  37779. }
  37780. };
  37781. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  37782. if (this.canUseWebAudio && this._audioContextInitialized) {
  37783. this.masterGain.gain.value = newVolume;
  37784. }
  37785. };
  37786. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  37787. if (this._connectedAnalyser) {
  37788. this._connectedAnalyser.stopDebugCanvas();
  37789. }
  37790. if (this.canUseWebAudio && this._audioContextInitialized) {
  37791. this._connectedAnalyser = analyser;
  37792. this.masterGain.disconnect();
  37793. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  37794. }
  37795. };
  37796. return AudioEngine;
  37797. }());
  37798. BABYLON.AudioEngine = AudioEngine;
  37799. })(BABYLON || (BABYLON = {}));
  37800. //# sourceMappingURL=babylon.audioEngine.js.map
  37801. var BABYLON;
  37802. (function (BABYLON) {
  37803. var Sound = (function () {
  37804. /**
  37805. * Create a sound and attach it to a scene
  37806. * @param name Name of your sound
  37807. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  37808. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  37809. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  37810. */
  37811. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  37812. var _this = this;
  37813. this.autoplay = false;
  37814. this.loop = false;
  37815. this.useCustomAttenuation = false;
  37816. this.spatialSound = false;
  37817. this.refDistance = 1;
  37818. this.rolloffFactor = 1;
  37819. this.maxDistance = 100;
  37820. this.distanceModel = "linear";
  37821. this._panningModel = "equalpower";
  37822. this._playbackRate = 1;
  37823. this._streaming = false;
  37824. this._startTime = 0;
  37825. this._startOffset = 0;
  37826. this._position = BABYLON.Vector3.Zero();
  37827. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  37828. this._volume = 1;
  37829. this._isLoaded = false;
  37830. this._isReadyToPlay = false;
  37831. this.isPlaying = false;
  37832. this.isPaused = false;
  37833. this._isDirectional = false;
  37834. // Used if you'd like to create a directional sound.
  37835. // If not set, the sound will be omnidirectional
  37836. this._coneInnerAngle = 360;
  37837. this._coneOuterAngle = 360;
  37838. this._coneOuterGain = 0;
  37839. this._isOutputConnected = false;
  37840. this._urlType = "Unknown";
  37841. this.name = name;
  37842. this._scene = scene;
  37843. this._readyToPlayCallback = readyToPlayCallback;
  37844. // Default custom attenuation function is a linear attenuation
  37845. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  37846. if (currentDistance < maxDistance) {
  37847. return currentVolume * (1 - currentDistance / maxDistance);
  37848. }
  37849. else {
  37850. return 0;
  37851. }
  37852. };
  37853. if (options) {
  37854. this.autoplay = options.autoplay || false;
  37855. this.loop = options.loop || false;
  37856. // if volume === 0, we need another way to check this option
  37857. if (options.volume !== undefined) {
  37858. this._volume = options.volume;
  37859. }
  37860. this.spatialSound = options.spatialSound || false;
  37861. this.maxDistance = options.maxDistance || 100;
  37862. this.useCustomAttenuation = options.useCustomAttenuation || false;
  37863. this.rolloffFactor = options.rolloffFactor || 1;
  37864. this.refDistance = options.refDistance || 1;
  37865. this.distanceModel = options.distanceModel || "linear";
  37866. this._playbackRate = options.playbackRate || 1;
  37867. this._streaming = options.streaming || false;
  37868. }
  37869. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37870. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  37871. this._soundGain.gain.value = this._volume;
  37872. this._inputAudioNode = this._soundGain;
  37873. this._ouputAudioNode = this._soundGain;
  37874. if (this.spatialSound) {
  37875. this._createSpatialParameters();
  37876. }
  37877. this._scene.mainSoundTrack.AddSound(this);
  37878. var validParameter = true;
  37879. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  37880. if (urlOrArrayBuffer) {
  37881. if (typeof (urlOrArrayBuffer) === "string")
  37882. this._urlType = "String";
  37883. if (Array.isArray(urlOrArrayBuffer))
  37884. this._urlType = "Array";
  37885. if (urlOrArrayBuffer instanceof ArrayBuffer)
  37886. this._urlType = "ArrayBuffer";
  37887. var urls = [];
  37888. var codecSupportedFound = false;
  37889. switch (this._urlType) {
  37890. case "ArrayBuffer":
  37891. if (urlOrArrayBuffer.byteLength > 0) {
  37892. codecSupportedFound = true;
  37893. this._soundLoaded(urlOrArrayBuffer);
  37894. }
  37895. break;
  37896. case "String":
  37897. urls.push(urlOrArrayBuffer);
  37898. case "Array":
  37899. if (urls.length === 0)
  37900. urls = urlOrArrayBuffer;
  37901. // If we found a supported format, we load it immediately and stop the loop
  37902. for (var i = 0; i < urls.length; i++) {
  37903. var url = urls[i];
  37904. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  37905. codecSupportedFound = true;
  37906. }
  37907. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  37908. codecSupportedFound = true;
  37909. }
  37910. if (url.indexOf(".wav", url.length - 4) !== -1) {
  37911. codecSupportedFound = true;
  37912. }
  37913. if (codecSupportedFound) {
  37914. // Loading sound using XHR2
  37915. if (!this._streaming) {
  37916. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  37917. }
  37918. else {
  37919. this._htmlAudioElement = new Audio(url);
  37920. this._htmlAudioElement.controls = false;
  37921. this._htmlAudioElement.loop = this.loop;
  37922. this._htmlAudioElement.crossOrigin = "anonymous";
  37923. this._htmlAudioElement.preload = "auto";
  37924. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  37925. _this._isReadyToPlay = true;
  37926. if (_this.autoplay) {
  37927. _this.play();
  37928. }
  37929. if (_this._readyToPlayCallback) {
  37930. _this._readyToPlayCallback();
  37931. }
  37932. });
  37933. document.body.appendChild(this._htmlAudioElement);
  37934. }
  37935. break;
  37936. }
  37937. }
  37938. break;
  37939. default:
  37940. validParameter = false;
  37941. break;
  37942. }
  37943. if (!validParameter) {
  37944. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  37945. }
  37946. else {
  37947. if (!codecSupportedFound) {
  37948. this._isReadyToPlay = true;
  37949. // Simulating a ready to play event to avoid breaking code path
  37950. if (this._readyToPlayCallback) {
  37951. window.setTimeout(function () {
  37952. _this._readyToPlayCallback();
  37953. }, 1000);
  37954. }
  37955. }
  37956. }
  37957. }
  37958. }
  37959. else {
  37960. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  37961. this._scene.mainSoundTrack.AddSound(this);
  37962. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  37963. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  37964. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  37965. }
  37966. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  37967. if (this._readyToPlayCallback) {
  37968. window.setTimeout(function () {
  37969. _this._readyToPlayCallback();
  37970. }, 1000);
  37971. }
  37972. }
  37973. }
  37974. Sound.prototype.dispose = function () {
  37975. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  37976. if (this.isPlaying) {
  37977. this.stop();
  37978. }
  37979. this._isReadyToPlay = false;
  37980. if (this.soundTrackId === -1) {
  37981. this._scene.mainSoundTrack.RemoveSound(this);
  37982. }
  37983. else {
  37984. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  37985. }
  37986. if (this._soundGain) {
  37987. this._soundGain.disconnect();
  37988. this._soundGain = null;
  37989. }
  37990. if (this._soundPanner) {
  37991. this._soundPanner.disconnect();
  37992. this._soundPanner = null;
  37993. }
  37994. if (this._soundSource) {
  37995. this._soundSource.disconnect();
  37996. this._soundSource = null;
  37997. }
  37998. this._audioBuffer = null;
  37999. if (this._htmlAudioElement) {
  38000. this._htmlAudioElement.pause();
  38001. this._htmlAudioElement.src = "";
  38002. document.body.removeChild(this._htmlAudioElement);
  38003. }
  38004. if (this._connectedMesh) {
  38005. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38006. this._connectedMesh = null;
  38007. }
  38008. }
  38009. };
  38010. Sound.prototype._soundLoaded = function (audioData) {
  38011. var _this = this;
  38012. this._isLoaded = true;
  38013. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  38014. _this._audioBuffer = buffer;
  38015. _this._isReadyToPlay = true;
  38016. if (_this.autoplay) {
  38017. _this.play();
  38018. }
  38019. if (_this._readyToPlayCallback) {
  38020. _this._readyToPlayCallback();
  38021. }
  38022. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  38023. };
  38024. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  38025. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38026. this._audioBuffer = audioBuffer;
  38027. this._isReadyToPlay = true;
  38028. }
  38029. };
  38030. Sound.prototype.updateOptions = function (options) {
  38031. if (options) {
  38032. this.loop = options.loop || this.loop;
  38033. this.maxDistance = options.maxDistance || this.maxDistance;
  38034. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  38035. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  38036. this.refDistance = options.refDistance || this.refDistance;
  38037. this.distanceModel = options.distanceModel || this.distanceModel;
  38038. this._playbackRate = options.playbackRate || this._playbackRate;
  38039. this._updateSpatialParameters();
  38040. if (this.isPlaying) {
  38041. if (this._streaming) {
  38042. this._htmlAudioElement.playbackRate = this._playbackRate;
  38043. }
  38044. else {
  38045. this._soundSource.playbackRate.value = this._playbackRate;
  38046. }
  38047. }
  38048. }
  38049. };
  38050. Sound.prototype._createSpatialParameters = function () {
  38051. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38052. if (this._scene.headphone) {
  38053. this._panningModel = "HRTF";
  38054. }
  38055. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  38056. this._updateSpatialParameters();
  38057. this._soundPanner.connect(this._ouputAudioNode);
  38058. this._inputAudioNode = this._soundPanner;
  38059. }
  38060. };
  38061. Sound.prototype._updateSpatialParameters = function () {
  38062. if (this.spatialSound) {
  38063. if (this.useCustomAttenuation) {
  38064. // Tricks to disable in a way embedded Web Audio attenuation
  38065. this._soundPanner.distanceModel = "linear";
  38066. this._soundPanner.maxDistance = Number.MAX_VALUE;
  38067. this._soundPanner.refDistance = 1;
  38068. this._soundPanner.rolloffFactor = 1;
  38069. this._soundPanner.panningModel = this._panningModel;
  38070. }
  38071. else {
  38072. this._soundPanner.distanceModel = this.distanceModel;
  38073. this._soundPanner.maxDistance = this.maxDistance;
  38074. this._soundPanner.refDistance = this.refDistance;
  38075. this._soundPanner.rolloffFactor = this.rolloffFactor;
  38076. this._soundPanner.panningModel = this._panningModel;
  38077. }
  38078. }
  38079. };
  38080. Sound.prototype.switchPanningModelToHRTF = function () {
  38081. this._panningModel = "HRTF";
  38082. this._switchPanningModel();
  38083. };
  38084. Sound.prototype.switchPanningModelToEqualPower = function () {
  38085. this._panningModel = "equalpower";
  38086. this._switchPanningModel();
  38087. };
  38088. Sound.prototype._switchPanningModel = function () {
  38089. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38090. this._soundPanner.panningModel = this._panningModel;
  38091. }
  38092. };
  38093. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  38094. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38095. if (this._isOutputConnected) {
  38096. this._ouputAudioNode.disconnect();
  38097. }
  38098. this._ouputAudioNode.connect(soundTrackAudioNode);
  38099. this._isOutputConnected = true;
  38100. }
  38101. };
  38102. /**
  38103. * Transform this sound into a directional source
  38104. * @param coneInnerAngle Size of the inner cone in degree
  38105. * @param coneOuterAngle Size of the outer cone in degree
  38106. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  38107. */
  38108. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  38109. if (coneOuterAngle < coneInnerAngle) {
  38110. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  38111. return;
  38112. }
  38113. this._coneInnerAngle = coneInnerAngle;
  38114. this._coneOuterAngle = coneOuterAngle;
  38115. this._coneOuterGain = coneOuterGain;
  38116. this._isDirectional = true;
  38117. if (this.isPlaying && this.loop) {
  38118. this.stop();
  38119. this.play();
  38120. }
  38121. };
  38122. Sound.prototype.setPosition = function (newPosition) {
  38123. this._position = newPosition;
  38124. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38125. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38126. }
  38127. };
  38128. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  38129. this._localDirection = newLocalDirection;
  38130. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  38131. this._updateDirection();
  38132. }
  38133. };
  38134. Sound.prototype._updateDirection = function () {
  38135. var mat = this._connectedMesh.getWorldMatrix();
  38136. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  38137. direction.normalize();
  38138. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  38139. };
  38140. Sound.prototype.updateDistanceFromListener = function () {
  38141. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  38142. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  38143. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  38144. }
  38145. };
  38146. Sound.prototype.setAttenuationFunction = function (callback) {
  38147. this._customAttenuationFunction = callback;
  38148. };
  38149. /**
  38150. * Play the sound
  38151. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  38152. * @param offset (optional) Start the sound setting it at a specific time
  38153. */
  38154. Sound.prototype.play = function (time, offset) {
  38155. var _this = this;
  38156. if (this._isReadyToPlay && this._scene.audioEnabled) {
  38157. try {
  38158. if (this._startOffset < 0) {
  38159. time = -this._startOffset;
  38160. this._startOffset = 0;
  38161. }
  38162. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38163. if (!this._soundSource || !this._streamingSource) {
  38164. if (this.spatialSound) {
  38165. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38166. if (this._isDirectional) {
  38167. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  38168. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  38169. this._soundPanner.coneOuterGain = this._coneOuterGain;
  38170. if (this._connectedMesh) {
  38171. this._updateDirection();
  38172. }
  38173. else {
  38174. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  38175. }
  38176. }
  38177. }
  38178. }
  38179. if (this._streaming) {
  38180. if (!this._streamingSource) {
  38181. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  38182. this._htmlAudioElement.onended = function () { _this._onended(); };
  38183. this._htmlAudioElement.playbackRate = this._playbackRate;
  38184. }
  38185. this._streamingSource.disconnect();
  38186. this._streamingSource.connect(this._inputAudioNode);
  38187. this._htmlAudioElement.play();
  38188. }
  38189. else {
  38190. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  38191. this._soundSource.buffer = this._audioBuffer;
  38192. this._soundSource.connect(this._inputAudioNode);
  38193. this._soundSource.loop = this.loop;
  38194. this._soundSource.playbackRate.value = this._playbackRate;
  38195. this._soundSource.onended = function () { _this._onended(); };
  38196. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  38197. }
  38198. this._startTime = startTime;
  38199. this.isPlaying = true;
  38200. this.isPaused = false;
  38201. }
  38202. catch (ex) {
  38203. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  38204. }
  38205. }
  38206. };
  38207. Sound.prototype._onended = function () {
  38208. this.isPlaying = false;
  38209. if (this.onended) {
  38210. this.onended();
  38211. }
  38212. };
  38213. /**
  38214. * Stop the sound
  38215. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  38216. */
  38217. Sound.prototype.stop = function (time) {
  38218. if (this.isPlaying) {
  38219. if (this._streaming) {
  38220. this._htmlAudioElement.pause();
  38221. // Test needed for Firefox or it will generate an Invalid State Error
  38222. if (this._htmlAudioElement.currentTime > 0) {
  38223. this._htmlAudioElement.currentTime = 0;
  38224. }
  38225. }
  38226. else {
  38227. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38228. this._soundSource.stop(stopTime);
  38229. this._soundSource.onended = null;
  38230. if (!this.isPaused) {
  38231. this._startOffset = 0;
  38232. }
  38233. }
  38234. this.isPlaying = false;
  38235. }
  38236. };
  38237. Sound.prototype.pause = function () {
  38238. if (this.isPlaying) {
  38239. this.isPaused = true;
  38240. if (this._streaming) {
  38241. this._htmlAudioElement.pause();
  38242. }
  38243. else {
  38244. this.stop(0);
  38245. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  38246. }
  38247. }
  38248. };
  38249. Sound.prototype.setVolume = function (newVolume, time) {
  38250. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38251. if (time) {
  38252. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  38253. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  38254. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  38255. }
  38256. else {
  38257. this._soundGain.gain.value = newVolume;
  38258. }
  38259. }
  38260. this._volume = newVolume;
  38261. };
  38262. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  38263. this._playbackRate = newPlaybackRate;
  38264. if (this.isPlaying) {
  38265. if (this._streaming) {
  38266. this._htmlAudioElement.playbackRate = this._playbackRate;
  38267. }
  38268. else {
  38269. this._soundSource.playbackRate.value = this._playbackRate;
  38270. }
  38271. }
  38272. };
  38273. Sound.prototype.getVolume = function () {
  38274. return this._volume;
  38275. };
  38276. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  38277. var _this = this;
  38278. if (this._connectedMesh) {
  38279. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38280. this._registerFunc = null;
  38281. }
  38282. this._connectedMesh = meshToConnectTo;
  38283. if (!this.spatialSound) {
  38284. this.spatialSound = true;
  38285. this._createSpatialParameters();
  38286. if (this.isPlaying && this.loop) {
  38287. this.stop();
  38288. this.play();
  38289. }
  38290. }
  38291. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  38292. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  38293. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  38294. };
  38295. Sound.prototype.detachFromMesh = function () {
  38296. if (this._connectedMesh) {
  38297. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38298. this._registerFunc = null;
  38299. this._connectedMesh = null;
  38300. }
  38301. };
  38302. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  38303. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  38304. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  38305. this._updateDirection();
  38306. }
  38307. };
  38308. Sound.prototype.clone = function () {
  38309. var _this = this;
  38310. if (!this._streaming) {
  38311. var setBufferAndRun = function () {
  38312. if (_this._isReadyToPlay) {
  38313. clonedSound._audioBuffer = _this.getAudioBuffer();
  38314. clonedSound._isReadyToPlay = true;
  38315. if (clonedSound.autoplay) {
  38316. clonedSound.play();
  38317. }
  38318. }
  38319. else {
  38320. window.setTimeout(setBufferAndRun, 300);
  38321. }
  38322. };
  38323. var currentOptions = {
  38324. autoplay: this.autoplay, loop: this.loop,
  38325. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  38326. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  38327. refDistance: this.refDistance, distanceModel: this.distanceModel
  38328. };
  38329. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  38330. if (this.useCustomAttenuation) {
  38331. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  38332. }
  38333. clonedSound.setPosition(this._position);
  38334. clonedSound.setPlaybackRate(this._playbackRate);
  38335. setBufferAndRun();
  38336. return clonedSound;
  38337. }
  38338. else {
  38339. return null;
  38340. }
  38341. };
  38342. Sound.prototype.getAudioBuffer = function () {
  38343. return this._audioBuffer;
  38344. };
  38345. Sound.prototype.serialize = function () {
  38346. var serializationObject = {
  38347. name: this.name,
  38348. url: this.name,
  38349. autoplay: this.autoplay,
  38350. loop: this.loop,
  38351. volume: this._volume,
  38352. spatialSound: this.spatialSound,
  38353. maxDistance: this.maxDistance,
  38354. rolloffFactor: this.rolloffFactor,
  38355. refDistance: this.refDistance,
  38356. distanceModel: this.distanceModel,
  38357. playbackRate: this._playbackRate,
  38358. panningModel: this._panningModel,
  38359. soundTrackId: this.soundTrackId
  38360. };
  38361. if (this.spatialSound) {
  38362. if (this._connectedMesh)
  38363. serializationObject.connectedMeshId = this._connectedMesh.id;
  38364. serializationObject.position = this._position.asArray();
  38365. serializationObject.refDistance = this.refDistance;
  38366. serializationObject.distanceModel = this.distanceModel;
  38367. serializationObject.isDirectional = this._isDirectional;
  38368. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  38369. serializationObject.coneInnerAngle = this._coneInnerAngle;
  38370. serializationObject.coneOuterAngle = this._coneOuterAngle;
  38371. serializationObject.coneOuterGain = this._coneOuterGain;
  38372. }
  38373. return serializationObject;
  38374. };
  38375. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  38376. var soundName = parsedSound.name;
  38377. var soundUrl;
  38378. if (parsedSound.url) {
  38379. soundUrl = rootUrl + parsedSound.url;
  38380. }
  38381. else {
  38382. soundUrl = rootUrl + soundName;
  38383. }
  38384. var options = {
  38385. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  38386. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  38387. rolloffFactor: parsedSound.rolloffFactor,
  38388. refDistance: parsedSound.refDistance,
  38389. distanceModel: parsedSound.distanceModel,
  38390. playbackRate: parsedSound.playbackRate
  38391. };
  38392. var newSound;
  38393. if (!sourceSound) {
  38394. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  38395. scene._addPendingData(newSound);
  38396. }
  38397. else {
  38398. var setBufferAndRun = function () {
  38399. if (sourceSound._isReadyToPlay) {
  38400. newSound._audioBuffer = sourceSound.getAudioBuffer();
  38401. newSound._isReadyToPlay = true;
  38402. if (newSound.autoplay) {
  38403. newSound.play();
  38404. }
  38405. }
  38406. else {
  38407. window.setTimeout(setBufferAndRun, 300);
  38408. }
  38409. };
  38410. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  38411. setBufferAndRun();
  38412. }
  38413. if (parsedSound.position) {
  38414. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  38415. newSound.setPosition(soundPosition);
  38416. }
  38417. if (parsedSound.isDirectional) {
  38418. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  38419. if (parsedSound.localDirectionToMesh) {
  38420. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  38421. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  38422. }
  38423. }
  38424. if (parsedSound.connectedMeshId) {
  38425. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  38426. if (connectedMesh) {
  38427. newSound.attachToMesh(connectedMesh);
  38428. }
  38429. }
  38430. return newSound;
  38431. };
  38432. return Sound;
  38433. }());
  38434. BABYLON.Sound = Sound;
  38435. })(BABYLON || (BABYLON = {}));
  38436. //# sourceMappingURL=babylon.sound.js.map
  38437. var BABYLON;
  38438. (function (BABYLON) {
  38439. var SoundTrack = (function () {
  38440. function SoundTrack(scene, options) {
  38441. this.id = -1;
  38442. this._isMainTrack = false;
  38443. this._isInitialized = false;
  38444. this._scene = scene;
  38445. this.soundCollection = new Array();
  38446. this._options = options;
  38447. if (!this._isMainTrack) {
  38448. this._scene.soundTracks.push(this);
  38449. this.id = this._scene.soundTracks.length - 1;
  38450. }
  38451. }
  38452. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  38453. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38454. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  38455. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  38456. if (this._options) {
  38457. if (this._options.volume) {
  38458. this._outputAudioNode.gain.value = this._options.volume;
  38459. }
  38460. if (this._options.mainTrack) {
  38461. this._isMainTrack = this._options.mainTrack;
  38462. }
  38463. }
  38464. this._isInitialized = true;
  38465. }
  38466. };
  38467. SoundTrack.prototype.dispose = function () {
  38468. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38469. if (this._connectedAnalyser) {
  38470. this._connectedAnalyser.stopDebugCanvas();
  38471. }
  38472. while (this.soundCollection.length) {
  38473. this.soundCollection[0].dispose();
  38474. }
  38475. if (this._outputAudioNode) {
  38476. this._outputAudioNode.disconnect();
  38477. }
  38478. this._outputAudioNode = null;
  38479. }
  38480. };
  38481. SoundTrack.prototype.AddSound = function (sound) {
  38482. if (!this._isInitialized) {
  38483. this._initializeSoundTrackAudioGraph();
  38484. }
  38485. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38486. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  38487. }
  38488. if (sound.soundTrackId) {
  38489. if (sound.soundTrackId === -1) {
  38490. this._scene.mainSoundTrack.RemoveSound(sound);
  38491. }
  38492. else {
  38493. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  38494. }
  38495. }
  38496. this.soundCollection.push(sound);
  38497. sound.soundTrackId = this.id;
  38498. };
  38499. SoundTrack.prototype.RemoveSound = function (sound) {
  38500. var index = this.soundCollection.indexOf(sound);
  38501. if (index !== -1) {
  38502. this.soundCollection.splice(index, 1);
  38503. }
  38504. };
  38505. SoundTrack.prototype.setVolume = function (newVolume) {
  38506. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38507. this._outputAudioNode.gain.value = newVolume;
  38508. }
  38509. };
  38510. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  38511. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38512. for (var i = 0; i < this.soundCollection.length; i++) {
  38513. this.soundCollection[i].switchPanningModelToHRTF();
  38514. }
  38515. }
  38516. };
  38517. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  38518. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38519. for (var i = 0; i < this.soundCollection.length; i++) {
  38520. this.soundCollection[i].switchPanningModelToEqualPower();
  38521. }
  38522. }
  38523. };
  38524. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  38525. if (this._connectedAnalyser) {
  38526. this._connectedAnalyser.stopDebugCanvas();
  38527. }
  38528. this._connectedAnalyser = analyser;
  38529. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38530. this._outputAudioNode.disconnect();
  38531. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  38532. }
  38533. };
  38534. return SoundTrack;
  38535. }());
  38536. BABYLON.SoundTrack = SoundTrack;
  38537. })(BABYLON || (BABYLON = {}));
  38538. //# sourceMappingURL=babylon.soundtrack.js.map
  38539. var BABYLON;
  38540. (function (BABYLON) {
  38541. /**
  38542. * Special Glow Blur post process only blurring the alpha channel
  38543. * It enforces keeping the most luminous color in the color channel.
  38544. */
  38545. var GlowBlurPostProcess = (function (_super) {
  38546. __extends(GlowBlurPostProcess, _super);
  38547. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  38548. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38549. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  38550. _this.direction = direction;
  38551. _this.blurWidth = blurWidth;
  38552. _this.onApplyObservable.add(function (effect) {
  38553. effect.setFloat2("screenSize", _this.width, _this.height);
  38554. effect.setVector2("direction", _this.direction);
  38555. effect.setFloat("blurWidth", _this.blurWidth);
  38556. });
  38557. return _this;
  38558. }
  38559. return GlowBlurPostProcess;
  38560. }(BABYLON.PostProcess));
  38561. /**
  38562. * The highlight layer Helps adding a glow effect around a mesh.
  38563. *
  38564. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  38565. * glowy meshes to your scene.
  38566. *
  38567. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  38568. */
  38569. var HighlightLayer = (function () {
  38570. /**
  38571. * Instantiates a new highlight Layer and references it to the scene..
  38572. * @param name The name of the layer
  38573. * @param scene The scene to use the layer in
  38574. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  38575. */
  38576. function HighlightLayer(name, scene, options) {
  38577. this._vertexBuffers = {};
  38578. this._mainTextureDesiredSize = { width: 0, height: 0 };
  38579. this._meshes = {};
  38580. this._maxSize = 0;
  38581. this._shouldRender = false;
  38582. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  38583. this._excludedMeshes = {};
  38584. /**
  38585. * Specifies whether or not the inner glow is ACTIVE in the layer.
  38586. */
  38587. this.innerGlow = true;
  38588. /**
  38589. * Specifies whether or not the outer glow is ACTIVE in the layer.
  38590. */
  38591. this.outerGlow = true;
  38592. /**
  38593. * Specifies wether the highlight layer is enabled or not.
  38594. */
  38595. this.isEnabled = true;
  38596. /**
  38597. * An event triggered when the highlight layer has been disposed.
  38598. * @type {BABYLON.Observable}
  38599. */
  38600. this.onDisposeObservable = new BABYLON.Observable();
  38601. /**
  38602. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  38603. * @type {BABYLON.Observable}
  38604. */
  38605. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  38606. /**
  38607. * An event triggered when the highlight layer is being blurred.
  38608. * @type {BABYLON.Observable}
  38609. */
  38610. this.onBeforeBlurObservable = new BABYLON.Observable();
  38611. /**
  38612. * An event triggered when the highlight layer has been blurred.
  38613. * @type {BABYLON.Observable}
  38614. */
  38615. this.onAfterBlurObservable = new BABYLON.Observable();
  38616. /**
  38617. * An event triggered when the glowing blurred texture is being merged in the scene.
  38618. * @type {BABYLON.Observable}
  38619. */
  38620. this.onBeforeComposeObservable = new BABYLON.Observable();
  38621. /**
  38622. * An event triggered when the glowing blurred texture has been merged in the scene.
  38623. * @type {BABYLON.Observable}
  38624. */
  38625. this.onAfterComposeObservable = new BABYLON.Observable();
  38626. /**
  38627. * An event triggered when the highlight layer changes its size.
  38628. * @type {BABYLON.Observable}
  38629. */
  38630. this.onSizeChangedObservable = new BABYLON.Observable();
  38631. this._scene = scene;
  38632. var engine = scene.getEngine();
  38633. this._engine = engine;
  38634. this._maxSize = this._engine.getCaps().maxTextureSize;
  38635. this._scene.highlightLayers.push(this);
  38636. // Warn on stencil.
  38637. if (!this._engine.isStencilEnable) {
  38638. 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 }");
  38639. }
  38640. // Adapt options
  38641. this._options = options || {
  38642. mainTextureRatio: 0.25,
  38643. blurTextureSizeRatio: 0.5,
  38644. blurHorizontalSize: 1,
  38645. blurVerticalSize: 1,
  38646. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  38647. };
  38648. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  38649. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  38650. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  38651. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  38652. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  38653. // VBO
  38654. var vertices = [];
  38655. vertices.push(1, 1);
  38656. vertices.push(-1, 1);
  38657. vertices.push(-1, -1);
  38658. vertices.push(1, -1);
  38659. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38660. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38661. // Indices
  38662. var indices = [];
  38663. indices.push(0);
  38664. indices.push(1);
  38665. indices.push(2);
  38666. indices.push(0);
  38667. indices.push(2);
  38668. indices.push(3);
  38669. this._indexBuffer = engine.createIndexBuffer(indices);
  38670. // Effect
  38671. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  38672. // Render target
  38673. this.setMainTextureSize();
  38674. // Create Textures and post processes
  38675. this.createTextureAndPostProcesses();
  38676. }
  38677. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  38678. /**
  38679. * Gets the horizontal size of the blur.
  38680. */
  38681. get: function () {
  38682. return this._horizontalBlurPostprocess.blurWidth;
  38683. },
  38684. /**
  38685. * Specifies the horizontal size of the blur.
  38686. */
  38687. set: function (value) {
  38688. this._horizontalBlurPostprocess.blurWidth = value;
  38689. },
  38690. enumerable: true,
  38691. configurable: true
  38692. });
  38693. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  38694. /**
  38695. * Gets the vertical size of the blur.
  38696. */
  38697. get: function () {
  38698. return this._verticalBlurPostprocess.blurWidth;
  38699. },
  38700. /**
  38701. * Specifies the vertical size of the blur.
  38702. */
  38703. set: function (value) {
  38704. this._verticalBlurPostprocess.blurWidth = value;
  38705. },
  38706. enumerable: true,
  38707. configurable: true
  38708. });
  38709. Object.defineProperty(HighlightLayer.prototype, "camera", {
  38710. /**
  38711. * Gets the camera attached to the layer.
  38712. */
  38713. get: function () {
  38714. return this._options.camera;
  38715. },
  38716. enumerable: true,
  38717. configurable: true
  38718. });
  38719. /**
  38720. * Creates the render target textures and post processes used in the highlight layer.
  38721. */
  38722. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  38723. var _this = this;
  38724. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  38725. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  38726. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  38727. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  38728. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  38729. width: this._mainTextureDesiredSize.width,
  38730. height: this._mainTextureDesiredSize.height
  38731. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38732. this._mainTexture.activeCamera = this._options.camera;
  38733. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38734. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38735. this._mainTexture.anisotropicFilteringLevel = 1;
  38736. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38737. this._mainTexture.renderParticles = false;
  38738. this._mainTexture.renderList = null;
  38739. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  38740. width: blurTextureWidth,
  38741. height: blurTextureHeight
  38742. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38743. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38744. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38745. this._blurTexture.anisotropicFilteringLevel = 16;
  38746. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38747. this._blurTexture.renderParticles = false;
  38748. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38749. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  38750. effect.setTexture("textureSampler", _this._mainTexture);
  38751. });
  38752. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  38753. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38754. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38755. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38756. });
  38757. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38758. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38759. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38760. });
  38761. }
  38762. else {
  38763. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38764. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38765. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38766. });
  38767. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38768. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38769. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38770. });
  38771. }
  38772. this._mainTexture.onAfterUnbindObservable.add(function () {
  38773. _this.onBeforeBlurObservable.notifyObservers(_this);
  38774. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  38775. _this.onAfterBlurObservable.notifyObservers(_this);
  38776. });
  38777. // Custom render function
  38778. var renderSubMesh = function (subMesh) {
  38779. var mesh = subMesh.getRenderingMesh();
  38780. var scene = _this._scene;
  38781. var engine = scene.getEngine();
  38782. // Culling
  38783. engine.setState(subMesh.getMaterial().backFaceCulling);
  38784. // Managing instances
  38785. var batch = mesh._getInstancesRenderList(subMesh._id);
  38786. if (batch.mustReturn) {
  38787. return;
  38788. }
  38789. // Excluded Mesh
  38790. if (_this._excludedMeshes[mesh.uniqueId]) {
  38791. return;
  38792. }
  38793. ;
  38794. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38795. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  38796. var material = subMesh.getMaterial();
  38797. var emissiveTexture = null;
  38798. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  38799. emissiveTexture = material.emissiveTexture;
  38800. }
  38801. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  38802. engine.enableEffect(_this._glowMapGenerationEffect);
  38803. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  38804. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  38805. if (highlightLayerMesh) {
  38806. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  38807. }
  38808. else {
  38809. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  38810. }
  38811. // Alpha test
  38812. if (material && material.needAlphaTesting()) {
  38813. var alphaTexture = material.getAlphaTestTexture();
  38814. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  38815. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38816. }
  38817. // Glow emissive only
  38818. if (emissiveTexture) {
  38819. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  38820. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  38821. }
  38822. // Bones
  38823. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38824. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38825. }
  38826. // Draw
  38827. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  38828. }
  38829. else {
  38830. // Need to reset refresh rate of the shadowMap
  38831. _this._mainTexture.resetRefreshCounter();
  38832. }
  38833. };
  38834. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38835. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  38836. var index;
  38837. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38838. renderSubMesh(opaqueSubMeshes.data[index]);
  38839. }
  38840. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38841. renderSubMesh(alphaTestSubMeshes.data[index]);
  38842. }
  38843. for (index = 0; index < transparentSubMeshes.length; index++) {
  38844. renderSubMesh(transparentSubMeshes.data[index]);
  38845. }
  38846. };
  38847. this._mainTexture.onClearObservable.add(function (engine) {
  38848. engine.clear(HighlightLayer.neutralColor, true, true, true);
  38849. });
  38850. };
  38851. /**
  38852. * Checks for the readiness of the element composing the layer.
  38853. * @param subMesh the mesh to check for
  38854. * @param useInstances specify wether or not to use instances to render the mesh
  38855. * @param emissiveTexture the associated emissive texture used to generate the glow
  38856. * @return true if ready otherwise, false
  38857. */
  38858. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  38859. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  38860. return false;
  38861. }
  38862. var defines = [];
  38863. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38864. var mesh = subMesh.getMesh();
  38865. var material = subMesh.getMaterial();
  38866. var uv1 = false;
  38867. var uv2 = false;
  38868. // Alpha test
  38869. if (material && material.needAlphaTesting()) {
  38870. var alphaTexture = material.getAlphaTestTexture();
  38871. if (alphaTexture) {
  38872. defines.push("#define ALPHATEST");
  38873. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38874. alphaTexture.coordinatesIndex === 1) {
  38875. defines.push("#define DIFFUSEUV2");
  38876. uv2 = true;
  38877. }
  38878. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38879. defines.push("#define DIFFUSEUV1");
  38880. uv1 = true;
  38881. }
  38882. }
  38883. }
  38884. // Emissive
  38885. if (emissiveTexture) {
  38886. defines.push("#define EMISSIVE");
  38887. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38888. emissiveTexture.coordinatesIndex === 1) {
  38889. defines.push("#define EMISSIVEUV2");
  38890. uv2 = true;
  38891. }
  38892. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38893. defines.push("#define EMISSIVEUV1");
  38894. uv1 = true;
  38895. }
  38896. }
  38897. if (uv1) {
  38898. attribs.push(BABYLON.VertexBuffer.UVKind);
  38899. defines.push("#define UV1");
  38900. }
  38901. if (uv2) {
  38902. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38903. defines.push("#define UV2");
  38904. }
  38905. // Bones
  38906. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38907. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38908. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38909. if (mesh.numBoneInfluencers > 4) {
  38910. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38911. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38912. }
  38913. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38914. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38915. }
  38916. else {
  38917. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38918. }
  38919. // Instances
  38920. if (useInstances) {
  38921. defines.push("#define INSTANCES");
  38922. attribs.push("world0");
  38923. attribs.push("world1");
  38924. attribs.push("world2");
  38925. attribs.push("world3");
  38926. }
  38927. // Get correct effect
  38928. var join = defines.join("\n");
  38929. if (this._cachedDefines !== join) {
  38930. this._cachedDefines = join;
  38931. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  38932. }
  38933. return this._glowMapGenerationEffect.isReady();
  38934. };
  38935. /**
  38936. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  38937. */
  38938. HighlightLayer.prototype.render = function () {
  38939. var currentEffect = this._glowMapMergeEffect;
  38940. // Check
  38941. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  38942. return;
  38943. var engine = this._scene.getEngine();
  38944. this.onBeforeComposeObservable.notifyObservers(this);
  38945. // Render
  38946. engine.enableEffect(currentEffect);
  38947. engine.setState(false);
  38948. // Cache
  38949. var previousStencilBuffer = engine.getStencilBuffer();
  38950. var previousStencilFunction = engine.getStencilFunction();
  38951. var previousStencilMask = engine.getStencilMask();
  38952. var previousAlphaMode = engine.getAlphaMode();
  38953. // Texture
  38954. currentEffect.setTexture("textureSampler", this._blurTexture);
  38955. // VBOs
  38956. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38957. // Draw order
  38958. engine.setAlphaMode(this._options.alphaBlendingMode);
  38959. engine.setStencilMask(0x00);
  38960. engine.setStencilBuffer(true);
  38961. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  38962. if (this.outerGlow) {
  38963. currentEffect.setFloat("offset", 0);
  38964. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  38965. engine.draw(true, 0, 6);
  38966. }
  38967. if (this.innerGlow) {
  38968. currentEffect.setFloat("offset", 1);
  38969. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  38970. engine.draw(true, 0, 6);
  38971. }
  38972. // Restore Cache
  38973. engine.setStencilFunction(previousStencilFunction);
  38974. engine.setStencilMask(previousStencilMask);
  38975. engine.setAlphaMode(previousAlphaMode);
  38976. engine.setStencilBuffer(previousStencilBuffer);
  38977. this.onAfterComposeObservable.notifyObservers(this);
  38978. // Handle size changes.
  38979. var size = this._mainTexture.getSize();
  38980. this.setMainTextureSize();
  38981. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  38982. // Recreate RTT and post processes on size change.
  38983. this.onSizeChangedObservable.notifyObservers(this);
  38984. this.disposeTextureAndPostProcesses();
  38985. this.createTextureAndPostProcesses();
  38986. }
  38987. };
  38988. /**
  38989. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  38990. * @param mesh The mesh to exclude from the highlight layer
  38991. */
  38992. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  38993. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  38994. if (!meshExcluded) {
  38995. this._excludedMeshes[mesh.uniqueId] = {
  38996. mesh: mesh,
  38997. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  38998. mesh.getEngine().setStencilBuffer(false);
  38999. }),
  39000. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  39001. mesh.getEngine().setStencilBuffer(true);
  39002. }),
  39003. };
  39004. }
  39005. };
  39006. /**
  39007. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  39008. * @param mesh The mesh to highlight
  39009. */
  39010. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  39011. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39012. if (meshExcluded) {
  39013. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  39014. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  39015. }
  39016. this._excludedMeshes[mesh.uniqueId] = undefined;
  39017. };
  39018. /**
  39019. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  39020. * @param mesh The mesh to highlight
  39021. * @param color The color of the highlight
  39022. * @param glowEmissiveOnly Extract the glow from the emissive texture
  39023. */
  39024. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  39025. var _this = this;
  39026. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  39027. var meshHighlight = this._meshes[mesh.uniqueId];
  39028. if (meshHighlight) {
  39029. meshHighlight.color = color;
  39030. }
  39031. else {
  39032. this._meshes[mesh.uniqueId] = {
  39033. mesh: mesh,
  39034. color: color,
  39035. // Lambda required for capture due to Observable this context
  39036. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  39037. if (_this._excludedMeshes[mesh.uniqueId]) {
  39038. _this.defaultStencilReference(mesh);
  39039. }
  39040. else {
  39041. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  39042. }
  39043. }),
  39044. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  39045. glowEmissiveOnly: glowEmissiveOnly
  39046. };
  39047. }
  39048. this._shouldRender = true;
  39049. };
  39050. /**
  39051. * Remove a mesh from the highlight layer in order to make it stop glowing.
  39052. * @param mesh The mesh to highlight
  39053. */
  39054. HighlightLayer.prototype.removeMesh = function (mesh) {
  39055. var meshHighlight = this._meshes[mesh.uniqueId];
  39056. if (meshHighlight) {
  39057. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39058. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39059. }
  39060. this._meshes[mesh.uniqueId] = undefined;
  39061. this._shouldRender = false;
  39062. for (var meshHighlightToCheck in this._meshes) {
  39063. if (meshHighlightToCheck) {
  39064. this._shouldRender = true;
  39065. break;
  39066. }
  39067. }
  39068. };
  39069. /**
  39070. * Returns true if the layer contains information to display, otherwise false.
  39071. */
  39072. HighlightLayer.prototype.shouldRender = function () {
  39073. return this.isEnabled && this._shouldRender;
  39074. };
  39075. /**
  39076. * Sets the main texture desired size which is the closest power of two
  39077. * of the engine canvas size.
  39078. */
  39079. HighlightLayer.prototype.setMainTextureSize = function () {
  39080. if (this._options.mainTextureFixedSize) {
  39081. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  39082. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  39083. }
  39084. else {
  39085. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  39086. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  39087. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  39088. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  39089. }
  39090. };
  39091. /**
  39092. * Force the stencil to the normal expected value for none glowing parts
  39093. */
  39094. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  39095. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  39096. };
  39097. /**
  39098. * Dispose only the render target textures and post process.
  39099. */
  39100. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  39101. this._blurTexture.dispose();
  39102. this._mainTexture.dispose();
  39103. this._downSamplePostprocess.dispose();
  39104. this._horizontalBlurPostprocess.dispose();
  39105. this._verticalBlurPostprocess.dispose();
  39106. };
  39107. /**
  39108. * Dispose the highlight layer and free resources.
  39109. */
  39110. HighlightLayer.prototype.dispose = function () {
  39111. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39112. if (vertexBuffer) {
  39113. vertexBuffer.dispose();
  39114. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39115. }
  39116. if (this._indexBuffer) {
  39117. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39118. this._indexBuffer = null;
  39119. }
  39120. // Clean textures and post processes
  39121. this.disposeTextureAndPostProcesses();
  39122. // Clean mesh references
  39123. for (var id in this._meshes) {
  39124. var meshHighlight = this._meshes[id];
  39125. if (meshHighlight && meshHighlight.mesh) {
  39126. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39127. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39128. }
  39129. }
  39130. this._meshes = null;
  39131. for (var id in this._excludedMeshes) {
  39132. var meshHighlight = this._excludedMeshes[id];
  39133. if (meshHighlight) {
  39134. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  39135. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  39136. }
  39137. }
  39138. this._excludedMeshes = null;
  39139. // Remove from scene
  39140. var index = this._scene.highlightLayers.indexOf(this, 0);
  39141. if (index > -1) {
  39142. this._scene.highlightLayers.splice(index, 1);
  39143. }
  39144. // Callback
  39145. this.onDisposeObservable.notifyObservers(this);
  39146. this.onDisposeObservable.clear();
  39147. this.onBeforeRenderMainTextureObservable.clear();
  39148. this.onBeforeBlurObservable.clear();
  39149. this.onBeforeComposeObservable.clear();
  39150. this.onAfterComposeObservable.clear();
  39151. this.onSizeChangedObservable.clear();
  39152. };
  39153. return HighlightLayer;
  39154. }());
  39155. /**
  39156. * The neutral color used during the preparation of the glow effect.
  39157. * This is black by default as the blend operation is a blend operation.
  39158. */
  39159. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  39160. /**
  39161. * Stencil value used for glowing meshes.
  39162. */
  39163. HighlightLayer.glowingMeshStencilReference = 0x02;
  39164. /**
  39165. * Stencil value used for the other meshes in the scene.
  39166. */
  39167. HighlightLayer.normalMeshStencilReference = 0x01;
  39168. BABYLON.HighlightLayer = HighlightLayer;
  39169. })(BABYLON || (BABYLON = {}));
  39170. //# sourceMappingURL=babylon.highlightlayer.js.map
  39171. var BABYLON;
  39172. (function (BABYLON) {
  39173. var SIMDVector3 = (function () {
  39174. function SIMDVector3() {
  39175. }
  39176. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  39177. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  39178. };
  39179. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  39180. var m = transformation.m;
  39181. var m0 = SIMD.Float32x4.load(m, 0);
  39182. var m1 = SIMD.Float32x4.load(m, 4);
  39183. var m2 = SIMD.Float32x4.load(m, 8);
  39184. var m3 = SIMD.Float32x4.load(m, 12);
  39185. 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));
  39186. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  39187. result.x = SIMD.Float32x4.extractLane(r, 0);
  39188. result.y = SIMD.Float32x4.extractLane(r, 1);
  39189. result.z = SIMD.Float32x4.extractLane(r, 2);
  39190. };
  39191. return SIMDVector3;
  39192. }());
  39193. var SIMDMatrix = (function () {
  39194. function SIMDMatrix() {
  39195. }
  39196. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  39197. var tm = this.m;
  39198. var om = other.m;
  39199. var m0 = SIMD.Float32x4.load(om, 0);
  39200. var m1 = SIMD.Float32x4.load(om, 4);
  39201. var m2 = SIMD.Float32x4.load(om, 8);
  39202. var m3 = SIMD.Float32x4.load(om, 12);
  39203. for (var i = 0; i < 16; i += 4) {
  39204. 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)))));
  39205. }
  39206. return this;
  39207. };
  39208. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  39209. var src = this.m;
  39210. var dest = other.m;
  39211. // Load the 4 rows
  39212. var src0 = SIMD.Float32x4.load(src, 0);
  39213. var src1 = SIMD.Float32x4.load(src, 4);
  39214. var src2 = SIMD.Float32x4.load(src, 8);
  39215. var src3 = SIMD.Float32x4.load(src, 12);
  39216. // Transpose the source matrix. Sort of. Not a true transpose operation
  39217. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  39218. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  39219. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  39220. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  39221. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  39222. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  39223. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  39224. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  39225. // This is a true transposition, but it will lead to an incorrect result
  39226. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  39227. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  39228. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39229. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39230. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  39231. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  39232. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39233. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39234. // ----
  39235. tmp1 = SIMD.Float32x4.mul(row2, row3);
  39236. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39237. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  39238. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  39239. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39240. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  39241. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  39242. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  39243. // ----
  39244. tmp1 = SIMD.Float32x4.mul(row1, row2);
  39245. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39246. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  39247. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  39248. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39249. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  39250. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  39251. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  39252. // ----
  39253. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  39254. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39255. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  39256. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  39257. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  39258. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39259. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  39260. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  39261. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  39262. // ----
  39263. tmp1 = SIMD.Float32x4.mul(row0, row1);
  39264. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39265. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39266. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  39267. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39268. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39269. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  39270. // ----
  39271. tmp1 = SIMD.Float32x4.mul(row0, row3);
  39272. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39273. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  39274. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  39275. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39276. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  39277. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  39278. // ----
  39279. tmp1 = SIMD.Float32x4.mul(row0, row2);
  39280. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39281. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  39282. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  39283. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39284. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  39285. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  39286. // Compute determinant
  39287. var det = SIMD.Float32x4.mul(row0, minor0);
  39288. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  39289. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  39290. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  39291. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  39292. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  39293. // These shuffles aren't necessary if the faulty transposition is done
  39294. // up at the top of this function.
  39295. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  39296. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  39297. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  39298. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  39299. // Compute final values by multiplying with 1/det
  39300. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  39301. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  39302. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  39303. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  39304. return this;
  39305. };
  39306. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  39307. var out = result.m;
  39308. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  39309. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  39310. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  39311. // cc.kmVec3Subtract(f, pCenter, pEye);
  39312. var f = SIMD.Float32x4.sub(center, eye);
  39313. // cc.kmVec3Normalize(f, f);
  39314. var tmp = SIMD.Float32x4.mul(f, f);
  39315. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39316. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39317. // cc.kmVec3Assign(up, pUp);
  39318. // cc.kmVec3Normalize(up, up);
  39319. tmp = SIMD.Float32x4.mul(up, up);
  39320. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39321. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39322. // cc.kmVec3Cross(s, f, up);
  39323. 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)));
  39324. // cc.kmVec3Normalize(s, s);
  39325. tmp = SIMD.Float32x4.mul(s, s);
  39326. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39327. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39328. // cc.kmVec3Cross(u, s, f);
  39329. 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)));
  39330. // cc.kmVec3Normalize(s, s);
  39331. tmp = SIMD.Float32x4.mul(s, s);
  39332. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39333. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39334. var zero = SIMD.Float32x4.splat(0.0);
  39335. s = SIMD.Float32x4.neg(s);
  39336. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  39337. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  39338. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  39339. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  39340. 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);
  39341. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  39342. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  39343. 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)))));
  39344. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  39345. 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)))));
  39346. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  39347. 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)))));
  39348. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  39349. 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)))));
  39350. };
  39351. return SIMDMatrix;
  39352. }());
  39353. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  39354. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  39355. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  39356. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  39357. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  39358. var SIMDHelper = (function () {
  39359. function SIMDHelper() {
  39360. }
  39361. Object.defineProperty(SIMDHelper, "IsEnabled", {
  39362. get: function () {
  39363. return SIMDHelper._isEnabled;
  39364. },
  39365. enumerable: true,
  39366. configurable: true
  39367. });
  39368. SIMDHelper.DisableSIMD = function () {
  39369. // Replace functions
  39370. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  39371. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  39372. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  39373. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  39374. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  39375. SIMDHelper._isEnabled = false;
  39376. };
  39377. SIMDHelper.EnableSIMD = function () {
  39378. if (self.SIMD === undefined) {
  39379. return;
  39380. }
  39381. // check if polyfills needed
  39382. if (!self.Math.fround) {
  39383. self.Math.fround = (function (array) { return function (x) {
  39384. return array[0] = x, array[0];
  39385. }; })(new Float32Array(1));
  39386. }
  39387. if (!self.Math.imul) {
  39388. self.Math.imul = function (a, b) {
  39389. var ah = (a >>> 16) & 0xffff;
  39390. var al = a & 0xffff;
  39391. var bh = (b >>> 16) & 0xffff;
  39392. var bl = b & 0xffff;
  39393. // the shift by 0 fixes the sign on the high part
  39394. // the final |0 converts the unsigned value into a signed value
  39395. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  39396. };
  39397. }
  39398. // Replace functions
  39399. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  39400. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  39401. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  39402. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  39403. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  39404. SIMDHelper._isEnabled = true;
  39405. };
  39406. return SIMDHelper;
  39407. }());
  39408. SIMDHelper._isEnabled = false;
  39409. BABYLON.SIMDHelper = SIMDHelper;
  39410. })(BABYLON || (BABYLON = {}));
  39411. //# sourceMappingURL=babylon.math.SIMD.js.map
  39412. var BABYLON;
  39413. (function (BABYLON) {
  39414. /**
  39415. * This class describe a rectangle that were added to the map.
  39416. * You have access to its coordinates either in pixel or normalized (UV)
  39417. */
  39418. var PackedRect = (function () {
  39419. function PackedRect(root, parent, pos, size) {
  39420. this._pos = pos;
  39421. this._size = size;
  39422. this._root = root;
  39423. this._parent = parent;
  39424. this._contentSize = null;
  39425. this._bottomNode = null;
  39426. this._leftNode = null;
  39427. this._initialSize = null;
  39428. this._rightNode = null;
  39429. }
  39430. Object.defineProperty(PackedRect.prototype, "pos", {
  39431. /**
  39432. * @returns the position of this node into the map
  39433. */
  39434. get: function () {
  39435. return this._pos;
  39436. },
  39437. enumerable: true,
  39438. configurable: true
  39439. });
  39440. Object.defineProperty(PackedRect.prototype, "contentSize", {
  39441. /**
  39442. * @returns the size of the rectangle this node handles
  39443. */
  39444. get: function () {
  39445. return this._contentSize;
  39446. },
  39447. enumerable: true,
  39448. configurable: true
  39449. });
  39450. Object.defineProperty(PackedRect.prototype, "UVs", {
  39451. /**
  39452. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  39453. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  39454. */
  39455. get: function () {
  39456. return this.getUVsForCustomSize(this._root._size);
  39457. },
  39458. enumerable: true,
  39459. configurable: true
  39460. });
  39461. /**
  39462. * 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.
  39463. * This method will return the UVs for this part by given the custom size of what you really use
  39464. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  39465. */
  39466. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  39467. var mainWidth = this._root._size.width;
  39468. var mainHeight = this._root._size.height;
  39469. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  39470. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  39471. var uvs = new Array();
  39472. uvs.push(topLeft);
  39473. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  39474. uvs.push(rightBottom);
  39475. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  39476. return uvs;
  39477. };
  39478. /**
  39479. * Free this rectangle from the map.
  39480. * Call this method when you no longer need the rectangle to be in the map.
  39481. */
  39482. PackedRect.prototype.freeContent = function () {
  39483. if (!this.contentSize) {
  39484. return;
  39485. }
  39486. this._contentSize = null;
  39487. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  39488. this.attemptDefrag();
  39489. };
  39490. Object.defineProperty(PackedRect.prototype, "isUsed", {
  39491. get: function () {
  39492. return this._contentSize != null || this._leftNode != null;
  39493. },
  39494. enumerable: true,
  39495. configurable: true
  39496. });
  39497. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  39498. var node = this.findNode(contentSize);
  39499. // Not enough space...
  39500. if (!node) {
  39501. return null;
  39502. }
  39503. node.splitNode(contentSize);
  39504. return node;
  39505. };
  39506. PackedRect.prototype.findNode = function (size) {
  39507. var resNode = null;
  39508. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  39509. if (this.isUsed) {
  39510. if (this._leftNode) {
  39511. resNode = this._leftNode.findNode(size);
  39512. }
  39513. if (!resNode && this._rightNode) {
  39514. resNode = this._rightNode.findNode(size);
  39515. }
  39516. if (!resNode && this._bottomNode) {
  39517. resNode = this._bottomNode.findNode(size);
  39518. }
  39519. }
  39520. else if (this._initialSize) {
  39521. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  39522. resNode = this;
  39523. }
  39524. else {
  39525. return null;
  39526. }
  39527. }
  39528. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  39529. resNode = this;
  39530. }
  39531. return resNode;
  39532. };
  39533. PackedRect.prototype.splitNode = function (contentSize) {
  39534. // 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)
  39535. if (!this._contentSize && this._initialSize) {
  39536. this._contentSize = contentSize.clone();
  39537. 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));
  39538. return this._leftNode.splitNode(contentSize);
  39539. }
  39540. else {
  39541. this._contentSize = contentSize.clone();
  39542. this._initialSize = contentSize.clone();
  39543. if (contentSize.width !== this._size.width) {
  39544. 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));
  39545. }
  39546. if (contentSize.height !== this._size.height) {
  39547. 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));
  39548. }
  39549. return this;
  39550. }
  39551. };
  39552. PackedRect.prototype.attemptDefrag = function () {
  39553. if (!this.isUsed && this.isRecursiveFree) {
  39554. this.clearNode();
  39555. if (this._parent) {
  39556. this._parent.attemptDefrag();
  39557. }
  39558. }
  39559. };
  39560. PackedRect.prototype.clearNode = function () {
  39561. this._initialSize = null;
  39562. this._rightNode = null;
  39563. this._bottomNode = null;
  39564. };
  39565. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  39566. get: function () {
  39567. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  39568. },
  39569. enumerable: true,
  39570. configurable: true
  39571. });
  39572. PackedRect.prototype.evalFreeSize = function (size) {
  39573. var levelSize = 0;
  39574. if (!this.isUsed) {
  39575. if (this._initialSize) {
  39576. levelSize = this._initialSize.surface;
  39577. }
  39578. else {
  39579. levelSize = this._size.surface;
  39580. }
  39581. }
  39582. if (this._rightNode) {
  39583. levelSize += this._rightNode.evalFreeSize(0);
  39584. }
  39585. if (this._bottomNode) {
  39586. levelSize += this._bottomNode.evalFreeSize(0);
  39587. }
  39588. return levelSize + size;
  39589. };
  39590. return PackedRect;
  39591. }());
  39592. BABYLON.PackedRect = PackedRect;
  39593. /**
  39594. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  39595. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  39596. * 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.
  39597. */
  39598. var RectPackingMap = (function (_super) {
  39599. __extends(RectPackingMap, _super);
  39600. /**
  39601. * Create an instance of the object with a dimension using the given size
  39602. * @param size The dimension of the rectangle that will contain all the sub ones.
  39603. */
  39604. function RectPackingMap(size) {
  39605. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  39606. _this._root = _this;
  39607. return _this;
  39608. }
  39609. /**
  39610. * Add a rectangle, finding the best location to store it into the map
  39611. * @param size the dimension of the rectangle to store
  39612. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  39613. */
  39614. RectPackingMap.prototype.addRect = function (size) {
  39615. var node = this.findAndSplitNode(size);
  39616. return node;
  39617. };
  39618. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  39619. /**
  39620. * Return the current space free normalized between [0;1]
  39621. * @returns {}
  39622. */
  39623. get: function () {
  39624. var freeSize = 0;
  39625. freeSize = this.evalFreeSize(freeSize);
  39626. return freeSize / (this._size.width * this._size.height);
  39627. },
  39628. enumerable: true,
  39629. configurable: true
  39630. });
  39631. return RectPackingMap;
  39632. }(PackedRect));
  39633. BABYLON.RectPackingMap = RectPackingMap;
  39634. })(BABYLON || (BABYLON = {}));
  39635. //# sourceMappingURL=babylon.rectPackingMap.js.map
  39636. var BABYLON;
  39637. (function (BABYLON) {
  39638. var DynamicFloatArrayElementInfo = (function () {
  39639. function DynamicFloatArrayElementInfo() {
  39640. }
  39641. return DynamicFloatArrayElementInfo;
  39642. }());
  39643. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  39644. /**
  39645. * 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.
  39646. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  39647. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  39648. * 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.
  39649. * 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.
  39650. * 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".
  39651. */
  39652. var DynamicFloatArray = (function () {
  39653. /**
  39654. * Construct an instance of the dynamic float array
  39655. * @param stride size of one element in float (i.e. not bytes!)
  39656. * @param initialElementCount the number of available entries at construction
  39657. */
  39658. function DynamicFloatArray(stride, initialElementCount) {
  39659. this.compareValueOffset = null;
  39660. this.sortingAscending = true;
  39661. this._stride = stride;
  39662. this.buffer = new Float32Array(stride * initialElementCount);
  39663. this._lastUsed = 0;
  39664. this._firstFree = 0;
  39665. this._allEntries = new Array(initialElementCount);
  39666. this._freeEntries = new Array(initialElementCount);
  39667. for (var i = 0; i < initialElementCount; i++) {
  39668. var element = new DynamicFloatArrayElementInfo();
  39669. element.offset = i * stride;
  39670. this._allEntries[i] = element;
  39671. this._freeEntries[initialElementCount - i - 1] = element;
  39672. }
  39673. }
  39674. /**
  39675. * Allocate an element in the array.
  39676. * @return the element info instance that contains the offset into the main buffer of the element's location.
  39677. * Beware, this offset may change when you call pack()
  39678. */
  39679. DynamicFloatArray.prototype.allocElement = function () {
  39680. if (this._freeEntries.length === 0) {
  39681. this._growBuffer();
  39682. }
  39683. var el = this._freeEntries.pop();
  39684. this._lastUsed = Math.max(el.offset, this._lastUsed);
  39685. if (el.offset === this._firstFree) {
  39686. if (this._freeEntries.length > 0) {
  39687. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  39688. }
  39689. else {
  39690. this._firstFree += this._stride;
  39691. }
  39692. }
  39693. return el;
  39694. };
  39695. /**
  39696. * Free the element corresponding to the given element info
  39697. * @param elInfo the element that describe the allocated element
  39698. */
  39699. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  39700. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  39701. this._freeEntries.push(elInfo);
  39702. };
  39703. /**
  39704. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  39705. * 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().
  39706. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  39707. */
  39708. DynamicFloatArray.prototype.pack = function () {
  39709. // no free slot? no need to pack
  39710. if (this._freeEntries.length === 0) {
  39711. return this.buffer;
  39712. }
  39713. // If the buffer is already packed the last used will always be lower than the first free
  39714. // 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.
  39715. if (this._lastUsed < this._firstFree) {
  39716. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  39717. return elementsBuffer_1;
  39718. }
  39719. var s = this._stride;
  39720. // 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
  39721. var lastFree = new DynamicFloatArrayElementInfo();
  39722. lastFree.offset = this.totalElementCount * s;
  39723. this._freeEntries.push(lastFree);
  39724. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  39725. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39726. var firstFreeSlotOffset = sortedFree[0].offset;
  39727. var freeZoneSize = 1;
  39728. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  39729. var prevOffset = sortedFree[0].offset;
  39730. for (var i = 1; i < sortedFree.length; i++) {
  39731. // 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
  39732. if (firstFreeSlotOffset >= occupiedZoneSize) {
  39733. break;
  39734. }
  39735. var curFree = sortedFree[i];
  39736. var curOffset = curFree.offset;
  39737. // Compute the distance between this offset and the previous
  39738. var distance = curOffset - prevOffset;
  39739. // If the distance is the stride size, they are adjacent, it good, move to the next
  39740. if (distance === s) {
  39741. // Free zone is one element bigger
  39742. ++freeZoneSize;
  39743. // as we're about to iterate to the next, the cur becomes the previous...
  39744. prevOffset = curOffset;
  39745. continue;
  39746. }
  39747. // Distance is bigger, which means there's x element between the previous free and this one
  39748. var usedRange = (distance / s) - 1;
  39749. // Two cases the free zone is smaller than the data to move or bigger
  39750. // Copy what can fit in the free zone
  39751. var curMoveOffset = curOffset - s;
  39752. var copyCount = Math.min(freeZoneSize, usedRange);
  39753. for (var j = 0; j < copyCount; j++) {
  39754. var freeI = firstFreeSlotOffset / s;
  39755. var curI = curMoveOffset / s;
  39756. var moveEl = sortedAll[curI];
  39757. this._moveElement(moveEl, firstFreeSlotOffset);
  39758. var replacedEl = sortedAll[freeI];
  39759. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  39760. replacedEl.offset = curMoveOffset;
  39761. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  39762. sortedAll[freeI] = moveEl;
  39763. sortedAll[curI] = replacedEl;
  39764. curMoveOffset -= s;
  39765. firstFreeSlotOffset += s;
  39766. }
  39767. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  39768. if (freeZoneSize <= usedRange) {
  39769. firstFreeSlotOffset = curMoveOffset + s;
  39770. freeZoneSize = 1 + copyCount;
  39771. }
  39772. else {
  39773. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  39774. }
  39775. // as we're about to iterate to the next, the cur becomes the previous...
  39776. prevOffset = curOffset;
  39777. }
  39778. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  39779. this._lastUsed = firstFreeSlotOffset - s;
  39780. this._firstFree = firstFreeSlotOffset;
  39781. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  39782. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  39783. this._allEntries = sortedAll;
  39784. return elementsBuffer;
  39785. };
  39786. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  39787. for (var i = 0; i < this._stride; i++) {
  39788. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  39789. }
  39790. element.offset = destOffset;
  39791. };
  39792. DynamicFloatArray.prototype._growBuffer = function () {
  39793. // Allocate the new buffer with 50% more entries, copy the content of the current one
  39794. var newElCount = Math.floor(this.totalElementCount * 1.5);
  39795. var newBuffer = new Float32Array(newElCount * this._stride);
  39796. newBuffer.set(this.buffer);
  39797. var curCount = this.totalElementCount;
  39798. var addedCount = newElCount - this.totalElementCount;
  39799. for (var i = 0; i < addedCount; i++) {
  39800. var element = new DynamicFloatArrayElementInfo();
  39801. element.offset = (curCount + i) * this.stride;
  39802. this._allEntries.push(element);
  39803. this._freeEntries[addedCount - i - 1] = element;
  39804. }
  39805. this._firstFree = curCount * this.stride;
  39806. this.buffer = newBuffer;
  39807. };
  39808. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  39809. /**
  39810. * Get the total count of entries that can fit in the current buffer
  39811. * @returns the elements count
  39812. */
  39813. get: function () {
  39814. return this._allEntries.length;
  39815. },
  39816. enumerable: true,
  39817. configurable: true
  39818. });
  39819. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  39820. /**
  39821. * Get the count of free entries that can still be allocated without resizing the buffer
  39822. * @returns the free elements count
  39823. */
  39824. get: function () {
  39825. return this._freeEntries.length;
  39826. },
  39827. enumerable: true,
  39828. configurable: true
  39829. });
  39830. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  39831. /**
  39832. * Get the count of allocated elements
  39833. * @returns the allocated elements count
  39834. */
  39835. get: function () {
  39836. return this._allEntries.length - this._freeEntries.length;
  39837. },
  39838. enumerable: true,
  39839. configurable: true
  39840. });
  39841. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  39842. /**
  39843. * Return the size of one element in float
  39844. * @returns the size in float
  39845. */
  39846. get: function () {
  39847. return this._stride;
  39848. },
  39849. enumerable: true,
  39850. configurable: true
  39851. });
  39852. DynamicFloatArray.prototype.sort = function () {
  39853. var _this = this;
  39854. if (!this.compareValueOffset) {
  39855. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  39856. }
  39857. var count = this.usedElementCount;
  39858. // Do we have to (re)create the sort table?
  39859. if (!this._sortTable || this._sortTable.length < count) {
  39860. // 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...
  39861. var newCount = Math.min(this.totalElementCount, count * 2);
  39862. this._sortTable = new Array(newCount);
  39863. }
  39864. if (!this._sortedTable || this._sortedTable.length !== count) {
  39865. this._sortedTable = new Array(count);
  39866. }
  39867. // Because, you know...
  39868. this.pack();
  39869. //let stride = this.stride;
  39870. //for (let i = 0; i < count; i++) {
  39871. // let si = this._sortTable[i];
  39872. // if (!si) {
  39873. // si = new SortInfo();
  39874. // this._sortTable[i] = si;
  39875. // }
  39876. // si.entry = this._allEntries[i];
  39877. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  39878. // si.swapedOffset = null;
  39879. // this._sortedTable[i] = si;
  39880. //}
  39881. var curOffset = 0;
  39882. var stride = this.stride;
  39883. for (var i = 0; i < count; i++, curOffset += stride) {
  39884. var si = this._sortTable[i];
  39885. if (!si) {
  39886. si = new SortInfo();
  39887. this._sortTable[i] = si;
  39888. }
  39889. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  39890. si.offset = curOffset;
  39891. si.swapedOffset = null;
  39892. this._sortedTable[i] = si;
  39893. }
  39894. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  39895. if (this.sortingAscending) {
  39896. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  39897. }
  39898. else {
  39899. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  39900. }
  39901. var swapElements = function (src, dst) {
  39902. for (var i = 0; i < stride; i++) {
  39903. var tps = _this.buffer[dst + i];
  39904. _this.buffer[dst + i] = _this.buffer[src + i];
  39905. _this.buffer[src + i] = tps;
  39906. }
  39907. };
  39908. // 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:
  39909. // 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),
  39910. // and I still want something with a good algorithm complexity.
  39911. // 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,
  39912. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  39913. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  39914. // 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
  39915. // until we find a SortInfo object without a swapedOffset which means we got the right location
  39916. // 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
  39917. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  39918. for (var i = 0; i < count; i++) {
  39919. // Get the element to move
  39920. var sourceSI = this._sortedTable[i];
  39921. var destSI = this._sortTable[i];
  39922. var sourceOff = sourceSI.offset;
  39923. // If the source changed location, find the new one
  39924. if (sourceSI.swapedOffset) {
  39925. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  39926. var curSI = sourceSI;
  39927. while (curSI.swapedOffset) {
  39928. curSI = this._sortTable[curSI.swapedOffset / stride];
  39929. }
  39930. // Finally get the right location
  39931. sourceOff = curSI.offset;
  39932. }
  39933. // Tag the element being replaced with its new location
  39934. destSI.swapedOffset = sourceOff;
  39935. // Swap elements (only if needed)
  39936. if (sourceOff !== destSI.offset) {
  39937. swapElements(sourceOff, destSI.offset);
  39938. }
  39939. // Update the offset in the corresponding DFAE
  39940. //sourceSI.entry.offset = destSI.entry.offset;
  39941. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  39942. }
  39943. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39944. return true;
  39945. };
  39946. return DynamicFloatArray;
  39947. }());
  39948. BABYLON.DynamicFloatArray = DynamicFloatArray;
  39949. var SortInfo = (function () {
  39950. function SortInfo() {
  39951. this.compareData = this.offset = this.swapedOffset = null;
  39952. }
  39953. return SortInfo;
  39954. }());
  39955. })(BABYLON || (BABYLON = {}));
  39956. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  39957. var BABYLON;
  39958. (function (BABYLON) {
  39959. /**
  39960. * This class given information about a given character.
  39961. */
  39962. var CharInfo = (function () {
  39963. function CharInfo() {
  39964. }
  39965. return CharInfo;
  39966. }());
  39967. BABYLON.CharInfo = CharInfo;
  39968. var FontTexture = (function (_super) {
  39969. __extends(FontTexture, _super);
  39970. /**
  39971. * Create a new instance of the FontTexture class
  39972. * @param name the name of the texture
  39973. * @param font the font to use, use the W3C CSS notation
  39974. * @param scene the scene that owns the texture
  39975. * @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
  39976. * @param samplingMode the texture sampling mode
  39977. * @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.
  39978. */
  39979. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  39980. if (maxCharCount === void 0) { maxCharCount = 200; }
  39981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39982. if (superSample === void 0) { superSample = false; }
  39983. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39984. var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
  39985. _this._charInfos = {};
  39986. _this._curCharCount = 0;
  39987. _this._lastUpdateCharCount = -1;
  39988. _this._usedCounter = 1;
  39989. _this.name = name;
  39990. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39991. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39992. _this._sdfScale = 8;
  39993. _this._signedDistanceField = signedDistanceField;
  39994. _this._superSample = false;
  39995. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  39996. if (superSample || signedDistanceField) {
  39997. var sfont = _this.getSuperSampleFont(font);
  39998. if (sfont) {
  39999. _this._superSample = true;
  40000. font = sfont;
  40001. }
  40002. }
  40003. // First canvas creation to determine the size of the texture to create
  40004. _this._canvas = document.createElement("canvas");
  40005. _this._context = _this._canvas.getContext("2d");
  40006. _this._context.font = font;
  40007. _this._context.fillStyle = "white";
  40008. _this._context.textBaseline = "top";
  40009. _this._cachedFontId = null;
  40010. var res = _this.getFontHeight(font);
  40011. _this._lineHeightSuper = res.height + 4;
  40012. _this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
  40013. _this._offset = res.offset - 1;
  40014. _this._xMargin = 1 + Math.ceil(_this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  40015. _this._yMargin = _this._xMargin;
  40016. var maxCharWidth = _this._context.measureText("W").width;
  40017. _this._spaceWidthSuper = _this._context.measureText(" ").width;
  40018. _this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
  40019. // This is an approximate size, but should always be able to fit at least the maxCharCount
  40020. var totalEstSurface = (_this._lineHeightSuper + _this._yMargin) * (maxCharWidth + _this._xMargin) * maxCharCount;
  40021. var edge = Math.sqrt(totalEstSurface);
  40022. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  40023. // Create the texture that will store the font characters
  40024. _this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  40025. var textureSize = _this.getSize();
  40026. _this.hasAlpha = _this._signedDistanceField === false;
  40027. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  40028. _this._canvas = document.createElement("canvas");
  40029. _this._canvas.width = textureSize.width;
  40030. _this._canvas.height = textureSize.height;
  40031. _this._context = _this._canvas.getContext("2d");
  40032. _this._context.textBaseline = "top";
  40033. _this._context.font = font;
  40034. _this._context.fillStyle = "white";
  40035. _this._context.imageSmoothingEnabled = false;
  40036. _this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  40037. // 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
  40038. // 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)
  40039. // So you can see this context as an intermediate one, because it is.
  40040. if (_this._signedDistanceField) {
  40041. var sdfC = document.createElement("canvas");
  40042. var s = _this._sdfScale;
  40043. sdfC.width = maxCharWidth * s;
  40044. sdfC.height = _this._lineHeightSuper * s;
  40045. var sdfCtx = sdfC.getContext("2d");
  40046. sdfCtx.scale(s, s);
  40047. sdfCtx.textBaseline = "top";
  40048. sdfCtx.font = font;
  40049. sdfCtx.fillStyle = "white";
  40050. sdfCtx.imageSmoothingEnabled = false;
  40051. _this._sdfCanvas = sdfC;
  40052. _this._sdfContext = sdfCtx;
  40053. }
  40054. _this._currentFreePosition = BABYLON.Vector2.Zero();
  40055. // Add the basic ASCII based characters
  40056. for (var i = 0x20; i < 0x7F; i++) {
  40057. var c = String.fromCharCode(i);
  40058. _this.getChar(c);
  40059. }
  40060. _this.update();
  40061. return _this;
  40062. }
  40063. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  40064. get: function () {
  40065. return this._superSample;
  40066. },
  40067. enumerable: true,
  40068. configurable: true
  40069. });
  40070. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  40071. get: function () {
  40072. return this._signedDistanceField;
  40073. },
  40074. enumerable: true,
  40075. configurable: true
  40076. });
  40077. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  40078. get: function () {
  40079. return this._spaceWidth;
  40080. },
  40081. enumerable: true,
  40082. configurable: true
  40083. });
  40084. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  40085. get: function () {
  40086. return this._lineHeight;
  40087. },
  40088. enumerable: true,
  40089. configurable: true
  40090. });
  40091. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40092. if (supersample === void 0) { supersample = false; }
  40093. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40094. var s = scene;
  40095. if (!s.__fontTextureCache__) {
  40096. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  40097. }
  40098. var dic = s.__fontTextureCache__;
  40099. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40100. var ft = dic.get(lfn);
  40101. if (ft) {
  40102. ++ft._usedCounter;
  40103. return ft;
  40104. }
  40105. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  40106. ft._cachedFontId = lfn;
  40107. dic.add(lfn, ft);
  40108. return ft;
  40109. };
  40110. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40111. if (supersample === void 0) { supersample = false; }
  40112. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40113. var s = scene;
  40114. var dic = s.__fontTextureCache__;
  40115. if (!dic) {
  40116. return;
  40117. }
  40118. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40119. var font = dic.get(lfn);
  40120. if (--font._usedCounter === 0) {
  40121. dic.remove(lfn);
  40122. font.dispose();
  40123. }
  40124. };
  40125. /**
  40126. * Make sure the given char is present in the font map.
  40127. * @param char the character to get or add
  40128. * @return the CharInfo instance corresponding to the given character
  40129. */
  40130. FontTexture.prototype.getChar = function (char) {
  40131. if (char.length !== 1) {
  40132. return null;
  40133. }
  40134. var info = this._charInfos[char];
  40135. if (info) {
  40136. return info;
  40137. }
  40138. info = new CharInfo();
  40139. var measure = this._context.measureText(char);
  40140. var textureSize = this.getSize();
  40141. // we reached the end of the current line?
  40142. var width = Math.round(measure.width);
  40143. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  40144. this._currentFreePosition.x = 0;
  40145. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  40146. // No more room?
  40147. if (this._currentFreePosition.y > textureSize.height) {
  40148. return this.getChar("!");
  40149. }
  40150. }
  40151. // 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)
  40152. if (this._signedDistanceField) {
  40153. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  40154. this._sdfContext.fillText(char, 0, -this._offset);
  40155. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  40156. var res = this._computeSDFChar(data);
  40157. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  40158. }
  40159. else {
  40160. // Draw the character in the HTML canvas
  40161. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  40162. }
  40163. // Fill the CharInfo object
  40164. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  40165. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  40166. if (this._signedDistanceField) {
  40167. var off = 1 / textureSize.width;
  40168. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  40169. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  40170. }
  40171. info.charWidth = this._superSample ? (width / 2) : width;
  40172. // Add the info structure
  40173. this._charInfos[char] = info;
  40174. this._curCharCount++;
  40175. // Set the next position
  40176. this._currentFreePosition.x += width + this._xMargin;
  40177. return info;
  40178. };
  40179. FontTexture.prototype._computeSDFChar = function (source) {
  40180. var scl = this._sdfScale;
  40181. var sw = source.width;
  40182. var sh = source.height;
  40183. var dw = sw / scl;
  40184. var dh = sh / scl;
  40185. var roffx = 0;
  40186. var roffy = 0;
  40187. // We shouldn't look beyond half of the biggest between width and height
  40188. var radius = scl;
  40189. var br = radius - 1;
  40190. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  40191. var sx = dx * scl;
  40192. var sy = dy * scl;
  40193. // Looking out of the area? return true to make the test going on
  40194. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  40195. return true;
  40196. }
  40197. // Get the pixel we want
  40198. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  40199. var res = (val > 0) === lookVis;
  40200. if (!res) {
  40201. roffx = offX;
  40202. roffy = offY;
  40203. }
  40204. return res;
  40205. };
  40206. var lookupArea = function (dx, dy, lookVis) {
  40207. // 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
  40208. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  40209. lookupSrc(dx, dy, 0, -br, lookVis) &&
  40210. lookupSrc(dx, dy, -br, 0, lookVis) &&
  40211. lookupSrc(dx, dy, br, 0, lookVis)) {
  40212. return 0;
  40213. }
  40214. for (var i = 1; i <= radius; i++) {
  40215. // Quick test N, S, W, E
  40216. 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)) {
  40217. return i * i; // Squared Distance is simple to compute in this case
  40218. }
  40219. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  40220. for (var j = 1; j <= i; j++) {
  40221. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  40222. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  40223. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  40224. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  40225. // We found the nearest texel having and opposite state, store the squared length
  40226. var res_1 = (i * i) + (j * j);
  40227. var count = 1;
  40228. // 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
  40229. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  40230. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  40231. ++count;
  40232. }
  40233. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  40234. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  40235. ++count;
  40236. }
  40237. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  40238. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  40239. ++count;
  40240. }
  40241. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  40242. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  40243. ++count;
  40244. }
  40245. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  40246. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  40247. ++count;
  40248. }
  40249. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  40250. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  40251. ++count;
  40252. }
  40253. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  40254. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  40255. ++count;
  40256. }
  40257. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  40258. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  40259. ++count;
  40260. }
  40261. // Compute the average based on the accumulated distance
  40262. return res_1 / count;
  40263. }
  40264. }
  40265. }
  40266. return 0;
  40267. };
  40268. var tmp = new Array(dw * dh);
  40269. for (var y = 0; y < dh; y++) {
  40270. for (var x = 0; x < dw; x++) {
  40271. var curState = lookupSrc(x, y, 0, 0, true);
  40272. var d = lookupArea(x, y, curState);
  40273. if (d === 0) {
  40274. d = radius * radius * 2;
  40275. }
  40276. tmp[(y * dw) + x] = curState ? d : -d;
  40277. }
  40278. }
  40279. var res = this._context.createImageData(dw, dh);
  40280. var size = dw * dh;
  40281. for (var j = 0; j < size; j++) {
  40282. var d = tmp[j];
  40283. var sign = (d < 0) ? -1 : 1;
  40284. d = Math.sqrt(Math.abs(d)) * sign;
  40285. d *= 127.5 / radius;
  40286. d += 127.5;
  40287. if (d < 0) {
  40288. d = 0;
  40289. }
  40290. else if (d > 255) {
  40291. d = 255;
  40292. }
  40293. d += 0.5;
  40294. res.data[j * 4 + 0] = d;
  40295. res.data[j * 4 + 1] = d;
  40296. res.data[j * 4 + 2] = d;
  40297. res.data[j * 4 + 3] = 255;
  40298. }
  40299. return res;
  40300. };
  40301. FontTexture.prototype.measureText = function (text, tabulationSize) {
  40302. if (tabulationSize === void 0) { tabulationSize = 4; }
  40303. var maxWidth = 0;
  40304. var curWidth = 0;
  40305. var lineCount = 1;
  40306. var charxpos = 0;
  40307. // Parse each char of the string
  40308. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  40309. var char = text_1[_i];
  40310. // Next line feed?
  40311. if (char === "\n") {
  40312. maxWidth = Math.max(maxWidth, curWidth);
  40313. charxpos = 0;
  40314. curWidth = 0;
  40315. ++lineCount;
  40316. continue;
  40317. }
  40318. // Tabulation ?
  40319. if (char === "\t") {
  40320. var nextPos = charxpos + tabulationSize;
  40321. nextPos = nextPos - (nextPos % tabulationSize);
  40322. curWidth += (nextPos - charxpos) * this.spaceWidth;
  40323. charxpos = nextPos;
  40324. continue;
  40325. }
  40326. if (char < " ") {
  40327. continue;
  40328. }
  40329. curWidth += this.getChar(char).charWidth;
  40330. ++charxpos;
  40331. }
  40332. maxWidth = Math.max(maxWidth, curWidth);
  40333. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  40334. };
  40335. FontTexture.prototype.getSuperSampleFont = function (font) {
  40336. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  40337. 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*$/;
  40338. var res = font.toLocaleLowerCase().match(regex);
  40339. if (res == null) {
  40340. return null;
  40341. }
  40342. var size = parseInt(res[4]);
  40343. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  40344. var newFont = "";
  40345. for (var j = 1; j < res.length; j++) {
  40346. if (res[j] != null) {
  40347. newFont += res[j] + " ";
  40348. }
  40349. }
  40350. return newFont;
  40351. };
  40352. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  40353. FontTexture.prototype.getFontHeight = function (font) {
  40354. var fontDraw = document.createElement("canvas");
  40355. var ctx = fontDraw.getContext('2d');
  40356. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  40357. ctx.textBaseline = 'top';
  40358. ctx.fillStyle = 'white';
  40359. ctx.font = font;
  40360. ctx.fillText('jH|', 0, 0);
  40361. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  40362. var start = -1;
  40363. var end = -1;
  40364. for (var row = 0; row < fontDraw.height; row++) {
  40365. for (var column = 0; column < fontDraw.width; column++) {
  40366. var index = (row * fontDraw.width + column) * 4;
  40367. if (pixels[index] === 0) {
  40368. if (column === fontDraw.width - 1 && start !== -1) {
  40369. end = row;
  40370. row = fontDraw.height;
  40371. break;
  40372. }
  40373. continue;
  40374. }
  40375. else {
  40376. if (start === -1) {
  40377. start = row;
  40378. }
  40379. break;
  40380. }
  40381. }
  40382. }
  40383. return { height: (end - start) + 1, offset: start - 1 };
  40384. };
  40385. Object.defineProperty(FontTexture.prototype, "canRescale", {
  40386. get: function () {
  40387. return false;
  40388. },
  40389. enumerable: true,
  40390. configurable: true
  40391. });
  40392. FontTexture.prototype.getContext = function () {
  40393. return this._context;
  40394. };
  40395. /**
  40396. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  40397. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  40398. */
  40399. FontTexture.prototype.update = function () {
  40400. // Update only if there's new char added since the previous update
  40401. if (this._lastUpdateCharCount < this._curCharCount) {
  40402. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  40403. this._lastUpdateCharCount = this._curCharCount;
  40404. }
  40405. };
  40406. // cloning should be prohibited, there's no point to duplicate this texture at all
  40407. FontTexture.prototype.clone = function () {
  40408. return null;
  40409. };
  40410. /**
  40411. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  40412. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  40413. */
  40414. FontTexture.prototype.incCachedFontTextureCounter = function () {
  40415. ++this._usedCounter;
  40416. };
  40417. /**
  40418. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  40419. */
  40420. FontTexture.prototype.decCachedFontTextureCounter = function () {
  40421. var s = this.getScene();
  40422. var dic = s.__fontTextureCache__;
  40423. if (!dic) {
  40424. return;
  40425. }
  40426. if (--this._usedCounter === 0) {
  40427. dic.remove(this._cachedFontId);
  40428. this.dispose();
  40429. }
  40430. };
  40431. return FontTexture;
  40432. }(BABYLON.Texture));
  40433. BABYLON.FontTexture = FontTexture;
  40434. })(BABYLON || (BABYLON = {}));
  40435. //# sourceMappingURL=babylon.fontTexture.js.map
  40436. var BABYLON;
  40437. (function (BABYLON) {
  40438. var MapTexture = (function (_super) {
  40439. __extends(MapTexture, _super);
  40440. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40442. if (useMipMap === void 0) { useMipMap = false; }
  40443. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  40444. _this.name = name;
  40445. _this._size = size;
  40446. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40447. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40448. // Create the rectPackMap that will allocate portion of the texture
  40449. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40450. // Create the texture that will store the content
  40451. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40452. return _this;
  40453. }
  40454. /**
  40455. * Allocate a rectangle of a given size in the texture map
  40456. * @param size the size of the rectangle to allocation
  40457. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40458. */
  40459. MapTexture.prototype.allocateRect = function (size) {
  40460. return this._rectPackingMap.addRect(size);
  40461. };
  40462. /**
  40463. * Free a given rectangle from the texture map
  40464. * @param rectInfo the instance corresponding to the rect to free.
  40465. */
  40466. MapTexture.prototype.freeRect = function (rectInfo) {
  40467. if (rectInfo) {
  40468. rectInfo.freeContent();
  40469. }
  40470. };
  40471. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40472. /**
  40473. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40474. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40475. * @returns {}
  40476. */
  40477. get: function () {
  40478. return this._rectPackingMap.freeSpace;
  40479. },
  40480. enumerable: true,
  40481. configurable: true
  40482. });
  40483. /**
  40484. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40485. * 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.
  40486. * Don't forget to call unbindTexture when you're done rendering
  40487. * @param rect the zone to render to
  40488. * @param clear true to clear the portion's color/depth data
  40489. */
  40490. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40491. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40492. };
  40493. /**
  40494. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40495. * 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.
  40496. * Don't forget to call unbindTexture when you're done rendering
  40497. * @param pos the position into the texture
  40498. * @param size the portion to fit the clip space to
  40499. * @param clear true to clear the portion's color/depth data
  40500. */
  40501. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40502. var engine = this.getScene().getEngine();
  40503. engine.bindFramebuffer(this._texture);
  40504. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40505. if (clear) {
  40506. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40507. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40508. }
  40509. };
  40510. /**
  40511. * Unbind the texture map from the rendering engine.
  40512. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40513. * @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.
  40514. */
  40515. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40516. // Dump ?
  40517. if (dumpForDebug) {
  40518. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40519. }
  40520. var engine = this.getScene().getEngine();
  40521. if (this._replacedViewport) {
  40522. engine.setViewport(this._replacedViewport);
  40523. this._replacedViewport = null;
  40524. }
  40525. engine.unBindFramebuffer(this._texture);
  40526. };
  40527. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40528. get: function () {
  40529. return false;
  40530. },
  40531. enumerable: true,
  40532. configurable: true
  40533. });
  40534. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40535. // Anyway, there's not much point to use this method for this kind of texture I guess
  40536. MapTexture.prototype.clone = function () {
  40537. return null;
  40538. };
  40539. return MapTexture;
  40540. }(BABYLON.Texture));
  40541. BABYLON.MapTexture = MapTexture;
  40542. })(BABYLON || (BABYLON = {}));
  40543. //# sourceMappingURL=babylon.mapTexture.js.map
  40544. var BABYLON;
  40545. (function (BABYLON) {
  40546. var ShaderMaterial = (function (_super) {
  40547. __extends(ShaderMaterial, _super);
  40548. function ShaderMaterial(name, scene, shaderPath, options) {
  40549. var _this = _super.call(this, name, scene) || this;
  40550. _this._textures = {};
  40551. _this._textureArrays = {};
  40552. _this._floats = {};
  40553. _this._floatsArrays = {};
  40554. _this._colors3 = {};
  40555. _this._colors4 = {};
  40556. _this._vectors2 = {};
  40557. _this._vectors3 = {};
  40558. _this._vectors4 = {};
  40559. _this._matrices = {};
  40560. _this._matrices3x3 = {};
  40561. _this._matrices2x2 = {};
  40562. _this._vectors3Arrays = {};
  40563. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40564. _this._shaderPath = shaderPath;
  40565. options.needAlphaBlending = options.needAlphaBlending || false;
  40566. options.needAlphaTesting = options.needAlphaTesting || false;
  40567. options.attributes = options.attributes || ["position", "normal", "uv"];
  40568. options.uniforms = options.uniforms || ["worldViewProjection"];
  40569. options.samplers = options.samplers || [];
  40570. options.defines = options.defines || [];
  40571. _this._options = options;
  40572. return _this;
  40573. }
  40574. ShaderMaterial.prototype.getClassName = function () {
  40575. return "ShaderMaterial";
  40576. };
  40577. ShaderMaterial.prototype.needAlphaBlending = function () {
  40578. return this._options.needAlphaBlending;
  40579. };
  40580. ShaderMaterial.prototype.needAlphaTesting = function () {
  40581. return this._options.needAlphaTesting;
  40582. };
  40583. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40584. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40585. this._options.uniforms.push(uniformName);
  40586. }
  40587. };
  40588. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40589. if (this._options.samplers.indexOf(name) === -1) {
  40590. this._options.samplers.push(name);
  40591. }
  40592. this._textures[name] = texture;
  40593. return this;
  40594. };
  40595. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40596. if (this._options.samplers.indexOf(name) === -1) {
  40597. this._options.samplers.push(name);
  40598. }
  40599. this._checkUniform(name);
  40600. this._textureArrays[name] = textures;
  40601. return this;
  40602. };
  40603. ShaderMaterial.prototype.setFloat = function (name, value) {
  40604. this._checkUniform(name);
  40605. this._floats[name] = value;
  40606. return this;
  40607. };
  40608. ShaderMaterial.prototype.setFloats = function (name, value) {
  40609. this._checkUniform(name);
  40610. this._floatsArrays[name] = value;
  40611. return this;
  40612. };
  40613. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40614. this._checkUniform(name);
  40615. this._colors3[name] = value;
  40616. return this;
  40617. };
  40618. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40619. this._checkUniform(name);
  40620. this._colors4[name] = value;
  40621. return this;
  40622. };
  40623. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40624. this._checkUniform(name);
  40625. this._vectors2[name] = value;
  40626. return this;
  40627. };
  40628. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40629. this._checkUniform(name);
  40630. this._vectors3[name] = value;
  40631. return this;
  40632. };
  40633. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40634. this._checkUniform(name);
  40635. this._vectors4[name] = value;
  40636. return this;
  40637. };
  40638. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40639. this._checkUniform(name);
  40640. this._matrices[name] = value;
  40641. return this;
  40642. };
  40643. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40644. this._checkUniform(name);
  40645. this._matrices3x3[name] = value;
  40646. return this;
  40647. };
  40648. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40649. this._checkUniform(name);
  40650. this._matrices2x2[name] = value;
  40651. return this;
  40652. };
  40653. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40654. this._checkUniform(name);
  40655. this._vectors3Arrays[name] = value;
  40656. return this;
  40657. };
  40658. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40659. if (!mesh) {
  40660. return true;
  40661. }
  40662. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40663. return false;
  40664. }
  40665. return false;
  40666. };
  40667. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40668. var scene = this.getScene();
  40669. var engine = scene.getEngine();
  40670. if (!this.checkReadyOnEveryCall) {
  40671. if (this._renderId === scene.getRenderId()) {
  40672. if (this._checkCache(scene, mesh, useInstances)) {
  40673. return true;
  40674. }
  40675. }
  40676. }
  40677. // Instances
  40678. var defines = [];
  40679. var fallbacks = new BABYLON.EffectFallbacks();
  40680. if (useInstances) {
  40681. defines.push("#define INSTANCES");
  40682. }
  40683. for (var index = 0; index < this._options.defines.length; index++) {
  40684. defines.push(this._options.defines[index]);
  40685. }
  40686. // Bones
  40687. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40688. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40689. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40690. fallbacks.addCPUSkinningFallback(0, mesh);
  40691. }
  40692. // Alpha test
  40693. if (engine.getAlphaTesting()) {
  40694. defines.push("#define ALPHATEST");
  40695. }
  40696. var previousEffect = this._effect;
  40697. var join = defines.join("\n");
  40698. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  40699. if (!this._effect.isReady()) {
  40700. return false;
  40701. }
  40702. if (previousEffect !== this._effect) {
  40703. scene.resetCachedMaterial();
  40704. }
  40705. this._renderId = scene.getRenderId();
  40706. return true;
  40707. };
  40708. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40709. var scene = this.getScene();
  40710. if (this._options.uniforms.indexOf("world") !== -1) {
  40711. this._effect.setMatrix("world", world);
  40712. }
  40713. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40714. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40715. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40716. }
  40717. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40718. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40719. }
  40720. };
  40721. ShaderMaterial.prototype.bind = function (world, mesh) {
  40722. // Std values
  40723. this.bindOnlyWorldMatrix(world);
  40724. if (this.getScene().getCachedMaterial() !== this) {
  40725. if (this._options.uniforms.indexOf("view") !== -1) {
  40726. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40727. }
  40728. if (this._options.uniforms.indexOf("projection") !== -1) {
  40729. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40730. }
  40731. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40732. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40733. }
  40734. // Bones
  40735. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40736. var name;
  40737. // Texture
  40738. for (name in this._textures) {
  40739. this._effect.setTexture(name, this._textures[name]);
  40740. }
  40741. // Texture arrays
  40742. for (name in this._textureArrays) {
  40743. this._effect.setTextureArray(name, this._textureArrays[name]);
  40744. }
  40745. // Float
  40746. for (name in this._floats) {
  40747. this._effect.setFloat(name, this._floats[name]);
  40748. }
  40749. // Float s
  40750. for (name in this._floatsArrays) {
  40751. this._effect.setArray(name, this._floatsArrays[name]);
  40752. }
  40753. // Color3
  40754. for (name in this._colors3) {
  40755. this._effect.setColor3(name, this._colors3[name]);
  40756. }
  40757. // Color4
  40758. for (name in this._colors4) {
  40759. var color = this._colors4[name];
  40760. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40761. }
  40762. // Vector2
  40763. for (name in this._vectors2) {
  40764. this._effect.setVector2(name, this._vectors2[name]);
  40765. }
  40766. // Vector3
  40767. for (name in this._vectors3) {
  40768. this._effect.setVector3(name, this._vectors3[name]);
  40769. }
  40770. // Vector4
  40771. for (name in this._vectors4) {
  40772. this._effect.setVector4(name, this._vectors4[name]);
  40773. }
  40774. // Matrix
  40775. for (name in this._matrices) {
  40776. this._effect.setMatrix(name, this._matrices[name]);
  40777. }
  40778. // Matrix 3x3
  40779. for (name in this._matrices3x3) {
  40780. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40781. }
  40782. // Matrix 2x2
  40783. for (name in this._matrices2x2) {
  40784. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40785. }
  40786. // Vector3Array
  40787. for (name in this._vectors3Arrays) {
  40788. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40789. }
  40790. }
  40791. _super.prototype.bind.call(this, world, mesh);
  40792. };
  40793. ShaderMaterial.prototype.clone = function (name) {
  40794. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40795. return newShaderMaterial;
  40796. };
  40797. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40798. if (forceDisposeTextures) {
  40799. var name;
  40800. for (name in this._textures) {
  40801. this._textures[name].dispose();
  40802. }
  40803. for (name in this._textureArrays) {
  40804. var array = this._textureArrays[name];
  40805. for (var index = 0; index < array.length; index++) {
  40806. array[index].dispose();
  40807. }
  40808. }
  40809. }
  40810. this._textures = {};
  40811. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40812. };
  40813. ShaderMaterial.prototype.serialize = function () {
  40814. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40815. serializationObject.customType = "BABYLON.ShaderMaterial";
  40816. serializationObject.options = this._options;
  40817. serializationObject.shaderPath = this._shaderPath;
  40818. var name;
  40819. // Texture
  40820. serializationObject.textures = {};
  40821. for (name in this._textures) {
  40822. serializationObject.textures[name] = this._textures[name].serialize();
  40823. }
  40824. // Texture arrays
  40825. serializationObject.textureArrays = {};
  40826. for (name in this._textureArrays) {
  40827. serializationObject.textureArrays[name] = [];
  40828. var array = this._textureArrays[name];
  40829. for (var index = 0; index < array.length; index++) {
  40830. serializationObject.textureArrays[name].push(array[index].serialize());
  40831. }
  40832. }
  40833. // Float
  40834. serializationObject.floats = {};
  40835. for (name in this._floats) {
  40836. serializationObject.floats[name] = this._floats[name];
  40837. }
  40838. // Float s
  40839. serializationObject.floatArrays = {};
  40840. for (name in this._floatsArrays) {
  40841. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40842. }
  40843. // Color3
  40844. serializationObject.colors3 = {};
  40845. for (name in this._colors3) {
  40846. serializationObject.colors3[name] = this._colors3[name].asArray();
  40847. }
  40848. // Color4
  40849. serializationObject.colors4 = {};
  40850. for (name in this._colors4) {
  40851. serializationObject.colors4[name] = this._colors4[name].asArray();
  40852. }
  40853. // Vector2
  40854. serializationObject.vectors2 = {};
  40855. for (name in this._vectors2) {
  40856. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40857. }
  40858. // Vector3
  40859. serializationObject.vectors3 = {};
  40860. for (name in this._vectors3) {
  40861. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40862. }
  40863. // Vector4
  40864. serializationObject.vectors4 = {};
  40865. for (name in this._vectors4) {
  40866. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40867. }
  40868. // Matrix
  40869. serializationObject.matrices = {};
  40870. for (name in this._matrices) {
  40871. serializationObject.matrices[name] = this._matrices[name].asArray();
  40872. }
  40873. // Matrix 3x3
  40874. serializationObject.matrices3x3 = {};
  40875. for (name in this._matrices3x3) {
  40876. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40877. }
  40878. // Matrix 2x2
  40879. serializationObject.matrices2x2 = {};
  40880. for (name in this._matrices2x2) {
  40881. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40882. }
  40883. // Vector3Array
  40884. serializationObject.vectors3Arrays = {};
  40885. for (name in this._vectors3Arrays) {
  40886. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40887. }
  40888. return serializationObject;
  40889. };
  40890. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40891. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40892. var name;
  40893. // Texture
  40894. for (name in source.textures) {
  40895. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40896. }
  40897. // Texture arrays
  40898. for (name in source.textureArrays) {
  40899. var array = source.textureArrays[name];
  40900. var textureArray = new Array();
  40901. for (var index = 0; index < array.length; index++) {
  40902. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40903. }
  40904. material.setTextureArray(name, textureArray);
  40905. }
  40906. // Float
  40907. for (name in source.floats) {
  40908. material.setFloat(name, source.floats[name]);
  40909. }
  40910. // Float s
  40911. for (name in source.floatsArrays) {
  40912. material.setFloats(name, source.floatsArrays[name]);
  40913. }
  40914. // Color3
  40915. for (name in source.colors3) {
  40916. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40917. }
  40918. // Color4
  40919. for (name in source.colors4) {
  40920. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40921. }
  40922. // Vector2
  40923. for (name in source.vectors2) {
  40924. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40925. }
  40926. // Vector3
  40927. for (name in source.vectors3) {
  40928. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40929. }
  40930. // Vector4
  40931. for (name in source.vectors4) {
  40932. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40933. }
  40934. // Matrix
  40935. for (name in source.matrices) {
  40936. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40937. }
  40938. // Matrix 3x3
  40939. for (name in source.matrices3x3) {
  40940. material.setMatrix3x3(name, source.matrices3x3[name]);
  40941. }
  40942. // Matrix 2x2
  40943. for (name in source.matrices2x2) {
  40944. material.setMatrix2x2(name, source.matrices2x2[name]);
  40945. }
  40946. // Vector3Array
  40947. for (name in source.vectors3Arrays) {
  40948. material.setArray3(name, source.vectors3Arrays[name]);
  40949. }
  40950. return material;
  40951. };
  40952. return ShaderMaterial;
  40953. }(BABYLON.Material));
  40954. BABYLON.ShaderMaterial = ShaderMaterial;
  40955. })(BABYLON || (BABYLON = {}));
  40956. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40957. var BABYLON;
  40958. (function (BABYLON) {
  40959. var Internals;
  40960. (function (Internals) {
  40961. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  40962. // All values and structures referenced from:
  40963. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  40964. var DDS_MAGIC = 0x20534444;
  40965. 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;
  40966. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  40967. 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;
  40968. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  40969. function FourCCToInt32(value) {
  40970. return value.charCodeAt(0) +
  40971. (value.charCodeAt(1) << 8) +
  40972. (value.charCodeAt(2) << 16) +
  40973. (value.charCodeAt(3) << 24);
  40974. }
  40975. function Int32ToFourCC(value) {
  40976. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  40977. }
  40978. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  40979. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  40980. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  40981. var headerLengthInt = 31; // The header length in 32 bit ints
  40982. // Offsets into the header array
  40983. var off_magic = 0;
  40984. var off_size = 1;
  40985. var off_flags = 2;
  40986. var off_height = 3;
  40987. var off_width = 4;
  40988. var off_mipmapCount = 7;
  40989. var off_pfFlags = 20;
  40990. var off_pfFourCC = 21;
  40991. var off_RGBbpp = 22;
  40992. var off_RMask = 23;
  40993. var off_GMask = 24;
  40994. var off_BMask = 25;
  40995. var off_AMask = 26;
  40996. var off_caps1 = 27;
  40997. var off_caps2 = 28;
  40998. ;
  40999. var DDSTools = (function () {
  41000. function DDSTools() {
  41001. }
  41002. DDSTools.GetDDSInfo = function (arrayBuffer) {
  41003. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  41004. var mipmapCount = 1;
  41005. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  41006. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41007. }
  41008. return {
  41009. width: header[off_width],
  41010. height: header[off_height],
  41011. mipmapCount: mipmapCount,
  41012. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  41013. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  41014. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  41015. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  41016. };
  41017. };
  41018. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41019. var byteArray = new Uint8Array(dataLength);
  41020. var srcData = new Uint8Array(arrayBuffer);
  41021. var index = 0;
  41022. for (var y = height - 1; y >= 0; y--) {
  41023. for (var x = 0; x < width; x++) {
  41024. var srcPos = dataOffset + (x + y * width) * 4;
  41025. byteArray[index + 2] = srcData[srcPos];
  41026. byteArray[index + 1] = srcData[srcPos + 1];
  41027. byteArray[index] = srcData[srcPos + 2];
  41028. byteArray[index + 3] = srcData[srcPos + 3];
  41029. index += 4;
  41030. }
  41031. }
  41032. return byteArray;
  41033. };
  41034. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41035. var byteArray = new Uint8Array(dataLength);
  41036. var srcData = new Uint8Array(arrayBuffer);
  41037. var index = 0;
  41038. for (var y = height - 1; y >= 0; y--) {
  41039. for (var x = 0; x < width; x++) {
  41040. var srcPos = dataOffset + (x + y * width) * 3;
  41041. byteArray[index + 2] = srcData[srcPos];
  41042. byteArray[index + 1] = srcData[srcPos + 1];
  41043. byteArray[index] = srcData[srcPos + 2];
  41044. index += 3;
  41045. }
  41046. }
  41047. return byteArray;
  41048. };
  41049. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41050. var byteArray = new Uint8Array(dataLength);
  41051. var srcData = new Uint8Array(arrayBuffer);
  41052. var index = 0;
  41053. for (var y = height - 1; y >= 0; y--) {
  41054. for (var x = 0; x < width; x++) {
  41055. var srcPos = dataOffset + (x + y * width);
  41056. byteArray[index] = srcData[srcPos];
  41057. index++;
  41058. }
  41059. }
  41060. return byteArray;
  41061. };
  41062. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  41063. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  41064. if (header[off_magic] != DDS_MAGIC) {
  41065. BABYLON.Tools.Error("Invalid magic number in DDS header");
  41066. return;
  41067. }
  41068. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  41069. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  41070. return;
  41071. }
  41072. if (info.isFourCC) {
  41073. fourCC = header[off_pfFourCC];
  41074. switch (fourCC) {
  41075. case FOURCC_DXT1:
  41076. blockBytes = 8;
  41077. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41078. break;
  41079. case FOURCC_DXT3:
  41080. blockBytes = 16;
  41081. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41082. break;
  41083. case FOURCC_DXT5:
  41084. blockBytes = 16;
  41085. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41086. break;
  41087. default:
  41088. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  41089. return;
  41090. }
  41091. }
  41092. mipmapCount = 1;
  41093. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  41094. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41095. }
  41096. var bpp = header[off_RGBbpp];
  41097. for (var face = 0; face < faces; face++) {
  41098. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41099. width = header[off_width];
  41100. height = header[off_height];
  41101. dataOffset = header[off_size] + 4;
  41102. for (i = 0; i < mipmapCount; ++i) {
  41103. if (info.isRGB) {
  41104. if (bpp === 24) {
  41105. dataLength = width * height * 3;
  41106. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41107. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41108. }
  41109. else {
  41110. dataLength = width * height * 4;
  41111. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41112. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41113. }
  41114. }
  41115. else if (info.isLuminance) {
  41116. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41117. var unpaddedRowSize = width;
  41118. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41119. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41120. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41121. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41122. }
  41123. else {
  41124. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41125. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41126. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41127. }
  41128. dataOffset += dataLength;
  41129. width *= 0.5;
  41130. height *= 0.5;
  41131. width = Math.max(1.0, width);
  41132. height = Math.max(1.0, height);
  41133. }
  41134. }
  41135. };
  41136. return DDSTools;
  41137. }());
  41138. Internals.DDSTools = DDSTools;
  41139. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41140. })(BABYLON || (BABYLON = {}));
  41141. //# sourceMappingURL=babylon.tools.dds.js.map
  41142. var BABYLON;
  41143. (function (BABYLON) {
  41144. var CannonJSPlugin = (function () {
  41145. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41146. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41147. if (iterations === void 0) { iterations = 10; }
  41148. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41149. this.name = "CannonJSPlugin";
  41150. this._physicsMaterials = [];
  41151. this._fixedTimeStep = 1 / 60;
  41152. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41153. this._currentCollisionGroup = 2;
  41154. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41155. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41156. this._tmpPosition = BABYLON.Vector3.Zero();
  41157. this._tmpQuaternion = new BABYLON.Quaternion();
  41158. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41159. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41160. this._tmpUnityRotation = new BABYLON.Quaternion();
  41161. if (!this.isSupported()) {
  41162. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41163. return;
  41164. }
  41165. this.world = new CANNON.World();
  41166. this.world.broadphase = new CANNON.NaiveBroadphase();
  41167. this.world.solver.iterations = iterations;
  41168. }
  41169. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41170. this.world.gravity.copy(gravity);
  41171. };
  41172. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41173. this._fixedTimeStep = timeStep;
  41174. };
  41175. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41176. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41177. };
  41178. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41179. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41180. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41181. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41182. };
  41183. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41184. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41185. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41186. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41187. };
  41188. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41189. //parent-child relationship. Does this impostor has a parent impostor?
  41190. if (impostor.parent) {
  41191. if (impostor.physicsBody) {
  41192. this.removePhysicsBody(impostor);
  41193. //TODO is that needed?
  41194. impostor.forceUpdate();
  41195. }
  41196. return;
  41197. }
  41198. //should a new body be created for this impostor?
  41199. if (impostor.isBodyInitRequired()) {
  41200. var shape = this._createShape(impostor);
  41201. //unregister events, if body is being changed
  41202. var oldBody = impostor.physicsBody;
  41203. if (oldBody) {
  41204. this.removePhysicsBody(impostor);
  41205. }
  41206. //create the body and material
  41207. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41208. var bodyCreationObject = {
  41209. mass: impostor.getParam("mass"),
  41210. material: material
  41211. };
  41212. // A simple extend, in case native options were used.
  41213. var nativeOptions = impostor.getParam("nativeOptions");
  41214. for (var key in nativeOptions) {
  41215. if (nativeOptions.hasOwnProperty(key)) {
  41216. bodyCreationObject[key] = nativeOptions[key];
  41217. }
  41218. }
  41219. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41220. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41221. this.world.addEventListener("preStep", impostor.beforeStep);
  41222. this.world.addEventListener("postStep", impostor.afterStep);
  41223. impostor.physicsBody.addShape(shape);
  41224. this.world.add(impostor.physicsBody);
  41225. //try to keep the body moving in the right direction by taking old properties.
  41226. //Should be tested!
  41227. if (oldBody) {
  41228. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41229. impostor.physicsBody[param].copy(oldBody[param]);
  41230. });
  41231. }
  41232. this._processChildMeshes(impostor);
  41233. }
  41234. //now update the body's transformation
  41235. this._updatePhysicsBodyTransformation(impostor);
  41236. };
  41237. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41238. var _this = this;
  41239. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41240. if (meshChildren.length) {
  41241. var processMesh = function (localPosition, mesh) {
  41242. var childImpostor = mesh.getPhysicsImpostor();
  41243. if (childImpostor) {
  41244. var parent = childImpostor.parent;
  41245. if (parent !== mainImpostor) {
  41246. var localPosition = mesh.position;
  41247. if (childImpostor.physicsBody) {
  41248. _this.removePhysicsBody(childImpostor);
  41249. childImpostor.physicsBody = null;
  41250. }
  41251. childImpostor.parent = mainImpostor;
  41252. childImpostor.resetUpdateFlags();
  41253. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41254. //Add the mass of the children.
  41255. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41256. }
  41257. }
  41258. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41259. };
  41260. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41261. }
  41262. };
  41263. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41264. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41265. this.world.removeEventListener("preStep", impostor.beforeStep);
  41266. this.world.removeEventListener("postStep", impostor.afterStep);
  41267. this.world.remove(impostor.physicsBody);
  41268. };
  41269. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41270. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41271. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41272. if (!mainBody || !connectedBody) {
  41273. return;
  41274. }
  41275. var constraint;
  41276. var jointData = impostorJoint.joint.jointData;
  41277. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41278. var constraintData = {
  41279. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41280. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41281. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41282. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41283. maxForce: jointData.nativeParams.maxForce,
  41284. collideConnected: !!jointData.collision
  41285. };
  41286. //Not needed, Cannon has a collideConnected flag
  41287. /*if (!jointData.collision) {
  41288. //add 1st body to a collision group of its own, if it is not in 1
  41289. if (mainBody.collisionFilterGroup === 1) {
  41290. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  41291. this._currentCollisionGroup <<= 1;
  41292. }
  41293. if (connectedBody.collisionFilterGroup === 1) {
  41294. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  41295. this._currentCollisionGroup <<= 1;
  41296. }
  41297. //add their mask to the collisionFilterMask of each other:
  41298. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  41299. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  41300. }*/
  41301. switch (impostorJoint.joint.type) {
  41302. case BABYLON.PhysicsJoint.HingeJoint:
  41303. case BABYLON.PhysicsJoint.Hinge2Joint:
  41304. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41305. break;
  41306. case BABYLON.PhysicsJoint.DistanceJoint:
  41307. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41308. break;
  41309. case BABYLON.PhysicsJoint.SpringJoint:
  41310. var springData = jointData;
  41311. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41312. restLength: springData.length,
  41313. stiffness: springData.stiffness,
  41314. damping: springData.damping,
  41315. localAnchorA: constraintData.pivotA,
  41316. localAnchorB: constraintData.pivotB
  41317. });
  41318. break;
  41319. case BABYLON.PhysicsJoint.LockJoint:
  41320. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41321. break;
  41322. case BABYLON.PhysicsJoint.PointToPointJoint:
  41323. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41324. default:
  41325. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41326. break;
  41327. }
  41328. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41329. constraint.collideConnected = !!jointData.collision;
  41330. impostorJoint.joint.physicsJoint = constraint;
  41331. //don't add spring as constraint, as it is not one.
  41332. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41333. this.world.addConstraint(constraint);
  41334. }
  41335. else {
  41336. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41337. constraint.applyForce();
  41338. });
  41339. }
  41340. };
  41341. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41342. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41343. };
  41344. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41345. var index;
  41346. var mat;
  41347. for (index = 0; index < this._physicsMaterials.length; index++) {
  41348. mat = this._physicsMaterials[index];
  41349. if (mat.friction === friction && mat.restitution === restitution) {
  41350. return mat;
  41351. }
  41352. }
  41353. var currentMat = new CANNON.Material(name);
  41354. currentMat.friction = friction;
  41355. currentMat.restitution = restitution;
  41356. this._physicsMaterials.push(currentMat);
  41357. return currentMat;
  41358. };
  41359. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41360. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41361. };
  41362. CannonJSPlugin.prototype._createShape = function (impostor) {
  41363. var object = impostor.object;
  41364. var returnValue;
  41365. var extendSize = impostor.getObjectExtendSize();
  41366. switch (impostor.type) {
  41367. case BABYLON.PhysicsEngine.SphereImpostor:
  41368. var radiusX = extendSize.x;
  41369. var radiusY = extendSize.y;
  41370. var radiusZ = extendSize.z;
  41371. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41372. break;
  41373. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41374. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41375. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41376. break;
  41377. case BABYLON.PhysicsImpostor.BoxImpostor:
  41378. var box = extendSize.scale(0.5);
  41379. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41380. break;
  41381. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41382. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41383. returnValue = new CANNON.Plane();
  41384. break;
  41385. case BABYLON.PhysicsImpostor.MeshImpostor:
  41386. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41387. var rawFaces = object.getIndices ? object.getIndices() : [];
  41388. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41389. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41390. break;
  41391. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41392. returnValue = this._createHeightmap(object);
  41393. break;
  41394. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41395. returnValue = new CANNON.Particle();
  41396. break;
  41397. }
  41398. return returnValue;
  41399. };
  41400. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41401. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41402. var matrix = [];
  41403. //For now pointDepth will not be used and will be automatically calculated.
  41404. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41405. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41406. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41407. var elementSize = dim * 2 / arraySize;
  41408. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41409. for (var i = 0; i < pos.length; i = i + 3) {
  41410. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41411. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41412. var y = pos[i + 1] + minY;
  41413. if (!matrix[x]) {
  41414. matrix[x] = [];
  41415. }
  41416. if (!matrix[x][z]) {
  41417. matrix[x][z] = y;
  41418. }
  41419. matrix[x][z] = Math.max(y, matrix[x][z]);
  41420. }
  41421. for (var x = 0; x <= arraySize; ++x) {
  41422. if (!matrix[x]) {
  41423. var loc = 1;
  41424. while (!matrix[(x + loc) % arraySize]) {
  41425. loc++;
  41426. }
  41427. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41428. }
  41429. for (var z = 0; z <= arraySize; ++z) {
  41430. if (!matrix[x][z]) {
  41431. var loc = 1;
  41432. var newValue;
  41433. while (newValue === undefined) {
  41434. newValue = matrix[x][(z + loc++) % arraySize];
  41435. }
  41436. matrix[x][z] = newValue;
  41437. }
  41438. }
  41439. }
  41440. var shape = new CANNON.Heightfield(matrix, {
  41441. elementSize: elementSize
  41442. });
  41443. //For future reference, needed for body transformation
  41444. shape.minY = minY;
  41445. return shape;
  41446. };
  41447. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41448. var object = impostor.object;
  41449. //make sure it is updated...
  41450. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41451. // The delta between the mesh position and the mesh bounding box center
  41452. var center = impostor.getObjectCenter();
  41453. var extendSize = impostor.getObjectExtendSize();
  41454. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41455. this._tmpPosition.copyFrom(center);
  41456. var quaternion = object.rotationQuaternion;
  41457. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41458. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  41459. //-90 DEG in X, precalculated
  41460. quaternion = quaternion.multiply(this._minus90X);
  41461. //Invert! (Precalculated, 90 deg in X)
  41462. //No need to clone. this will never change.
  41463. impostor.setDeltaRotation(this._plus90X);
  41464. }
  41465. //If it is a heightfield, if should be centered.
  41466. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  41467. var mesh = object;
  41468. //calculate the correct body position:
  41469. var rotationQuaternion = mesh.rotationQuaternion;
  41470. mesh.rotationQuaternion = this._tmpUnityRotation;
  41471. mesh.computeWorldMatrix(true);
  41472. //get original center with no rotation
  41473. var c = center.clone();
  41474. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  41475. //rotation is back
  41476. mesh.rotationQuaternion = rotationQuaternion;
  41477. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  41478. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  41479. mesh.setPivotMatrix(p);
  41480. mesh.computeWorldMatrix(true);
  41481. //calculate the translation
  41482. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  41483. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  41484. //add it inverted to the delta
  41485. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  41486. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  41487. mesh.setPivotMatrix(oldPivot);
  41488. mesh.computeWorldMatrix(true);
  41489. }
  41490. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  41491. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  41492. this._tmpPosition.copyFrom(object.position);
  41493. }
  41494. impostor.setDeltaPosition(this._tmpDeltaPosition);
  41495. //Now update the impostor object
  41496. impostor.physicsBody.position.copy(this._tmpPosition);
  41497. impostor.physicsBody.quaternion.copy(quaternion);
  41498. };
  41499. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41500. impostor.object.position.copyFrom(impostor.physicsBody.position);
  41501. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  41502. };
  41503. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41504. impostor.physicsBody.position.copy(newPosition);
  41505. impostor.physicsBody.quaternion.copy(newRotation);
  41506. };
  41507. CannonJSPlugin.prototype.isSupported = function () {
  41508. return window.CANNON !== undefined;
  41509. };
  41510. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41511. impostor.physicsBody.velocity.copy(velocity);
  41512. };
  41513. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41514. impostor.physicsBody.angularVelocity.copy(velocity);
  41515. };
  41516. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41517. var v = impostor.physicsBody.velocity;
  41518. if (!v)
  41519. return null;
  41520. return new BABYLON.Vector3(v.x, v.y, v.z);
  41521. };
  41522. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41523. var v = impostor.physicsBody.angularVelocity;
  41524. if (!v)
  41525. return null;
  41526. return new BABYLON.Vector3(v.x, v.y, v.z);
  41527. };
  41528. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41529. impostor.physicsBody.mass = mass;
  41530. impostor.physicsBody.updateMassProperties();
  41531. };
  41532. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  41533. impostor.physicsBody.sleep();
  41534. };
  41535. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  41536. impostor.physicsBody.wakeUp();
  41537. };
  41538. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41539. joint.physicsJoint.distance = maxDistance;
  41540. };
  41541. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  41542. if (!motorIndex) {
  41543. joint.physicsJoint.enableMotor();
  41544. }
  41545. };
  41546. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  41547. if (!motorIndex) {
  41548. joint.physicsJoint.disableMotor();
  41549. }
  41550. };
  41551. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41552. if (!motorIndex) {
  41553. joint.physicsJoint.enableMotor();
  41554. joint.physicsJoint.setMotorSpeed(speed);
  41555. if (maxForce) {
  41556. this.setLimit(joint, maxForce);
  41557. }
  41558. }
  41559. };
  41560. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  41561. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  41562. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  41563. };
  41564. CannonJSPlugin.prototype.dispose = function () {
  41565. //nothing to do, actually.
  41566. };
  41567. return CannonJSPlugin;
  41568. }());
  41569. BABYLON.CannonJSPlugin = CannonJSPlugin;
  41570. })(BABYLON || (BABYLON = {}));
  41571. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  41572. var BABYLON;
  41573. (function (BABYLON) {
  41574. var OimoJSPlugin = (function () {
  41575. function OimoJSPlugin(iterations) {
  41576. this.name = "OimoJSPlugin";
  41577. this._tmpImpostorsArray = [];
  41578. this._tmpPositionVector = BABYLON.Vector3.Zero();
  41579. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  41580. this.world.worldscale(1);
  41581. this.world.clear();
  41582. //making sure no stats are calculated
  41583. this.world.isNoStat = true;
  41584. }
  41585. OimoJSPlugin.prototype.setGravity = function (gravity) {
  41586. this.world.gravity.copy(gravity);
  41587. };
  41588. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  41589. this.world.timeStep = timeStep;
  41590. };
  41591. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  41592. var _this = this;
  41593. impostors.forEach(function (impostor) {
  41594. impostor.beforeStep();
  41595. });
  41596. this.world.step();
  41597. impostors.forEach(function (impostor) {
  41598. impostor.afterStep();
  41599. //update the ordered impostors array
  41600. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  41601. });
  41602. //check for collisions
  41603. var contact = this.world.contacts;
  41604. while (contact !== null) {
  41605. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  41606. contact = contact.next;
  41607. continue;
  41608. }
  41609. //is this body colliding with any other? get the impostor
  41610. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  41611. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  41612. if (!mainImpostor || !collidingImpostor) {
  41613. contact = contact.next;
  41614. continue;
  41615. }
  41616. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41617. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  41618. contact = contact.next;
  41619. }
  41620. };
  41621. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41622. var mass = impostor.physicsBody.massInfo.mass;
  41623. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  41624. };
  41625. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41626. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  41627. this.applyImpulse(impostor, force, contactPoint);
  41628. };
  41629. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41630. var _this = this;
  41631. //parent-child relationship. Does this impostor has a parent impostor?
  41632. if (impostor.parent) {
  41633. if (impostor.physicsBody) {
  41634. this.removePhysicsBody(impostor);
  41635. //TODO is that needed?
  41636. impostor.forceUpdate();
  41637. }
  41638. return;
  41639. }
  41640. if (impostor.isBodyInitRequired()) {
  41641. var bodyConfig = {
  41642. name: impostor.uniqueId,
  41643. //Oimo must have mass, also for static objects.
  41644. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  41645. size: [],
  41646. type: [],
  41647. pos: [],
  41648. rot: [],
  41649. move: impostor.getParam("mass") !== 0,
  41650. //Supporting older versions of Oimo
  41651. world: this.world
  41652. };
  41653. var impostors = [impostor];
  41654. var addToArray = function (parent) {
  41655. if (!parent.getChildMeshes)
  41656. return;
  41657. parent.getChildMeshes().forEach(function (m) {
  41658. if (m.physicsImpostor) {
  41659. impostors.push(m.physicsImpostor);
  41660. m.physicsImpostor._init();
  41661. }
  41662. });
  41663. };
  41664. addToArray(impostor.object);
  41665. var checkWithEpsilon_1 = function (value) {
  41666. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  41667. };
  41668. impostors.forEach(function (i) {
  41669. //get the correct bounding box
  41670. var oldQuaternion = i.object.rotationQuaternion;
  41671. var rot = new OIMO.Euler().setFromQuaternion({
  41672. x: impostor.object.rotationQuaternion.x,
  41673. y: impostor.object.rotationQuaternion.y,
  41674. z: impostor.object.rotationQuaternion.z,
  41675. s: impostor.object.rotationQuaternion.w
  41676. });
  41677. var extendSize = i.getObjectExtendSize();
  41678. if (i === impostor) {
  41679. var center = impostor.getObjectCenter();
  41680. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  41681. //Can also use Array.prototype.push.apply
  41682. bodyConfig.pos.push(center.x);
  41683. bodyConfig.pos.push(center.y);
  41684. bodyConfig.pos.push(center.z);
  41685. //tmp solution
  41686. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  41687. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  41688. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  41689. }
  41690. else {
  41691. bodyConfig.pos.push(i.object.position.x);
  41692. bodyConfig.pos.push(i.object.position.y);
  41693. bodyConfig.pos.push(i.object.position.z);
  41694. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  41695. bodyConfig.rot.push(0);
  41696. bodyConfig.rot.push(0);
  41697. bodyConfig.rot.push(0);
  41698. }
  41699. // register mesh
  41700. switch (i.type) {
  41701. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41702. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  41703. case BABYLON.PhysicsImpostor.SphereImpostor:
  41704. var radiusX = extendSize.x;
  41705. var radiusY = extendSize.y;
  41706. var radiusZ = extendSize.z;
  41707. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  41708. bodyConfig.type.push('sphere');
  41709. //due to the way oimo works with compounds, add 3 times
  41710. bodyConfig.size.push(size);
  41711. bodyConfig.size.push(size);
  41712. bodyConfig.size.push(size);
  41713. break;
  41714. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41715. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  41716. var sizeY = checkWithEpsilon_1(extendSize.y);
  41717. bodyConfig.type.push('cylinder');
  41718. bodyConfig.size.push(sizeX);
  41719. bodyConfig.size.push(sizeY);
  41720. //due to the way oimo works with compounds, add one more value.
  41721. bodyConfig.size.push(sizeY);
  41722. break;
  41723. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41724. case BABYLON.PhysicsImpostor.BoxImpostor:
  41725. default:
  41726. var sizeX = checkWithEpsilon_1(extendSize.x);
  41727. var sizeY = checkWithEpsilon_1(extendSize.y);
  41728. var sizeZ = checkWithEpsilon_1(extendSize.z);
  41729. bodyConfig.type.push('box');
  41730. bodyConfig.size.push(sizeX);
  41731. bodyConfig.size.push(sizeY);
  41732. bodyConfig.size.push(sizeZ);
  41733. break;
  41734. }
  41735. //actually not needed, but hey...
  41736. i.object.rotationQuaternion = oldQuaternion;
  41737. });
  41738. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  41739. }
  41740. else {
  41741. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  41742. }
  41743. impostor.setDeltaPosition(this._tmpPositionVector);
  41744. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  41745. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  41746. };
  41747. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41748. //impostor.physicsBody.dispose();
  41749. //Same as : (older oimo versions)
  41750. this.world.removeRigidBody(impostor.physicsBody);
  41751. };
  41752. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41753. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41754. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41755. if (!mainBody || !connectedBody) {
  41756. return;
  41757. }
  41758. var jointData = impostorJoint.joint.jointData;
  41759. var options = jointData.nativeParams || {};
  41760. var type;
  41761. var nativeJointData = {
  41762. body1: mainBody,
  41763. body2: connectedBody,
  41764. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  41765. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  41766. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  41767. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  41768. min: options.min,
  41769. max: options.max,
  41770. collision: options.collision || jointData.collision,
  41771. spring: options.spring,
  41772. //supporting older version of Oimo
  41773. world: this.world
  41774. };
  41775. switch (impostorJoint.joint.type) {
  41776. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41777. type = "jointBall";
  41778. break;
  41779. case BABYLON.PhysicsJoint.SpringJoint:
  41780. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  41781. var springData = jointData;
  41782. nativeJointData.min = springData.length || nativeJointData.min;
  41783. //Max should also be set, just make sure it is at least min
  41784. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  41785. case BABYLON.PhysicsJoint.DistanceJoint:
  41786. type = "jointDistance";
  41787. nativeJointData.max = jointData.maxDistance;
  41788. break;
  41789. case BABYLON.PhysicsJoint.PrismaticJoint:
  41790. type = "jointPrisme";
  41791. break;
  41792. case BABYLON.PhysicsJoint.SliderJoint:
  41793. type = "jointSlide";
  41794. break;
  41795. case BABYLON.PhysicsJoint.WheelJoint:
  41796. type = "jointWheel";
  41797. break;
  41798. case BABYLON.PhysicsJoint.HingeJoint:
  41799. default:
  41800. type = "jointHinge";
  41801. break;
  41802. }
  41803. nativeJointData.type = type;
  41804. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  41805. };
  41806. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41807. //Bug in Oimo prevents us from disposing a joint in the playground
  41808. //joint.joint.physicsJoint.dispose();
  41809. //So we will bruteforce it!
  41810. try {
  41811. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  41812. }
  41813. catch (e) {
  41814. BABYLON.Tools.Warn(e);
  41815. }
  41816. };
  41817. OimoJSPlugin.prototype.isSupported = function () {
  41818. return OIMO !== undefined;
  41819. };
  41820. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41821. if (!impostor.physicsBody.sleeping) {
  41822. //TODO check that
  41823. if (impostor.physicsBody.shapes.next) {
  41824. var parentShape = this._getLastShape(impostor.physicsBody);
  41825. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  41826. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  41827. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  41828. }
  41829. else {
  41830. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  41831. }
  41832. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  41833. impostor.object.rotationQuaternion.normalize();
  41834. }
  41835. };
  41836. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41837. var body = impostor.physicsBody;
  41838. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  41839. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  41840. body.syncShapes();
  41841. body.awake();
  41842. };
  41843. OimoJSPlugin.prototype._getLastShape = function (body) {
  41844. var lastShape = body.shapes;
  41845. while (lastShape.next) {
  41846. lastShape = lastShape.next;
  41847. }
  41848. return lastShape;
  41849. };
  41850. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41851. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  41852. };
  41853. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41854. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  41855. };
  41856. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41857. var v = impostor.physicsBody.linearVelocity;
  41858. if (!v)
  41859. return null;
  41860. return new BABYLON.Vector3(v.x, v.y, v.z);
  41861. };
  41862. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41863. var v = impostor.physicsBody.angularVelocity;
  41864. if (!v)
  41865. return null;
  41866. return new BABYLON.Vector3(v.x, v.y, v.z);
  41867. };
  41868. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41869. var staticBody = mass === 0;
  41870. //this will actually set the body's density and not its mass.
  41871. //But this is how oimo treats the mass variable.
  41872. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  41873. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  41874. };
  41875. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  41876. impostor.physicsBody.sleep();
  41877. };
  41878. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  41879. impostor.physicsBody.awake();
  41880. };
  41881. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41882. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  41883. if (minDistance !== void 0) {
  41884. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  41885. }
  41886. };
  41887. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41888. //TODO separate rotational and transational motors.
  41889. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41890. if (motor) {
  41891. motor.setMotor(speed, maxForce);
  41892. }
  41893. };
  41894. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  41895. //TODO separate rotational and transational motors.
  41896. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41897. if (motor) {
  41898. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  41899. }
  41900. };
  41901. OimoJSPlugin.prototype.dispose = function () {
  41902. this.world.clear();
  41903. };
  41904. return OimoJSPlugin;
  41905. }());
  41906. BABYLON.OimoJSPlugin = OimoJSPlugin;
  41907. })(BABYLON || (BABYLON = {}));
  41908. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  41909. var BABYLON;
  41910. (function (BABYLON) {
  41911. var DisplayPassPostProcess = (function (_super) {
  41912. __extends(DisplayPassPostProcess, _super);
  41913. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  41914. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  41915. }
  41916. return DisplayPassPostProcess;
  41917. }(BABYLON.PostProcess));
  41918. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  41919. })(BABYLON || (BABYLON = {}));
  41920. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  41921. var BABYLON;
  41922. (function (BABYLON) {
  41923. var SimplificationSettings = (function () {
  41924. function SimplificationSettings(quality, distance, optimizeMesh) {
  41925. this.quality = quality;
  41926. this.distance = distance;
  41927. this.optimizeMesh = optimizeMesh;
  41928. }
  41929. return SimplificationSettings;
  41930. }());
  41931. BABYLON.SimplificationSettings = SimplificationSettings;
  41932. var SimplificationQueue = (function () {
  41933. function SimplificationQueue() {
  41934. this.running = false;
  41935. this._simplificationArray = [];
  41936. }
  41937. SimplificationQueue.prototype.addTask = function (task) {
  41938. this._simplificationArray.push(task);
  41939. };
  41940. SimplificationQueue.prototype.executeNext = function () {
  41941. var task = this._simplificationArray.pop();
  41942. if (task) {
  41943. this.running = true;
  41944. this.runSimplification(task);
  41945. }
  41946. else {
  41947. this.running = false;
  41948. }
  41949. };
  41950. SimplificationQueue.prototype.runSimplification = function (task) {
  41951. var _this = this;
  41952. if (task.parallelProcessing) {
  41953. //parallel simplifier
  41954. task.settings.forEach(function (setting) {
  41955. var simplifier = _this.getSimplifier(task);
  41956. simplifier.simplify(setting, function (newMesh) {
  41957. task.mesh.addLODLevel(setting.distance, newMesh);
  41958. newMesh.isVisible = true;
  41959. //check if it is the last
  41960. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41961. //all done, run the success callback.
  41962. task.successCallback();
  41963. }
  41964. _this.executeNext();
  41965. });
  41966. });
  41967. }
  41968. else {
  41969. //single simplifier.
  41970. var simplifier = this.getSimplifier(task);
  41971. var runDecimation = function (setting, callback) {
  41972. simplifier.simplify(setting, function (newMesh) {
  41973. task.mesh.addLODLevel(setting.distance, newMesh);
  41974. newMesh.isVisible = true;
  41975. //run the next quality level
  41976. callback();
  41977. });
  41978. };
  41979. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  41980. runDecimation(task.settings[loop.index], function () {
  41981. loop.executeNext();
  41982. });
  41983. }, function () {
  41984. //execution ended, run the success callback.
  41985. if (task.successCallback) {
  41986. task.successCallback();
  41987. }
  41988. _this.executeNext();
  41989. });
  41990. }
  41991. };
  41992. SimplificationQueue.prototype.getSimplifier = function (task) {
  41993. switch (task.simplificationType) {
  41994. case SimplificationType.QUADRATIC:
  41995. default:
  41996. return new QuadraticErrorSimplification(task.mesh);
  41997. }
  41998. };
  41999. return SimplificationQueue;
  42000. }());
  42001. BABYLON.SimplificationQueue = SimplificationQueue;
  42002. /**
  42003. * The implemented types of simplification.
  42004. * At the moment only Quadratic Error Decimation is implemented.
  42005. */
  42006. var SimplificationType;
  42007. (function (SimplificationType) {
  42008. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  42009. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  42010. var DecimationTriangle = (function () {
  42011. function DecimationTriangle(vertices) {
  42012. this.vertices = vertices;
  42013. this.error = new Array(4);
  42014. this.deleted = false;
  42015. this.isDirty = false;
  42016. this.deletePending = false;
  42017. this.borderFactor = 0;
  42018. }
  42019. return DecimationTriangle;
  42020. }());
  42021. BABYLON.DecimationTriangle = DecimationTriangle;
  42022. var DecimationVertex = (function () {
  42023. function DecimationVertex(position, id) {
  42024. this.position = position;
  42025. this.id = id;
  42026. this.isBorder = true;
  42027. this.q = new QuadraticMatrix();
  42028. this.triangleCount = 0;
  42029. this.triangleStart = 0;
  42030. this.originalOffsets = [];
  42031. }
  42032. DecimationVertex.prototype.updatePosition = function (newPosition) {
  42033. this.position.copyFrom(newPosition);
  42034. };
  42035. return DecimationVertex;
  42036. }());
  42037. BABYLON.DecimationVertex = DecimationVertex;
  42038. var QuadraticMatrix = (function () {
  42039. function QuadraticMatrix(data) {
  42040. this.data = new Array(10);
  42041. for (var i = 0; i < 10; ++i) {
  42042. if (data && data[i]) {
  42043. this.data[i] = data[i];
  42044. }
  42045. else {
  42046. this.data[i] = 0;
  42047. }
  42048. }
  42049. }
  42050. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  42051. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  42052. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  42053. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  42054. return det;
  42055. };
  42056. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  42057. for (var i = 0; i < 10; ++i) {
  42058. this.data[i] += matrix.data[i];
  42059. }
  42060. };
  42061. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  42062. for (var i = 0; i < 10; ++i) {
  42063. this.data[i] += data[i];
  42064. }
  42065. };
  42066. QuadraticMatrix.prototype.add = function (matrix) {
  42067. var m = new QuadraticMatrix();
  42068. for (var i = 0; i < 10; ++i) {
  42069. m.data[i] = this.data[i] + matrix.data[i];
  42070. }
  42071. return m;
  42072. };
  42073. QuadraticMatrix.FromData = function (a, b, c, d) {
  42074. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  42075. };
  42076. //returning an array to avoid garbage collection
  42077. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  42078. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  42079. };
  42080. return QuadraticMatrix;
  42081. }());
  42082. BABYLON.QuadraticMatrix = QuadraticMatrix;
  42083. var Reference = (function () {
  42084. function Reference(vertexId, triangleId) {
  42085. this.vertexId = vertexId;
  42086. this.triangleId = triangleId;
  42087. }
  42088. return Reference;
  42089. }());
  42090. BABYLON.Reference = Reference;
  42091. /**
  42092. * An implementation of the Quadratic Error simplification algorithm.
  42093. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  42094. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  42095. * @author RaananW
  42096. */
  42097. var QuadraticErrorSimplification = (function () {
  42098. function QuadraticErrorSimplification(_mesh) {
  42099. this._mesh = _mesh;
  42100. this.initialized = false;
  42101. this.syncIterations = 5000;
  42102. this.aggressiveness = 7;
  42103. this.decimationIterations = 100;
  42104. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42105. }
  42106. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42107. var _this = this;
  42108. this.initDecimatedMesh();
  42109. //iterating through the submeshes array, one after the other.
  42110. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42111. _this.initWithMesh(loop.index, function () {
  42112. _this.runDecimation(settings, loop.index, function () {
  42113. loop.executeNext();
  42114. });
  42115. }, settings.optimizeMesh);
  42116. }, function () {
  42117. setTimeout(function () {
  42118. successCallback(_this._reconstructedMesh);
  42119. }, 0);
  42120. });
  42121. };
  42122. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42123. var _this = this;
  42124. var gCount = 0;
  42125. triangle.vertices.forEach(function (vertex) {
  42126. var count = 0;
  42127. var vPos = vertex.position;
  42128. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42129. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42130. ++count;
  42131. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42132. ++count;
  42133. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42134. ++count;
  42135. if (count > 1) {
  42136. ++gCount;
  42137. }
  42138. ;
  42139. });
  42140. if (gCount > 1) {
  42141. console.log(triangle, gCount);
  42142. }
  42143. return gCount > 1;
  42144. };
  42145. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42146. var _this = this;
  42147. var targetCount = ~~(this.triangles.length * settings.quality);
  42148. var deletedTriangles = 0;
  42149. var triangleCount = this.triangles.length;
  42150. var iterationFunction = function (iteration, callback) {
  42151. setTimeout(function () {
  42152. if (iteration % 5 === 0) {
  42153. _this.updateMesh(iteration === 0);
  42154. }
  42155. for (var i = 0; i < _this.triangles.length; ++i) {
  42156. _this.triangles[i].isDirty = false;
  42157. }
  42158. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42159. var trianglesIterator = function (i) {
  42160. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42161. var t = _this.triangles[tIdx];
  42162. if (!t)
  42163. return;
  42164. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42165. return;
  42166. }
  42167. for (var j = 0; j < 3; ++j) {
  42168. if (t.error[j] < threshold) {
  42169. var deleted0 = [];
  42170. var deleted1 = [];
  42171. var v0 = t.vertices[j];
  42172. var v1 = t.vertices[(j + 1) % 3];
  42173. if (v0.isBorder || v1.isBorder)
  42174. continue;
  42175. var p = BABYLON.Vector3.Zero();
  42176. var n = BABYLON.Vector3.Zero();
  42177. var uv = BABYLON.Vector2.Zero();
  42178. var color = new BABYLON.Color4(0, 0, 0, 1);
  42179. _this.calculateError(v0, v1, p, n, uv, color);
  42180. var delTr = [];
  42181. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42182. continue;
  42183. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42184. continue;
  42185. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42186. continue;
  42187. var uniqueArray = [];
  42188. delTr.forEach(function (deletedT) {
  42189. if (uniqueArray.indexOf(deletedT) === -1) {
  42190. deletedT.deletePending = true;
  42191. uniqueArray.push(deletedT);
  42192. }
  42193. });
  42194. if (uniqueArray.length % 2 !== 0) {
  42195. continue;
  42196. }
  42197. v0.q = v1.q.add(v0.q);
  42198. v0.updatePosition(p);
  42199. var tStart = _this.references.length;
  42200. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42201. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42202. var tCount = _this.references.length - tStart;
  42203. if (tCount <= v0.triangleCount) {
  42204. if (tCount) {
  42205. for (var c = 0; c < tCount; c++) {
  42206. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42207. }
  42208. }
  42209. }
  42210. else {
  42211. v0.triangleStart = tStart;
  42212. }
  42213. v0.triangleCount = tCount;
  42214. break;
  42215. }
  42216. }
  42217. };
  42218. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42219. }, 0);
  42220. };
  42221. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42222. if (triangleCount - deletedTriangles <= targetCount)
  42223. loop.breakLoop();
  42224. else {
  42225. iterationFunction(loop.index, function () {
  42226. loop.executeNext();
  42227. });
  42228. }
  42229. }, function () {
  42230. setTimeout(function () {
  42231. //reconstruct this part of the mesh
  42232. _this.reconstructMesh(submeshIndex);
  42233. successCallback();
  42234. }, 0);
  42235. });
  42236. };
  42237. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42238. var _this = this;
  42239. this.vertices = [];
  42240. this.triangles = [];
  42241. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42242. var indices = this._mesh.getIndices();
  42243. var submesh = this._mesh.subMeshes[submeshIndex];
  42244. var findInVertices = function (positionToSearch) {
  42245. if (optimizeMesh) {
  42246. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42247. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42248. return _this.vertices[ii];
  42249. }
  42250. }
  42251. }
  42252. return null;
  42253. };
  42254. var vertexReferences = [];
  42255. var vertexInit = function (i) {
  42256. var offset = i + submesh.verticesStart;
  42257. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42258. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42259. vertex.originalOffsets.push(offset);
  42260. if (vertex.id === _this.vertices.length) {
  42261. _this.vertices.push(vertex);
  42262. }
  42263. vertexReferences.push(vertex.id);
  42264. };
  42265. //var totalVertices = mesh.getTotalVertices();
  42266. var totalVertices = submesh.verticesCount;
  42267. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42268. var indicesInit = function (i) {
  42269. var offset = (submesh.indexStart / 3) + i;
  42270. var pos = (offset * 3);
  42271. var i0 = indices[pos + 0];
  42272. var i1 = indices[pos + 1];
  42273. var i2 = indices[pos + 2];
  42274. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42275. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42276. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42277. var triangle = new DecimationTriangle([v0, v1, v2]);
  42278. triangle.originalOffset = pos;
  42279. _this.triangles.push(triangle);
  42280. };
  42281. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42282. _this.init(callback);
  42283. });
  42284. });
  42285. };
  42286. QuadraticErrorSimplification.prototype.init = function (callback) {
  42287. var _this = this;
  42288. var triangleInit1 = function (i) {
  42289. var t = _this.triangles[i];
  42290. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42291. for (var j = 0; j < 3; j++) {
  42292. 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))));
  42293. }
  42294. };
  42295. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42296. var triangleInit2 = function (i) {
  42297. var t = _this.triangles[i];
  42298. for (var j = 0; j < 3; ++j) {
  42299. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42300. }
  42301. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42302. };
  42303. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42304. _this.initialized = true;
  42305. callback();
  42306. });
  42307. });
  42308. };
  42309. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42310. var newTriangles = [];
  42311. var i;
  42312. for (i = 0; i < this.vertices.length; ++i) {
  42313. this.vertices[i].triangleCount = 0;
  42314. }
  42315. var t;
  42316. var j;
  42317. for (i = 0; i < this.triangles.length; ++i) {
  42318. if (!this.triangles[i].deleted) {
  42319. t = this.triangles[i];
  42320. for (j = 0; j < 3; ++j) {
  42321. t.vertices[j].triangleCount = 1;
  42322. }
  42323. newTriangles.push(t);
  42324. }
  42325. }
  42326. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42327. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42328. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42329. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42330. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42331. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42332. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42333. var vertexCount = 0;
  42334. for (i = 0; i < this.vertices.length; ++i) {
  42335. var vertex = this.vertices[i];
  42336. vertex.id = vertexCount;
  42337. if (vertex.triangleCount) {
  42338. vertex.originalOffsets.forEach(function (originalOffset) {
  42339. newPositionData.push(vertex.position.x);
  42340. newPositionData.push(vertex.position.y);
  42341. newPositionData.push(vertex.position.z);
  42342. newNormalData.push(normalData[originalOffset * 3]);
  42343. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42344. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42345. if (uvs && uvs.length) {
  42346. newUVsData.push(uvs[(originalOffset * 2)]);
  42347. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42348. }
  42349. else if (colorsData && colorsData.length) {
  42350. newColorsData.push(colorsData[(originalOffset * 4)]);
  42351. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42352. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42353. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42354. }
  42355. ++vertexCount;
  42356. });
  42357. }
  42358. }
  42359. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42360. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42361. var submeshesArray = this._reconstructedMesh.subMeshes;
  42362. this._reconstructedMesh.subMeshes = [];
  42363. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42364. var originalIndices = this._mesh.getIndices();
  42365. for (i = 0; i < newTriangles.length; ++i) {
  42366. t = newTriangles[i]; //now get the new referencing point for each vertex
  42367. [0, 1, 2].forEach(function (idx) {
  42368. var id = originalIndices[t.originalOffset + idx];
  42369. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42370. if (offset < 0)
  42371. offset = 0;
  42372. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42373. });
  42374. }
  42375. //overwriting the old vertex buffers and indices.
  42376. this._reconstructedMesh.setIndices(newIndicesArray);
  42377. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42378. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42379. if (newUVsData.length > 0)
  42380. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42381. if (newColorsData.length > 0)
  42382. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42383. //create submesh
  42384. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42385. if (submeshIndex > 0) {
  42386. this._reconstructedMesh.subMeshes = [];
  42387. submeshesArray.forEach(function (submesh) {
  42388. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42389. });
  42390. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42391. }
  42392. };
  42393. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42394. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42395. this._reconstructedMesh.material = this._mesh.material;
  42396. this._reconstructedMesh.parent = this._mesh.parent;
  42397. this._reconstructedMesh.isVisible = false;
  42398. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42399. };
  42400. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42401. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42402. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42403. if (t.deleted)
  42404. continue;
  42405. var s = this.references[vertex1.triangleStart + i].vertexId;
  42406. var v1 = t.vertices[(s + 1) % 3];
  42407. var v2 = t.vertices[(s + 2) % 3];
  42408. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42409. deletedArray[i] = true;
  42410. delTr.push(t);
  42411. continue;
  42412. }
  42413. var d1 = v1.position.subtract(point);
  42414. d1 = d1.normalize();
  42415. var d2 = v2.position.subtract(point);
  42416. d2 = d2.normalize();
  42417. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42418. return true;
  42419. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42420. deletedArray[i] = false;
  42421. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42422. return true;
  42423. }
  42424. return false;
  42425. };
  42426. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42427. var newDeleted = deletedTriangles;
  42428. for (var i = 0; i < vertex.triangleCount; ++i) {
  42429. var ref = this.references[vertex.triangleStart + i];
  42430. var t = this.triangles[ref.triangleId];
  42431. if (t.deleted)
  42432. continue;
  42433. if (deletedArray[i] && t.deletePending) {
  42434. t.deleted = true;
  42435. newDeleted++;
  42436. continue;
  42437. }
  42438. t.vertices[ref.vertexId] = origVertex;
  42439. t.isDirty = true;
  42440. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42441. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42442. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42443. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42444. this.references.push(ref);
  42445. }
  42446. return newDeleted;
  42447. };
  42448. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42449. for (var i = 0; i < this.vertices.length; ++i) {
  42450. var vCount = [];
  42451. var vId = [];
  42452. var v = this.vertices[i];
  42453. var j;
  42454. for (j = 0; j < v.triangleCount; ++j) {
  42455. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42456. for (var ii = 0; ii < 3; ii++) {
  42457. var ofs = 0;
  42458. var vv = triangle.vertices[ii];
  42459. while (ofs < vCount.length) {
  42460. if (vId[ofs] === vv.id)
  42461. break;
  42462. ++ofs;
  42463. }
  42464. if (ofs === vCount.length) {
  42465. vCount.push(1);
  42466. vId.push(vv.id);
  42467. }
  42468. else {
  42469. vCount[ofs]++;
  42470. }
  42471. }
  42472. }
  42473. for (j = 0; j < vCount.length; ++j) {
  42474. if (vCount[j] === 1) {
  42475. this.vertices[vId[j]].isBorder = true;
  42476. }
  42477. else {
  42478. this.vertices[vId[j]].isBorder = false;
  42479. }
  42480. }
  42481. }
  42482. };
  42483. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  42484. if (identifyBorders === void 0) { identifyBorders = false; }
  42485. var i;
  42486. if (!identifyBorders) {
  42487. var newTrianglesVector = [];
  42488. for (i = 0; i < this.triangles.length; ++i) {
  42489. if (!this.triangles[i].deleted) {
  42490. newTrianglesVector.push(this.triangles[i]);
  42491. }
  42492. }
  42493. this.triangles = newTrianglesVector;
  42494. }
  42495. for (i = 0; i < this.vertices.length; ++i) {
  42496. this.vertices[i].triangleCount = 0;
  42497. this.vertices[i].triangleStart = 0;
  42498. }
  42499. var t;
  42500. var j;
  42501. var v;
  42502. for (i = 0; i < this.triangles.length; ++i) {
  42503. t = this.triangles[i];
  42504. for (j = 0; j < 3; ++j) {
  42505. v = t.vertices[j];
  42506. v.triangleCount++;
  42507. }
  42508. }
  42509. var tStart = 0;
  42510. for (i = 0; i < this.vertices.length; ++i) {
  42511. this.vertices[i].triangleStart = tStart;
  42512. tStart += this.vertices[i].triangleCount;
  42513. this.vertices[i].triangleCount = 0;
  42514. }
  42515. var newReferences = new Array(this.triangles.length * 3);
  42516. for (i = 0; i < this.triangles.length; ++i) {
  42517. t = this.triangles[i];
  42518. for (j = 0; j < 3; ++j) {
  42519. v = t.vertices[j];
  42520. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  42521. v.triangleCount++;
  42522. }
  42523. }
  42524. this.references = newReferences;
  42525. if (identifyBorders) {
  42526. this.identifyBorder();
  42527. }
  42528. };
  42529. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  42530. var x = point.x;
  42531. var y = point.y;
  42532. var z = point.z;
  42533. 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
  42534. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  42535. };
  42536. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  42537. var q = vertex1.q.add(vertex2.q);
  42538. var border = vertex1.isBorder && vertex2.isBorder;
  42539. var error = 0;
  42540. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  42541. if (qDet !== 0 && !border) {
  42542. if (!pointResult) {
  42543. pointResult = BABYLON.Vector3.Zero();
  42544. }
  42545. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  42546. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  42547. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  42548. error = this.vertexError(q, pointResult);
  42549. }
  42550. else {
  42551. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  42552. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  42553. var error1 = this.vertexError(q, vertex1.position);
  42554. var error2 = this.vertexError(q, vertex2.position);
  42555. var error3 = this.vertexError(q, p3);
  42556. error = Math.min(error1, error2, error3);
  42557. if (error === error1) {
  42558. if (pointResult) {
  42559. pointResult.copyFrom(vertex1.position);
  42560. }
  42561. }
  42562. else if (error === error2) {
  42563. if (pointResult) {
  42564. pointResult.copyFrom(vertex2.position);
  42565. }
  42566. }
  42567. else {
  42568. if (pointResult) {
  42569. pointResult.copyFrom(p3);
  42570. }
  42571. }
  42572. }
  42573. return error;
  42574. };
  42575. return QuadraticErrorSimplification;
  42576. }());
  42577. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  42578. })(BABYLON || (BABYLON = {}));
  42579. //# sourceMappingURL=babylon.meshSimplification.js.map
  42580. var BABYLON;
  42581. (function (BABYLON) {
  42582. var serializedGeometries = [];
  42583. var serializeGeometry = function (geometry, serializationGeometries) {
  42584. if (serializedGeometries[geometry.id]) {
  42585. return;
  42586. }
  42587. if (geometry.doNotSerialize) {
  42588. return;
  42589. }
  42590. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  42591. serializationGeometries.boxes.push(geometry.serialize());
  42592. }
  42593. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  42594. serializationGeometries.spheres.push(geometry.serialize());
  42595. }
  42596. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  42597. serializationGeometries.cylinders.push(geometry.serialize());
  42598. }
  42599. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  42600. serializationGeometries.toruses.push(geometry.serialize());
  42601. }
  42602. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  42603. serializationGeometries.grounds.push(geometry.serialize());
  42604. }
  42605. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  42606. serializationGeometries.planes.push(geometry.serialize());
  42607. }
  42608. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  42609. serializationGeometries.torusKnots.push(geometry.serialize());
  42610. }
  42611. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  42612. throw new Error("Unknown primitive type");
  42613. }
  42614. else {
  42615. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  42616. }
  42617. serializedGeometries[geometry.id] = true;
  42618. };
  42619. var serializeMesh = function (mesh, serializationScene) {
  42620. var serializationObject = {};
  42621. serializationObject.name = mesh.name;
  42622. serializationObject.id = mesh.id;
  42623. if (BABYLON.Tags.HasTags(mesh)) {
  42624. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  42625. }
  42626. serializationObject.position = mesh.position.asArray();
  42627. if (mesh.rotationQuaternion) {
  42628. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  42629. }
  42630. else if (mesh.rotation) {
  42631. serializationObject.rotation = mesh.rotation.asArray();
  42632. }
  42633. serializationObject.scaling = mesh.scaling.asArray();
  42634. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  42635. serializationObject.isEnabled = mesh.isEnabled();
  42636. serializationObject.isVisible = mesh.isVisible;
  42637. serializationObject.infiniteDistance = mesh.infiniteDistance;
  42638. serializationObject.pickable = mesh.isPickable;
  42639. serializationObject.receiveShadows = mesh.receiveShadows;
  42640. serializationObject.billboardMode = mesh.billboardMode;
  42641. serializationObject.visibility = mesh.visibility;
  42642. serializationObject.checkCollisions = mesh.checkCollisions;
  42643. serializationObject.isBlocker = mesh.isBlocker;
  42644. // Parent
  42645. if (mesh.parent) {
  42646. serializationObject.parentId = mesh.parent.id;
  42647. }
  42648. // Geometry
  42649. var geometry = mesh._geometry;
  42650. if (geometry) {
  42651. var geometryId = geometry.id;
  42652. serializationObject.geometryId = geometryId;
  42653. if (!mesh.getScene().getGeometryByID(geometryId)) {
  42654. // 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
  42655. serializeGeometry(geometry, serializationScene.geometries);
  42656. }
  42657. // SubMeshes
  42658. serializationObject.subMeshes = [];
  42659. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42660. var subMesh = mesh.subMeshes[subIndex];
  42661. serializationObject.subMeshes.push({
  42662. materialIndex: subMesh.materialIndex,
  42663. verticesStart: subMesh.verticesStart,
  42664. verticesCount: subMesh.verticesCount,
  42665. indexStart: subMesh.indexStart,
  42666. indexCount: subMesh.indexCount
  42667. });
  42668. }
  42669. }
  42670. // Material
  42671. if (mesh.material) {
  42672. serializationObject.materialId = mesh.material.id;
  42673. }
  42674. else {
  42675. mesh.material = null;
  42676. }
  42677. // Skeleton
  42678. if (mesh.skeleton) {
  42679. serializationObject.skeletonId = mesh.skeleton.id;
  42680. }
  42681. // Physics
  42682. //TODO implement correct serialization for physics impostors.
  42683. if (mesh.getPhysicsImpostor()) {
  42684. serializationObject.physicsMass = mesh.getPhysicsMass();
  42685. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  42686. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  42687. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  42688. }
  42689. // Metadata
  42690. if (mesh.metadata) {
  42691. serializationObject.metadata = mesh.metadata;
  42692. }
  42693. // Instances
  42694. serializationObject.instances = [];
  42695. for (var index = 0; index < mesh.instances.length; index++) {
  42696. var instance = mesh.instances[index];
  42697. var serializationInstance = {
  42698. name: instance.name,
  42699. position: instance.position.asArray(),
  42700. scaling: instance.scaling.asArray()
  42701. };
  42702. if (instance.rotationQuaternion) {
  42703. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  42704. }
  42705. else if (instance.rotation) {
  42706. serializationInstance.rotation = instance.rotation.asArray();
  42707. }
  42708. serializationObject.instances.push(serializationInstance);
  42709. // Animations
  42710. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  42711. serializationInstance.ranges = instance.serializeAnimationRanges();
  42712. }
  42713. // Animations
  42714. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  42715. serializationObject.ranges = mesh.serializeAnimationRanges();
  42716. // Layer mask
  42717. serializationObject.layerMask = mesh.layerMask;
  42718. // Alpha
  42719. serializationObject.alphaIndex = mesh.alphaIndex;
  42720. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  42721. // Overlay
  42722. serializationObject.overlayAlpha = mesh.overlayAlpha;
  42723. serializationObject.overlayColor = mesh.overlayColor.asArray();
  42724. serializationObject.renderOverlay = mesh.renderOverlay;
  42725. // Fog
  42726. serializationObject.applyFog = mesh.applyFog;
  42727. // Action Manager
  42728. if (mesh.actionManager) {
  42729. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  42730. }
  42731. return serializationObject;
  42732. };
  42733. var finalizeSingleMesh = function (mesh, serializationObject) {
  42734. //only works if the mesh is already loaded
  42735. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42736. //serialize material
  42737. if (mesh.material) {
  42738. if (mesh.material instanceof BABYLON.StandardMaterial) {
  42739. serializationObject.materials = serializationObject.materials || [];
  42740. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42741. serializationObject.materials.push(mesh.material.serialize());
  42742. }
  42743. }
  42744. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  42745. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  42746. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42747. serializationObject.multiMaterials.push(mesh.material.serialize());
  42748. }
  42749. }
  42750. }
  42751. //serialize geometry
  42752. var geometry = mesh._geometry;
  42753. if (geometry) {
  42754. if (!serializationObject.geometries) {
  42755. serializationObject.geometries = {};
  42756. serializationObject.geometries.boxes = [];
  42757. serializationObject.geometries.spheres = [];
  42758. serializationObject.geometries.cylinders = [];
  42759. serializationObject.geometries.toruses = [];
  42760. serializationObject.geometries.grounds = [];
  42761. serializationObject.geometries.planes = [];
  42762. serializationObject.geometries.torusKnots = [];
  42763. serializationObject.geometries.vertexData = [];
  42764. }
  42765. serializeGeometry(geometry, serializationObject.geometries);
  42766. }
  42767. // Skeletons
  42768. if (mesh.skeleton) {
  42769. serializationObject.skeletons = serializationObject.skeletons || [];
  42770. serializationObject.skeletons.push(mesh.skeleton.serialize());
  42771. }
  42772. //serialize the actual mesh
  42773. serializationObject.meshes = serializationObject.meshes || [];
  42774. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42775. }
  42776. };
  42777. var SceneSerializer = (function () {
  42778. function SceneSerializer() {
  42779. }
  42780. SceneSerializer.ClearCache = function () {
  42781. serializedGeometries = [];
  42782. };
  42783. SceneSerializer.Serialize = function (scene) {
  42784. var serializationObject = {};
  42785. // Scene
  42786. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  42787. serializationObject.autoClear = scene.autoClear;
  42788. serializationObject.clearColor = scene.clearColor.asArray();
  42789. serializationObject.ambientColor = scene.ambientColor.asArray();
  42790. serializationObject.gravity = scene.gravity.asArray();
  42791. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  42792. serializationObject.workerCollisions = scene.workerCollisions;
  42793. // Fog
  42794. if (scene.fogMode && scene.fogMode !== 0) {
  42795. serializationObject.fogMode = scene.fogMode;
  42796. serializationObject.fogColor = scene.fogColor.asArray();
  42797. serializationObject.fogStart = scene.fogStart;
  42798. serializationObject.fogEnd = scene.fogEnd;
  42799. serializationObject.fogDensity = scene.fogDensity;
  42800. }
  42801. //Physics
  42802. if (scene.isPhysicsEnabled()) {
  42803. serializationObject.physicsEnabled = true;
  42804. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  42805. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  42806. }
  42807. // Metadata
  42808. if (scene.metadata) {
  42809. serializationObject.metadata = scene.metadata;
  42810. }
  42811. // Lights
  42812. serializationObject.lights = [];
  42813. var index;
  42814. var light;
  42815. for (index = 0; index < scene.lights.length; index++) {
  42816. light = scene.lights[index];
  42817. if (!light.doNotSerialize) {
  42818. serializationObject.lights.push(light.serialize());
  42819. }
  42820. }
  42821. // Cameras
  42822. serializationObject.cameras = [];
  42823. for (index = 0; index < scene.cameras.length; index++) {
  42824. var camera = scene.cameras[index];
  42825. if (!camera.doNotSerialize) {
  42826. serializationObject.cameras.push(camera.serialize());
  42827. }
  42828. }
  42829. if (scene.activeCamera) {
  42830. serializationObject.activeCameraID = scene.activeCamera.id;
  42831. }
  42832. // Animations
  42833. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  42834. // Materials
  42835. serializationObject.materials = [];
  42836. serializationObject.multiMaterials = [];
  42837. var material;
  42838. for (index = 0; index < scene.materials.length; index++) {
  42839. material = scene.materials[index];
  42840. if (!material.doNotSerialize) {
  42841. serializationObject.materials.push(material.serialize());
  42842. }
  42843. }
  42844. // MultiMaterials
  42845. serializationObject.multiMaterials = [];
  42846. for (index = 0; index < scene.multiMaterials.length; index++) {
  42847. var multiMaterial = scene.multiMaterials[index];
  42848. serializationObject.multiMaterials.push(multiMaterial.serialize());
  42849. }
  42850. // Skeletons
  42851. serializationObject.skeletons = [];
  42852. for (index = 0; index < scene.skeletons.length; index++) {
  42853. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  42854. }
  42855. // Geometries
  42856. serializationObject.geometries = {};
  42857. serializationObject.geometries.boxes = [];
  42858. serializationObject.geometries.spheres = [];
  42859. serializationObject.geometries.cylinders = [];
  42860. serializationObject.geometries.toruses = [];
  42861. serializationObject.geometries.grounds = [];
  42862. serializationObject.geometries.planes = [];
  42863. serializationObject.geometries.torusKnots = [];
  42864. serializationObject.geometries.vertexData = [];
  42865. serializedGeometries = [];
  42866. var geometries = scene.getGeometries();
  42867. for (index = 0; index < geometries.length; index++) {
  42868. var geometry = geometries[index];
  42869. if (geometry.isReady()) {
  42870. serializeGeometry(geometry, serializationObject.geometries);
  42871. }
  42872. }
  42873. // Meshes
  42874. serializationObject.meshes = [];
  42875. for (index = 0; index < scene.meshes.length; index++) {
  42876. var abstractMesh = scene.meshes[index];
  42877. if (abstractMesh instanceof BABYLON.Mesh) {
  42878. var mesh = abstractMesh;
  42879. if (!mesh.doNotSerialize) {
  42880. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42881. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42882. }
  42883. }
  42884. }
  42885. }
  42886. // Particles Systems
  42887. serializationObject.particleSystems = [];
  42888. for (index = 0; index < scene.particleSystems.length; index++) {
  42889. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  42890. }
  42891. // Lens flares
  42892. serializationObject.lensFlareSystems = [];
  42893. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  42894. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  42895. }
  42896. // Shadows
  42897. serializationObject.shadowGenerators = [];
  42898. for (index = 0; index < scene.lights.length; index++) {
  42899. light = scene.lights[index];
  42900. var shadowGenerator = light.getShadowGenerator();
  42901. // Only support serialization for official generator so far.
  42902. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  42903. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  42904. }
  42905. }
  42906. // Action Manager
  42907. if (scene.actionManager) {
  42908. serializationObject.actions = scene.actionManager.serialize("scene");
  42909. }
  42910. // Audio
  42911. serializationObject.sounds = [];
  42912. for (index = 0; index < scene.soundTracks.length; index++) {
  42913. var soundtrack = scene.soundTracks[index];
  42914. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  42915. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  42916. }
  42917. }
  42918. return serializationObject;
  42919. };
  42920. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  42921. if (withParents === void 0) { withParents = false; }
  42922. if (withChildren === void 0) { withChildren = false; }
  42923. var serializationObject = {};
  42924. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  42925. if (withParents || withChildren) {
  42926. //deliberate for loop! not for each, appended should be processed as well.
  42927. for (var i = 0; i < toSerialize.length; ++i) {
  42928. if (withChildren) {
  42929. toSerialize[i].getDescendants().forEach(function (node) {
  42930. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  42931. toSerialize.push(node);
  42932. }
  42933. });
  42934. }
  42935. //make sure the array doesn't contain the object already
  42936. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  42937. toSerialize.push(toSerialize[i].parent);
  42938. }
  42939. }
  42940. }
  42941. toSerialize.forEach(function (mesh) {
  42942. finalizeSingleMesh(mesh, serializationObject);
  42943. });
  42944. return serializationObject;
  42945. };
  42946. return SceneSerializer;
  42947. }());
  42948. BABYLON.SceneSerializer = SceneSerializer;
  42949. })(BABYLON || (BABYLON = {}));
  42950. //# sourceMappingURL=babylon.sceneSerializer.js.map
  42951. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  42952. // Huge respect for a such great lib.
  42953. // Earcut license:
  42954. // Copyright (c) 2016, Mapbox
  42955. //
  42956. // Permission to use, copy, modify, and/or distribute this software for any purpose
  42957. // with or without fee is hereby granted, provided that the above copyright notice
  42958. // and this permission notice appear in all copies.
  42959. //
  42960. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  42961. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  42962. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  42963. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  42964. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  42965. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  42966. // THIS SOFTWARE.
  42967. var Earcut;
  42968. (function (Earcut) {
  42969. /**
  42970. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  42971. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  42972. * @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).
  42973. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  42974. */
  42975. function earcut(data, holeIndices, dim) {
  42976. dim = dim || 2;
  42977. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  42978. if (!outerNode)
  42979. return triangles;
  42980. var minX, minY, maxX, maxY, x, y, size;
  42981. if (hasHoles)
  42982. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  42983. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  42984. if (data.length > 80 * dim) {
  42985. minX = maxX = data[0];
  42986. minY = maxY = data[1];
  42987. for (var i = dim; i < outerLen; i += dim) {
  42988. x = data[i];
  42989. y = data[i + 1];
  42990. if (x < minX)
  42991. minX = x;
  42992. if (y < minY)
  42993. minY = y;
  42994. if (x > maxX)
  42995. maxX = x;
  42996. if (y > maxY)
  42997. maxY = y;
  42998. }
  42999. // minX, minY and size are later used to transform coords into integers for z-order calculation
  43000. size = Math.max(maxX - minX, maxY - minY);
  43001. }
  43002. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  43003. return triangles;
  43004. }
  43005. Earcut.earcut = earcut;
  43006. // create a circular doubly linked list from polygon points in the specified winding order
  43007. function linkedList(data, start, end, dim, clockwise) {
  43008. var i, last;
  43009. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  43010. for (i = start; i < end; i += dim)
  43011. last = insertNode(i, data[i], data[i + 1], last);
  43012. }
  43013. else {
  43014. for (i = end - dim; i >= start; i -= dim)
  43015. last = insertNode(i, data[i], data[i + 1], last);
  43016. }
  43017. if (last && equals(last, last.next)) {
  43018. removeNode(last);
  43019. last = last.next;
  43020. }
  43021. return last;
  43022. }
  43023. // eliminate colinear or duplicate points
  43024. function filterPoints(start, end) {
  43025. if (!start)
  43026. return start;
  43027. if (!end)
  43028. end = start;
  43029. var p = start, again;
  43030. do {
  43031. again = false;
  43032. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  43033. removeNode(p);
  43034. p = end = p.prev;
  43035. if (p === p.next)
  43036. return null;
  43037. again = true;
  43038. }
  43039. else {
  43040. p = p.next;
  43041. }
  43042. } while (again || p !== end);
  43043. return end;
  43044. }
  43045. // main ear slicing loop which triangulates a polygon (given as a linked list)
  43046. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  43047. if (!ear)
  43048. return;
  43049. // interlink polygon nodes in z-order
  43050. if (!pass && size)
  43051. indexCurve(ear, minX, minY, size);
  43052. var stop = ear, prev, next;
  43053. // iterate through ears, slicing them one by one
  43054. while (ear.prev !== ear.next) {
  43055. prev = ear.prev;
  43056. next = ear.next;
  43057. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  43058. // cut off the triangle
  43059. triangles.push(prev.i / dim);
  43060. triangles.push(ear.i / dim);
  43061. triangles.push(next.i / dim);
  43062. removeNode(ear);
  43063. // skipping the next vertice leads to less sliver triangles
  43064. ear = next.next;
  43065. stop = next.next;
  43066. continue;
  43067. }
  43068. ear = next;
  43069. // if we looped through the whole remaining polygon and can't find any more ears
  43070. if (ear === stop) {
  43071. // try filtering points and slicing again
  43072. if (!pass) {
  43073. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  43074. }
  43075. else if (pass === 1) {
  43076. ear = cureLocalIntersections(ear, triangles, dim);
  43077. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43078. }
  43079. else if (pass === 2) {
  43080. splitEarcut(ear, triangles, dim, minX, minY, size);
  43081. }
  43082. break;
  43083. }
  43084. }
  43085. }
  43086. // check whether a polygon node forms a valid ear with adjacent nodes
  43087. function isEar(ear) {
  43088. var a = ear.prev, b = ear, c = ear.next;
  43089. if (area(a, b, c) >= 0)
  43090. return false; // reflex, can't be an ear
  43091. // now make sure we don't have other points inside the potential ear
  43092. var p = ear.next.next;
  43093. while (p !== ear.prev) {
  43094. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43095. area(p.prev, p, p.next) >= 0)
  43096. return false;
  43097. p = p.next;
  43098. }
  43099. return true;
  43100. }
  43101. function isEarHashed(ear, minX, minY, size) {
  43102. var a = ear.prev, b = ear, c = ear.next;
  43103. if (area(a, b, c) >= 0)
  43104. return false; // reflex, can't be an ear
  43105. // triangle bbox; min & max are calculated like this for speed
  43106. 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);
  43107. // z-order range for the current triangle bbox;
  43108. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43109. // first look for points inside the triangle in increasing z-order
  43110. var p = ear.nextZ;
  43111. while (p && p.z <= maxZ) {
  43112. if (p !== ear.prev &&
  43113. p !== ear.next &&
  43114. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43115. area(p.prev, p, p.next) >= 0)
  43116. return false;
  43117. p = p.nextZ;
  43118. }
  43119. // then look for points in decreasing z-order
  43120. p = ear.prevZ;
  43121. while (p && p.z >= minZ) {
  43122. if (p !== ear.prev &&
  43123. p !== ear.next &&
  43124. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43125. area(p.prev, p, p.next) >= 0)
  43126. return false;
  43127. p = p.prevZ;
  43128. }
  43129. return true;
  43130. }
  43131. // go through all polygon nodes and cure small local self-intersections
  43132. function cureLocalIntersections(start, triangles, dim) {
  43133. var p = start;
  43134. do {
  43135. var a = p.prev, b = p.next.next;
  43136. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43137. triangles.push(a.i / dim);
  43138. triangles.push(p.i / dim);
  43139. triangles.push(b.i / dim);
  43140. // remove two nodes involved
  43141. removeNode(p);
  43142. removeNode(p.next);
  43143. p = start = b;
  43144. }
  43145. p = p.next;
  43146. } while (p !== start);
  43147. return p;
  43148. }
  43149. // try splitting polygon into two and triangulate them independently
  43150. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43151. // look for a valid diagonal that divides the polygon into two
  43152. var a = start;
  43153. do {
  43154. var b = a.next.next;
  43155. while (b !== a.prev) {
  43156. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43157. // split the polygon in two by the diagonal
  43158. var c = splitPolygon(a, b);
  43159. // filter colinear points around the cuts
  43160. a = filterPoints(a, a.next);
  43161. c = filterPoints(c, c.next);
  43162. // run earcut on each half
  43163. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43164. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43165. return;
  43166. }
  43167. b = b.next;
  43168. }
  43169. a = a.next;
  43170. } while (a !== start);
  43171. }
  43172. // link every hole into the outer loop, producing a single-ring polygon without holes
  43173. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43174. var queue = [], i, len, start, end, list;
  43175. for (i = 0, len = holeIndices.length; i < len; i++) {
  43176. start = holeIndices[i] * dim;
  43177. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43178. list = linkedList(data, start, end, dim, false);
  43179. if (list === list.next)
  43180. list.steiner = true;
  43181. queue.push(getLeftmost(list));
  43182. }
  43183. queue.sort(compareX);
  43184. // process holes from left to right
  43185. for (i = 0; i < queue.length; i++) {
  43186. eliminateHole(queue[i], outerNode);
  43187. outerNode = filterPoints(outerNode, outerNode.next);
  43188. }
  43189. return outerNode;
  43190. }
  43191. function compareX(a, b) {
  43192. return a.x - b.x;
  43193. }
  43194. // find a bridge between vertices that connects hole with an outer ring and and link it
  43195. function eliminateHole(hole, outerNode) {
  43196. outerNode = findHoleBridge(hole, outerNode);
  43197. if (outerNode) {
  43198. var b = splitPolygon(outerNode, hole);
  43199. filterPoints(b, b.next);
  43200. }
  43201. }
  43202. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43203. function findHoleBridge(hole, outerNode) {
  43204. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43205. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43206. // segment's endpoint with lesser x will be potential connection point
  43207. do {
  43208. if (hy <= p.y && hy >= p.next.y) {
  43209. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43210. if (x <= hx && x > qx) {
  43211. qx = x;
  43212. if (x === hx) {
  43213. if (hy === p.y)
  43214. return p;
  43215. if (hy === p.next.y)
  43216. return p.next;
  43217. }
  43218. m = p.x < p.next.x ? p : p.next;
  43219. }
  43220. }
  43221. p = p.next;
  43222. } while (p !== outerNode);
  43223. if (!m)
  43224. return null;
  43225. if (hx === qx)
  43226. return m.prev; // hole touches outer segment; pick lower endpoint
  43227. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43228. // if there are no points found, we have a valid connection;
  43229. // otherwise choose the point of the minimum angle with the ray as connection point
  43230. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43231. p = m.next;
  43232. while (p !== stop) {
  43233. if (hx >= p.x &&
  43234. p.x >= mx &&
  43235. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43236. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43237. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43238. m = p;
  43239. tanMin = tan;
  43240. }
  43241. }
  43242. p = p.next;
  43243. }
  43244. return m;
  43245. }
  43246. // interlink polygon nodes in z-order
  43247. function indexCurve(start, minX, minY, size) {
  43248. var p = start;
  43249. do {
  43250. if (p.z === null)
  43251. p.z = zOrder(p.x, p.y, minX, minY, size);
  43252. p.prevZ = p.prev;
  43253. p.nextZ = p.next;
  43254. p = p.next;
  43255. } while (p !== start);
  43256. p.prevZ.nextZ = null;
  43257. p.prevZ = null;
  43258. sortLinked(p);
  43259. }
  43260. // Simon Tatham's linked list merge sort algorithm
  43261. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43262. function sortLinked(list) {
  43263. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43264. do {
  43265. p = list;
  43266. list = null;
  43267. tail = null;
  43268. numMerges = 0;
  43269. while (p) {
  43270. numMerges++;
  43271. q = p;
  43272. pSize = 0;
  43273. for (i = 0; i < inSize; i++) {
  43274. pSize++;
  43275. q = q.nextZ;
  43276. if (!q)
  43277. break;
  43278. }
  43279. qSize = inSize;
  43280. while (pSize > 0 || (qSize > 0 && q)) {
  43281. if (pSize === 0) {
  43282. e = q;
  43283. q = q.nextZ;
  43284. qSize--;
  43285. }
  43286. else if (qSize === 0 || !q) {
  43287. e = p;
  43288. p = p.nextZ;
  43289. pSize--;
  43290. }
  43291. else if (p.z <= q.z) {
  43292. e = p;
  43293. p = p.nextZ;
  43294. pSize--;
  43295. }
  43296. else {
  43297. e = q;
  43298. q = q.nextZ;
  43299. qSize--;
  43300. }
  43301. if (tail)
  43302. tail.nextZ = e;
  43303. else
  43304. list = e;
  43305. e.prevZ = tail;
  43306. tail = e;
  43307. }
  43308. p = q;
  43309. }
  43310. tail.nextZ = null;
  43311. inSize *= 2;
  43312. } while (numMerges > 1);
  43313. return list;
  43314. }
  43315. // z-order of a point given coords and size of the data bounding box
  43316. function zOrder(x, y, minX, minY, size) {
  43317. // coords are transformed into non-negative 15-bit integer range
  43318. x = 32767 * (x - minX) / size;
  43319. y = 32767 * (y - minY) / size;
  43320. x = (x | (x << 8)) & 0x00FF00FF;
  43321. x = (x | (x << 4)) & 0x0F0F0F0F;
  43322. x = (x | (x << 2)) & 0x33333333;
  43323. x = (x | (x << 1)) & 0x55555555;
  43324. y = (y | (y << 8)) & 0x00FF00FF;
  43325. y = (y | (y << 4)) & 0x0F0F0F0F;
  43326. y = (y | (y << 2)) & 0x33333333;
  43327. y = (y | (y << 1)) & 0x55555555;
  43328. return x | (y << 1);
  43329. }
  43330. // find the leftmost node of a polygon ring
  43331. function getLeftmost(start) {
  43332. var p = start, leftmost = start;
  43333. do {
  43334. if (p.x < leftmost.x)
  43335. leftmost = p;
  43336. p = p.next;
  43337. } while (p !== start);
  43338. return leftmost;
  43339. }
  43340. // check if a point lies within a convex triangle
  43341. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43342. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43343. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43344. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43345. }
  43346. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43347. function isValidDiagonal(a, b) {
  43348. return a.next.i !== b.i &&
  43349. a.prev.i !== b.i &&
  43350. !intersectsPolygon(a, b) &&
  43351. locallyInside(a, b) &&
  43352. locallyInside(b, a) &&
  43353. middleInside(a, b);
  43354. }
  43355. // signed area of a triangle
  43356. function area(p, q, r) {
  43357. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43358. }
  43359. // check if two points are equal
  43360. function equals(p1, p2) {
  43361. return p1.x === p2.x && p1.y === p2.y;
  43362. }
  43363. // check if two segments intersect
  43364. function intersects(p1, q1, p2, q2) {
  43365. if ((equals(p1, q1) && equals(p2, q2)) ||
  43366. (equals(p1, q2) && equals(p2, q1)))
  43367. return true;
  43368. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43369. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43370. }
  43371. // check if a polygon diagonal intersects any polygon segments
  43372. function intersectsPolygon(a, b) {
  43373. var p = a;
  43374. do {
  43375. if (p.i !== a.i &&
  43376. p.next.i !== a.i &&
  43377. p.i !== b.i &&
  43378. p.next.i !== b.i &&
  43379. intersects(p, p.next, a, b))
  43380. return true;
  43381. p = p.next;
  43382. } while (p !== a);
  43383. return false;
  43384. }
  43385. // check if a polygon diagonal is locally inside the polygon
  43386. function locallyInside(a, b) {
  43387. return area(a.prev, a, a.next) < 0
  43388. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43389. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43390. }
  43391. // check if the middle point of a polygon diagonal is inside the polygon
  43392. function middleInside(a, b) {
  43393. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43394. do {
  43395. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43396. inside = !inside;
  43397. p = p.next;
  43398. } while (p !== a);
  43399. return inside;
  43400. }
  43401. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43402. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43403. function splitPolygon(a, b) {
  43404. 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;
  43405. a.next = b;
  43406. b.prev = a;
  43407. a2.next = an;
  43408. an.prev = a2;
  43409. b2.next = a2;
  43410. a2.prev = b2;
  43411. bp.next = b2;
  43412. b2.prev = bp;
  43413. return b2;
  43414. }
  43415. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43416. function insertNode(i, x, y, last) {
  43417. var p = new Node(i, x, y);
  43418. if (!last) {
  43419. p.prev = p;
  43420. p.next = p;
  43421. }
  43422. else {
  43423. p.next = last.next;
  43424. p.prev = last;
  43425. last.next.prev = p;
  43426. last.next = p;
  43427. }
  43428. return p;
  43429. }
  43430. function removeNode(p) {
  43431. p.next.prev = p.prev;
  43432. p.prev.next = p.next;
  43433. if (p.prevZ)
  43434. p.prevZ.nextZ = p.nextZ;
  43435. if (p.nextZ)
  43436. p.nextZ.prevZ = p.prevZ;
  43437. }
  43438. function Node(i, x, y) {
  43439. // vertice index in coordinates array
  43440. this.i = i;
  43441. // vertex coordinates
  43442. this.x = x;
  43443. this.y = y;
  43444. // previous and next vertice nodes in a polygon ring
  43445. this.prev = null;
  43446. this.next = null;
  43447. // z-order curve value
  43448. this.z = null;
  43449. // previous and next nodes in z-order
  43450. this.prevZ = null;
  43451. this.nextZ = null;
  43452. // indicates whether this is a steiner point
  43453. this.steiner = false;
  43454. }
  43455. /**
  43456. * return a percentage difference between the polygon area and its triangulation area;
  43457. * used to verify correctness of triangulation
  43458. */
  43459. function deviation(data, holeIndices, dim, triangles) {
  43460. var hasHoles = holeIndices && holeIndices.length;
  43461. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  43462. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  43463. if (hasHoles) {
  43464. for (var i = 0, len = holeIndices.length; i < len; i++) {
  43465. var start = holeIndices[i] * dim;
  43466. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43467. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  43468. }
  43469. }
  43470. var trianglesArea = 0;
  43471. for (i = 0; i < triangles.length; i += 3) {
  43472. var a = triangles[i] * dim;
  43473. var b = triangles[i + 1] * dim;
  43474. var c = triangles[i + 2] * dim;
  43475. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  43476. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  43477. }
  43478. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  43479. }
  43480. Earcut.deviation = deviation;
  43481. ;
  43482. function signedArea(data, start, end, dim) {
  43483. var sum = 0;
  43484. for (var i = start, j = end - dim; i < end; i += dim) {
  43485. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  43486. j = i;
  43487. }
  43488. return sum;
  43489. }
  43490. /**
  43491. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  43492. */
  43493. function flatten(data) {
  43494. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  43495. for (var i = 0; i < data.length; i++) {
  43496. for (var j = 0; j < data[i].length; j++) {
  43497. for (var d = 0; d < dim; d++)
  43498. result.vertices.push(data[i][j][d]);
  43499. }
  43500. if (i > 0) {
  43501. holeIndex += data[i - 1].length;
  43502. result.holes.push(holeIndex);
  43503. }
  43504. }
  43505. return result;
  43506. }
  43507. Earcut.flatten = flatten;
  43508. ;
  43509. })(Earcut || (Earcut = {}));
  43510. //# sourceMappingURL=babylon.earcut.js.map
  43511. var BABYLON;
  43512. (function (BABYLON) {
  43513. // Unique ID when we import meshes from Babylon to CSG
  43514. var currentCSGMeshId = 0;
  43515. // # class Vertex
  43516. // Represents a vertex of a polygon. Use your own vertex class instead of this
  43517. // one to provide additional features like texture coordinates and vertex
  43518. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  43519. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  43520. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  43521. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  43522. // is not used anywhere else.
  43523. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  43524. var Vertex = (function () {
  43525. function Vertex(pos, normal, uv) {
  43526. this.pos = pos;
  43527. this.normal = normal;
  43528. this.uv = uv;
  43529. }
  43530. Vertex.prototype.clone = function () {
  43531. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43532. };
  43533. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  43534. // orientation of a polygon is flipped.
  43535. Vertex.prototype.flip = function () {
  43536. this.normal = this.normal.scale(-1);
  43537. };
  43538. // Create a new vertex between this vertex and `other` by linearly
  43539. // interpolating all properties using a parameter of `t`. Subclasses should
  43540. // override this to interpolate additional properties.
  43541. Vertex.prototype.interpolate = function (other, t) {
  43542. 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));
  43543. };
  43544. return Vertex;
  43545. }());
  43546. // # class Plane
  43547. // Represents a plane in 3D space.
  43548. var Plane = (function () {
  43549. function Plane(normal, w) {
  43550. this.normal = normal;
  43551. this.w = w;
  43552. }
  43553. Plane.FromPoints = function (a, b, c) {
  43554. var v0 = c.subtract(a);
  43555. var v1 = b.subtract(a);
  43556. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  43557. return null;
  43558. }
  43559. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  43560. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  43561. };
  43562. Plane.prototype.clone = function () {
  43563. return new Plane(this.normal.clone(), this.w);
  43564. };
  43565. Plane.prototype.flip = function () {
  43566. this.normal.scaleInPlace(-1);
  43567. this.w = -this.w;
  43568. };
  43569. // Split `polygon` by this plane if needed, then put the polygon or polygon
  43570. // fragments in the appropriate lists. Coplanar polygons go into either
  43571. // `coplanarFront` or `coplanarBack` depending on their orientation with
  43572. // respect to this plane. Polygons in front or in back of this plane go into
  43573. // either `front` or `back`.
  43574. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  43575. var COPLANAR = 0;
  43576. var FRONT = 1;
  43577. var BACK = 2;
  43578. var SPANNING = 3;
  43579. // Classify each point as well as the entire polygon into one of the above
  43580. // four classes.
  43581. var polygonType = 0;
  43582. var types = [];
  43583. var i;
  43584. var t;
  43585. for (i = 0; i < polygon.vertices.length; i++) {
  43586. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  43587. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  43588. polygonType |= type;
  43589. types.push(type);
  43590. }
  43591. // Put the polygon in the correct list, splitting it when necessary.
  43592. switch (polygonType) {
  43593. case COPLANAR:
  43594. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  43595. break;
  43596. case FRONT:
  43597. front.push(polygon);
  43598. break;
  43599. case BACK:
  43600. back.push(polygon);
  43601. break;
  43602. case SPANNING:
  43603. var f = [], b = [];
  43604. for (i = 0; i < polygon.vertices.length; i++) {
  43605. var j = (i + 1) % polygon.vertices.length;
  43606. var ti = types[i], tj = types[j];
  43607. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  43608. if (ti !== BACK)
  43609. f.push(vi);
  43610. if (ti !== FRONT)
  43611. b.push(ti !== BACK ? vi.clone() : vi);
  43612. if ((ti | tj) === SPANNING) {
  43613. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  43614. var v = vi.interpolate(vj, t);
  43615. f.push(v);
  43616. b.push(v.clone());
  43617. }
  43618. }
  43619. var poly;
  43620. if (f.length >= 3) {
  43621. poly = new Polygon(f, polygon.shared);
  43622. if (poly.plane)
  43623. front.push(poly);
  43624. }
  43625. if (b.length >= 3) {
  43626. poly = new Polygon(b, polygon.shared);
  43627. if (poly.plane)
  43628. back.push(poly);
  43629. }
  43630. break;
  43631. }
  43632. };
  43633. return Plane;
  43634. }());
  43635. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  43636. // point is on the plane.
  43637. Plane.EPSILON = 1e-5;
  43638. // # class Polygon
  43639. // Represents a convex polygon. The vertices used to initialize a polygon must
  43640. // be coplanar and form a convex loop.
  43641. //
  43642. // Each convex polygon has a `shared` property, which is shared between all
  43643. // polygons that are clones of each other or were split from the same polygon.
  43644. // This can be used to define per-polygon properties (such as surface color).
  43645. var Polygon = (function () {
  43646. function Polygon(vertices, shared) {
  43647. this.vertices = vertices;
  43648. this.shared = shared;
  43649. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  43650. }
  43651. Polygon.prototype.clone = function () {
  43652. var vertices = this.vertices.map(function (v) { return v.clone(); });
  43653. return new Polygon(vertices, this.shared);
  43654. };
  43655. Polygon.prototype.flip = function () {
  43656. this.vertices.reverse().map(function (v) { v.flip(); });
  43657. this.plane.flip();
  43658. };
  43659. return Polygon;
  43660. }());
  43661. // # class Node
  43662. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  43663. // by picking a polygon to split along. That polygon (and all other coplanar
  43664. // polygons) are added directly to that node and the other polygons are added to
  43665. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  43666. // no distinction between internal and leaf nodes.
  43667. var Node = (function () {
  43668. function Node(polygons) {
  43669. this.plane = null;
  43670. this.front = null;
  43671. this.back = null;
  43672. this.polygons = [];
  43673. if (polygons) {
  43674. this.build(polygons);
  43675. }
  43676. }
  43677. Node.prototype.clone = function () {
  43678. var node = new Node();
  43679. node.plane = this.plane && this.plane.clone();
  43680. node.front = this.front && this.front.clone();
  43681. node.back = this.back && this.back.clone();
  43682. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  43683. return node;
  43684. };
  43685. // Convert solid space to empty space and empty space to solid space.
  43686. Node.prototype.invert = function () {
  43687. for (var i = 0; i < this.polygons.length; i++) {
  43688. this.polygons[i].flip();
  43689. }
  43690. if (this.plane) {
  43691. this.plane.flip();
  43692. }
  43693. if (this.front) {
  43694. this.front.invert();
  43695. }
  43696. if (this.back) {
  43697. this.back.invert();
  43698. }
  43699. var temp = this.front;
  43700. this.front = this.back;
  43701. this.back = temp;
  43702. };
  43703. // Recursively remove all polygons in `polygons` that are inside this BSP
  43704. // tree.
  43705. Node.prototype.clipPolygons = function (polygons) {
  43706. if (!this.plane)
  43707. return polygons.slice();
  43708. var front = [], back = [];
  43709. for (var i = 0; i < polygons.length; i++) {
  43710. this.plane.splitPolygon(polygons[i], front, back, front, back);
  43711. }
  43712. if (this.front) {
  43713. front = this.front.clipPolygons(front);
  43714. }
  43715. if (this.back) {
  43716. back = this.back.clipPolygons(back);
  43717. }
  43718. else {
  43719. back = [];
  43720. }
  43721. return front.concat(back);
  43722. };
  43723. // Remove all polygons in this BSP tree that are inside the other BSP tree
  43724. // `bsp`.
  43725. Node.prototype.clipTo = function (bsp) {
  43726. this.polygons = bsp.clipPolygons(this.polygons);
  43727. if (this.front)
  43728. this.front.clipTo(bsp);
  43729. if (this.back)
  43730. this.back.clipTo(bsp);
  43731. };
  43732. // Return a list of all polygons in this BSP tree.
  43733. Node.prototype.allPolygons = function () {
  43734. var polygons = this.polygons.slice();
  43735. if (this.front)
  43736. polygons = polygons.concat(this.front.allPolygons());
  43737. if (this.back)
  43738. polygons = polygons.concat(this.back.allPolygons());
  43739. return polygons;
  43740. };
  43741. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  43742. // new polygons are filtered down to the bottom of the tree and become new
  43743. // nodes there. Each set of polygons is partitioned using the first polygon
  43744. // (no heuristic is used to pick a good split).
  43745. Node.prototype.build = function (polygons) {
  43746. if (!polygons.length)
  43747. return;
  43748. if (!this.plane)
  43749. this.plane = polygons[0].plane.clone();
  43750. var front = [], back = [];
  43751. for (var i = 0; i < polygons.length; i++) {
  43752. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  43753. }
  43754. if (front.length) {
  43755. if (!this.front)
  43756. this.front = new Node();
  43757. this.front.build(front);
  43758. }
  43759. if (back.length) {
  43760. if (!this.back)
  43761. this.back = new Node();
  43762. this.back.build(back);
  43763. }
  43764. };
  43765. return Node;
  43766. }());
  43767. var CSG = (function () {
  43768. function CSG() {
  43769. this.polygons = new Array();
  43770. }
  43771. // Convert BABYLON.Mesh to BABYLON.CSG
  43772. CSG.FromMesh = function (mesh) {
  43773. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  43774. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  43775. if (mesh instanceof BABYLON.Mesh) {
  43776. mesh.computeWorldMatrix(true);
  43777. matrix = mesh.getWorldMatrix();
  43778. meshPosition = mesh.position.clone();
  43779. meshRotation = mesh.rotation.clone();
  43780. if (mesh.rotationQuaternion) {
  43781. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  43782. }
  43783. meshScaling = mesh.scaling.clone();
  43784. }
  43785. else {
  43786. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  43787. }
  43788. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43789. var subMeshes = mesh.subMeshes;
  43790. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  43791. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  43792. vertices = [];
  43793. for (var j = 0; j < 3; j++) {
  43794. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  43795. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  43796. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  43797. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  43798. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  43799. vertex = new Vertex(position, normal, uv);
  43800. vertices.push(vertex);
  43801. }
  43802. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  43803. // To handle the case of degenerated triangle
  43804. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  43805. if (polygon.plane)
  43806. polygons.push(polygon);
  43807. }
  43808. }
  43809. var csg = CSG.FromPolygons(polygons);
  43810. csg.matrix = matrix;
  43811. csg.position = meshPosition;
  43812. csg.rotation = meshRotation;
  43813. csg.scaling = meshScaling;
  43814. csg.rotationQuaternion = meshRotationQuaternion;
  43815. currentCSGMeshId++;
  43816. return csg;
  43817. };
  43818. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  43819. CSG.FromPolygons = function (polygons) {
  43820. var csg = new CSG();
  43821. csg.polygons = polygons;
  43822. return csg;
  43823. };
  43824. CSG.prototype.clone = function () {
  43825. var csg = new CSG();
  43826. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  43827. csg.copyTransformAttributes(this);
  43828. return csg;
  43829. };
  43830. CSG.prototype.toPolygons = function () {
  43831. return this.polygons;
  43832. };
  43833. CSG.prototype.union = function (csg) {
  43834. var a = new Node(this.clone().polygons);
  43835. var b = new Node(csg.clone().polygons);
  43836. a.clipTo(b);
  43837. b.clipTo(a);
  43838. b.invert();
  43839. b.clipTo(a);
  43840. b.invert();
  43841. a.build(b.allPolygons());
  43842. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43843. };
  43844. CSG.prototype.unionInPlace = function (csg) {
  43845. var a = new Node(this.polygons);
  43846. var b = new Node(csg.polygons);
  43847. a.clipTo(b);
  43848. b.clipTo(a);
  43849. b.invert();
  43850. b.clipTo(a);
  43851. b.invert();
  43852. a.build(b.allPolygons());
  43853. this.polygons = a.allPolygons();
  43854. };
  43855. CSG.prototype.subtract = function (csg) {
  43856. var a = new Node(this.clone().polygons);
  43857. var b = new Node(csg.clone().polygons);
  43858. a.invert();
  43859. a.clipTo(b);
  43860. b.clipTo(a);
  43861. b.invert();
  43862. b.clipTo(a);
  43863. b.invert();
  43864. a.build(b.allPolygons());
  43865. a.invert();
  43866. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43867. };
  43868. CSG.prototype.subtractInPlace = function (csg) {
  43869. var a = new Node(this.polygons);
  43870. var b = new Node(csg.polygons);
  43871. a.invert();
  43872. a.clipTo(b);
  43873. b.clipTo(a);
  43874. b.invert();
  43875. b.clipTo(a);
  43876. b.invert();
  43877. a.build(b.allPolygons());
  43878. a.invert();
  43879. this.polygons = a.allPolygons();
  43880. };
  43881. CSG.prototype.intersect = function (csg) {
  43882. var a = new Node(this.clone().polygons);
  43883. var b = new Node(csg.clone().polygons);
  43884. a.invert();
  43885. b.clipTo(a);
  43886. b.invert();
  43887. a.clipTo(b);
  43888. b.clipTo(a);
  43889. a.build(b.allPolygons());
  43890. a.invert();
  43891. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43892. };
  43893. CSG.prototype.intersectInPlace = function (csg) {
  43894. var a = new Node(this.polygons);
  43895. var b = new Node(csg.polygons);
  43896. a.invert();
  43897. b.clipTo(a);
  43898. b.invert();
  43899. a.clipTo(b);
  43900. b.clipTo(a);
  43901. a.build(b.allPolygons());
  43902. a.invert();
  43903. this.polygons = a.allPolygons();
  43904. };
  43905. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  43906. // not modified.
  43907. CSG.prototype.inverse = function () {
  43908. var csg = this.clone();
  43909. csg.inverseInPlace();
  43910. return csg;
  43911. };
  43912. CSG.prototype.inverseInPlace = function () {
  43913. this.polygons.map(function (p) { p.flip(); });
  43914. };
  43915. // This is used to keep meshes transformations so they can be restored
  43916. // when we build back a Babylon Mesh
  43917. // NB : All CSG operations are performed in world coordinates
  43918. CSG.prototype.copyTransformAttributes = function (csg) {
  43919. this.matrix = csg.matrix;
  43920. this.position = csg.position;
  43921. this.rotation = csg.rotation;
  43922. this.scaling = csg.scaling;
  43923. this.rotationQuaternion = csg.rotationQuaternion;
  43924. return this;
  43925. };
  43926. // Build Raw mesh from CSG
  43927. // Coordinates here are in world space
  43928. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  43929. var matrix = this.matrix.clone();
  43930. matrix.invert();
  43931. 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;
  43932. if (keepSubMeshes) {
  43933. // Sort Polygons, since subMeshes are indices range
  43934. polygons.sort(function (a, b) {
  43935. if (a.shared.meshId === b.shared.meshId) {
  43936. return a.shared.subMeshId - b.shared.subMeshId;
  43937. }
  43938. else {
  43939. return a.shared.meshId - b.shared.meshId;
  43940. }
  43941. });
  43942. }
  43943. for (var i = 0, il = polygons.length; i < il; i++) {
  43944. polygon = polygons[i];
  43945. // Building SubMeshes
  43946. if (!subMesh_dict[polygon.shared.meshId]) {
  43947. subMesh_dict[polygon.shared.meshId] = {};
  43948. }
  43949. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  43950. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  43951. indexStart: +Infinity,
  43952. indexEnd: -Infinity,
  43953. materialIndex: polygon.shared.materialIndex
  43954. };
  43955. }
  43956. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  43957. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  43958. polygonIndices[0] = 0;
  43959. polygonIndices[1] = j - 1;
  43960. polygonIndices[2] = j;
  43961. for (var k = 0; k < 3; k++) {
  43962. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  43963. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  43964. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  43965. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  43966. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  43967. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  43968. // Check if 2 points can be merged
  43969. if (!(typeof vertex_idx !== 'undefined' &&
  43970. normals[vertex_idx * 3] === localNormal.x &&
  43971. normals[vertex_idx * 3 + 1] === localNormal.y &&
  43972. normals[vertex_idx * 3 + 2] === localNormal.z &&
  43973. uvs[vertex_idx * 2] === uv.x &&
  43974. uvs[vertex_idx * 2 + 1] === uv.y)) {
  43975. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  43976. uvs.push(uv.x, uv.y);
  43977. normals.push(normal.x, normal.y, normal.z);
  43978. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  43979. }
  43980. indices.push(vertex_idx);
  43981. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  43982. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  43983. currentIndex++;
  43984. }
  43985. }
  43986. }
  43987. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  43988. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  43989. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  43990. mesh.setIndices(indices);
  43991. if (keepSubMeshes) {
  43992. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  43993. var materialIndexOffset = 0, materialMaxIndex;
  43994. mesh.subMeshes = new Array();
  43995. for (var m in subMesh_dict) {
  43996. materialMaxIndex = -1;
  43997. for (var sm in subMesh_dict[m]) {
  43998. subMesh_obj = subMesh_dict[m][sm];
  43999. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  44000. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  44001. }
  44002. materialIndexOffset += ++materialMaxIndex;
  44003. }
  44004. }
  44005. return mesh;
  44006. };
  44007. // Build Mesh from CSG taking material and transforms into account
  44008. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  44009. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  44010. mesh.material = material;
  44011. mesh.position.copyFrom(this.position);
  44012. mesh.rotation.copyFrom(this.rotation);
  44013. if (this.rotationQuaternion) {
  44014. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  44015. }
  44016. mesh.scaling.copyFrom(this.scaling);
  44017. mesh.computeWorldMatrix(true);
  44018. return mesh;
  44019. };
  44020. return CSG;
  44021. }());
  44022. BABYLON.CSG = CSG;
  44023. })(BABYLON || (BABYLON = {}));
  44024. //# sourceMappingURL=babylon.csg.js.map
  44025. var BABYLON;
  44026. (function (BABYLON) {
  44027. var VRDistortionCorrectionPostProcess = (function (_super) {
  44028. __extends(VRDistortionCorrectionPostProcess, _super);
  44029. //ANY
  44030. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  44031. var _this = _super.call(this, name, "vrDistortionCorrection", [
  44032. 'LensCenter',
  44033. 'Scale',
  44034. 'ScaleIn',
  44035. 'HmdWarpParam'
  44036. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  44037. _this._isRightEye = isRightEye;
  44038. _this._distortionFactors = vrMetrics.distortionK;
  44039. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  44040. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  44041. _this.onSizeChangedObservable.add(function () {
  44042. _this.aspectRatio = _this.width * .5 / _this.height;
  44043. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  44044. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  44045. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  44046. });
  44047. _this.onApplyObservable.add(function (effect) {
  44048. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  44049. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  44050. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  44051. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  44052. });
  44053. return _this;
  44054. }
  44055. return VRDistortionCorrectionPostProcess;
  44056. }(BABYLON.PostProcess));
  44057. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  44058. })(BABYLON || (BABYLON = {}));
  44059. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  44060. // Mainly based on these 2 articles :
  44061. // 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
  44062. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  44063. var BABYLON;
  44064. (function (BABYLON) {
  44065. var JoystickAxis;
  44066. (function (JoystickAxis) {
  44067. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  44068. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  44069. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44070. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44071. var VirtualJoystick = (function () {
  44072. function VirtualJoystick(leftJoystick) {
  44073. var _this = this;
  44074. if (leftJoystick) {
  44075. this._leftJoystick = true;
  44076. }
  44077. else {
  44078. this._leftJoystick = false;
  44079. }
  44080. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44081. VirtualJoystick._globalJoystickIndex++;
  44082. // By default left & right arrow keys are moving the X
  44083. // and up & down keys are moving the Y
  44084. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44085. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44086. this.reverseLeftRight = false;
  44087. this.reverseUpDown = false;
  44088. // collections of pointers
  44089. this._touches = new BABYLON.StringDictionary();
  44090. this.deltaPosition = BABYLON.Vector3.Zero();
  44091. this._joystickSensibility = 25;
  44092. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44093. this._rotationSpeed = 25;
  44094. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44095. this._rotateOnAxisRelativeToMesh = false;
  44096. this._onResize = function (evt) {
  44097. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44098. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44099. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44100. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44101. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44102. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44103. };
  44104. // injecting a canvas element on top of the canvas 3D game
  44105. if (!VirtualJoystick.vjCanvas) {
  44106. window.addEventListener("resize", this._onResize, false);
  44107. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44108. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44109. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44110. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44111. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44112. VirtualJoystick.vjCanvas.style.width = "100%";
  44113. VirtualJoystick.vjCanvas.style.height = "100%";
  44114. VirtualJoystick.vjCanvas.style.position = "absolute";
  44115. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44116. VirtualJoystick.vjCanvas.style.top = "0px";
  44117. VirtualJoystick.vjCanvas.style.left = "0px";
  44118. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44119. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44120. // Support for jQuery PEP polyfill
  44121. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44122. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44123. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44124. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44125. document.body.appendChild(VirtualJoystick.vjCanvas);
  44126. }
  44127. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44128. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44129. this.pressed = false;
  44130. // default joystick color
  44131. this._joystickColor = "cyan";
  44132. this._joystickPointerID = -1;
  44133. // current joystick position
  44134. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44135. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44136. // origin joystick position
  44137. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44138. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44139. this._onPointerDownHandlerRef = function (evt) {
  44140. _this._onPointerDown(evt);
  44141. };
  44142. this._onPointerMoveHandlerRef = function (evt) {
  44143. _this._onPointerMove(evt);
  44144. };
  44145. this._onPointerOutHandlerRef = function (evt) {
  44146. _this._onPointerUp(evt);
  44147. };
  44148. this._onPointerUpHandlerRef = function (evt) {
  44149. _this._onPointerUp(evt);
  44150. };
  44151. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44152. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44153. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44154. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44155. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44156. evt.preventDefault(); // Disables system menu
  44157. }, false);
  44158. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44159. }
  44160. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44161. this._joystickSensibility = newJoystickSensibility;
  44162. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44163. };
  44164. VirtualJoystick.prototype._onPointerDown = function (e) {
  44165. var positionOnScreenCondition;
  44166. e.preventDefault();
  44167. if (this._leftJoystick === true) {
  44168. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44169. }
  44170. else {
  44171. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44172. }
  44173. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44174. // First contact will be dedicated to the virtual joystick
  44175. this._joystickPointerID = e.pointerId;
  44176. this._joystickPointerStartPos.x = e.clientX;
  44177. this._joystickPointerStartPos.y = e.clientY;
  44178. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44179. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44180. this._deltaJoystickVector.x = 0;
  44181. this._deltaJoystickVector.y = 0;
  44182. this.pressed = true;
  44183. this._touches.add(e.pointerId.toString(), e);
  44184. }
  44185. else {
  44186. // You can only trigger the action buttons with a joystick declared
  44187. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44188. this._action();
  44189. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44190. }
  44191. }
  44192. };
  44193. VirtualJoystick.prototype._onPointerMove = function (e) {
  44194. // If the current pointer is the one associated to the joystick (first touch contact)
  44195. if (this._joystickPointerID == e.pointerId) {
  44196. this._joystickPointerPos.x = e.clientX;
  44197. this._joystickPointerPos.y = e.clientY;
  44198. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44199. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44200. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44201. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44202. switch (this._axisTargetedByLeftAndRight) {
  44203. case JoystickAxis.X:
  44204. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44205. break;
  44206. case JoystickAxis.Y:
  44207. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44208. break;
  44209. case JoystickAxis.Z:
  44210. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44211. break;
  44212. }
  44213. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44214. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44215. switch (this._axisTargetedByUpAndDown) {
  44216. case JoystickAxis.X:
  44217. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44218. break;
  44219. case JoystickAxis.Y:
  44220. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44221. break;
  44222. case JoystickAxis.Z:
  44223. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44224. break;
  44225. }
  44226. }
  44227. else {
  44228. var data = this._touches.get(e.pointerId.toString());
  44229. if (data) {
  44230. data.x = e.clientX;
  44231. data.y = e.clientY;
  44232. }
  44233. }
  44234. };
  44235. VirtualJoystick.prototype._onPointerUp = function (e) {
  44236. if (this._joystickPointerID == e.pointerId) {
  44237. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  44238. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  44239. this._joystickPointerID = -1;
  44240. this.pressed = false;
  44241. }
  44242. else {
  44243. var touch = this._touches.get(e.pointerId.toString());
  44244. if (touch) {
  44245. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44246. }
  44247. }
  44248. this._deltaJoystickVector.x = 0;
  44249. this._deltaJoystickVector.y = 0;
  44250. this._touches.remove(e.pointerId.toString());
  44251. };
  44252. /**
  44253. * Change the color of the virtual joystick
  44254. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44255. */
  44256. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44257. this._joystickColor = newColor;
  44258. };
  44259. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44260. this._action = action;
  44261. };
  44262. // Define which axis you'd like to control for left & right
  44263. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44264. switch (axis) {
  44265. case JoystickAxis.X:
  44266. case JoystickAxis.Y:
  44267. case JoystickAxis.Z:
  44268. this._axisTargetedByLeftAndRight = axis;
  44269. break;
  44270. default:
  44271. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44272. break;
  44273. }
  44274. };
  44275. // Define which axis you'd like to control for up & down
  44276. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44277. switch (axis) {
  44278. case JoystickAxis.X:
  44279. case JoystickAxis.Y:
  44280. case JoystickAxis.Z:
  44281. this._axisTargetedByUpAndDown = axis;
  44282. break;
  44283. default:
  44284. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44285. break;
  44286. }
  44287. };
  44288. VirtualJoystick.prototype._clearCanvas = function () {
  44289. if (this._leftJoystick) {
  44290. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44291. }
  44292. else {
  44293. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44294. }
  44295. };
  44296. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44297. var _this = this;
  44298. if (this.pressed) {
  44299. this._touches.forEach(function (touch) {
  44300. if (touch.pointerId === _this._joystickPointerID) {
  44301. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44302. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44303. VirtualJoystick.vjCanvasContext.beginPath();
  44304. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44305. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44306. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44307. VirtualJoystick.vjCanvasContext.stroke();
  44308. VirtualJoystick.vjCanvasContext.closePath();
  44309. VirtualJoystick.vjCanvasContext.beginPath();
  44310. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44311. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44312. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44313. VirtualJoystick.vjCanvasContext.stroke();
  44314. VirtualJoystick.vjCanvasContext.closePath();
  44315. VirtualJoystick.vjCanvasContext.beginPath();
  44316. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44317. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44318. VirtualJoystick.vjCanvasContext.stroke();
  44319. VirtualJoystick.vjCanvasContext.closePath();
  44320. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44321. }
  44322. else {
  44323. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44324. VirtualJoystick.vjCanvasContext.beginPath();
  44325. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44326. VirtualJoystick.vjCanvasContext.beginPath();
  44327. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44328. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44329. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44330. VirtualJoystick.vjCanvasContext.stroke();
  44331. VirtualJoystick.vjCanvasContext.closePath();
  44332. touch.prevX = touch.x;
  44333. touch.prevY = touch.y;
  44334. }
  44335. ;
  44336. });
  44337. }
  44338. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44339. };
  44340. VirtualJoystick.prototype.releaseCanvas = function () {
  44341. if (VirtualJoystick.vjCanvas) {
  44342. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44343. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44344. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44345. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44346. window.removeEventListener("resize", this._onResize);
  44347. document.body.removeChild(VirtualJoystick.vjCanvas);
  44348. VirtualJoystick.vjCanvas = null;
  44349. }
  44350. };
  44351. return VirtualJoystick;
  44352. }());
  44353. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44354. VirtualJoystick._globalJoystickIndex = 0;
  44355. BABYLON.VirtualJoystick = VirtualJoystick;
  44356. })(BABYLON || (BABYLON = {}));
  44357. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44358. var BABYLON;
  44359. (function (BABYLON) {
  44360. // We're mainly based on the logic defined into the FreeCamera code
  44361. var VirtualJoysticksCamera = (function (_super) {
  44362. __extends(VirtualJoysticksCamera, _super);
  44363. function VirtualJoysticksCamera(name, position, scene) {
  44364. var _this = _super.call(this, name, position, scene) || this;
  44365. _this.inputs.addVirtualJoystick();
  44366. return _this;
  44367. }
  44368. VirtualJoysticksCamera.prototype.getClassName = function () {
  44369. return "VirtualJoysticksCamera";
  44370. };
  44371. return VirtualJoysticksCamera;
  44372. }(BABYLON.FreeCamera));
  44373. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44374. })(BABYLON || (BABYLON = {}));
  44375. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44376. var BABYLON;
  44377. (function (BABYLON) {
  44378. var FreeCameraVirtualJoystickInput = (function () {
  44379. function FreeCameraVirtualJoystickInput() {
  44380. }
  44381. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44382. return this._leftjoystick;
  44383. };
  44384. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44385. return this._rightjoystick;
  44386. };
  44387. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44388. if (this._leftjoystick) {
  44389. var camera = this.camera;
  44390. var speed = camera._computeLocalCameraSpeed() * 50;
  44391. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44392. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44393. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44394. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44395. if (!this._leftjoystick.pressed) {
  44396. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44397. }
  44398. if (!this._rightjoystick.pressed) {
  44399. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44400. }
  44401. }
  44402. };
  44403. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44404. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44405. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44406. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44407. this._leftjoystick.setJoystickSensibility(0.15);
  44408. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44409. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44410. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44411. this._rightjoystick.reverseUpDown = true;
  44412. this._rightjoystick.setJoystickSensibility(0.05);
  44413. this._rightjoystick.setJoystickColor("yellow");
  44414. };
  44415. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44416. this._leftjoystick.releaseCanvas();
  44417. this._rightjoystick.releaseCanvas();
  44418. };
  44419. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44420. return "FreeCameraVirtualJoystickInput";
  44421. };
  44422. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44423. return "virtualJoystick";
  44424. };
  44425. return FreeCameraVirtualJoystickInput;
  44426. }());
  44427. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44428. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44429. })(BABYLON || (BABYLON = {}));
  44430. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44431. var BABYLON;
  44432. (function (BABYLON) {
  44433. var AnaglyphPostProcess = (function (_super) {
  44434. __extends(AnaglyphPostProcess, _super);
  44435. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44436. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  44437. _this._passedProcess = rigCameras[0]._rigPostProcess;
  44438. _this.onApplyObservable.add(function (effect) {
  44439. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44440. });
  44441. return _this;
  44442. }
  44443. return AnaglyphPostProcess;
  44444. }(BABYLON.PostProcess));
  44445. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44446. })(BABYLON || (BABYLON = {}));
  44447. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44448. var BABYLON;
  44449. (function (BABYLON) {
  44450. var OutlineRenderer = (function () {
  44451. function OutlineRenderer(scene) {
  44452. this._scene = scene;
  44453. }
  44454. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44455. var _this = this;
  44456. if (useOverlay === void 0) { useOverlay = false; }
  44457. var scene = this._scene;
  44458. var engine = this._scene.getEngine();
  44459. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44460. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  44461. return;
  44462. }
  44463. var mesh = subMesh.getRenderingMesh();
  44464. var material = subMesh.getMaterial();
  44465. engine.enableEffect(this._effect);
  44466. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  44467. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  44468. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44469. // Bones
  44470. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44471. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44472. }
  44473. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44474. // Alpha test
  44475. if (material && material.needAlphaTesting()) {
  44476. var alphaTexture = material.getAlphaTestTexture();
  44477. this._effect.setTexture("diffuseSampler", alphaTexture);
  44478. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44479. }
  44480. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  44481. };
  44482. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  44483. var defines = [];
  44484. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  44485. var mesh = subMesh.getMesh();
  44486. var material = subMesh.getMaterial();
  44487. // Alpha test
  44488. if (material && material.needAlphaTesting()) {
  44489. defines.push("#define ALPHATEST");
  44490. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44491. attribs.push(BABYLON.VertexBuffer.UVKind);
  44492. defines.push("#define UV1");
  44493. }
  44494. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44495. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44496. defines.push("#define UV2");
  44497. }
  44498. }
  44499. // Bones
  44500. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44501. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44502. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44503. if (mesh.numBoneInfluencers > 4) {
  44504. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44505. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44506. }
  44507. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44508. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44509. }
  44510. else {
  44511. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44512. }
  44513. // Instances
  44514. if (useInstances) {
  44515. defines.push("#define INSTANCES");
  44516. attribs.push("world0");
  44517. attribs.push("world1");
  44518. attribs.push("world2");
  44519. attribs.push("world3");
  44520. }
  44521. // Get correct effect
  44522. var join = defines.join("\n");
  44523. if (this._cachedDefines !== join) {
  44524. this._cachedDefines = join;
  44525. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  44526. }
  44527. return this._effect.isReady();
  44528. };
  44529. return OutlineRenderer;
  44530. }());
  44531. BABYLON.OutlineRenderer = OutlineRenderer;
  44532. })(BABYLON || (BABYLON = {}));
  44533. //# sourceMappingURL=babylon.outlineRenderer.js.map
  44534. var BABYLON;
  44535. (function (BABYLON) {
  44536. var MeshAssetTask = (function () {
  44537. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  44538. this.name = name;
  44539. this.meshesNames = meshesNames;
  44540. this.rootUrl = rootUrl;
  44541. this.sceneFilename = sceneFilename;
  44542. this.isCompleted = false;
  44543. }
  44544. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44545. var _this = this;
  44546. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  44547. _this.loadedMeshes = meshes;
  44548. _this.loadedParticleSystems = particleSystems;
  44549. _this.loadedSkeletons = skeletons;
  44550. _this.isCompleted = true;
  44551. if (_this.onSuccess) {
  44552. _this.onSuccess(_this);
  44553. }
  44554. onSuccess();
  44555. }, null, function () {
  44556. if (_this.onError) {
  44557. _this.onError(_this);
  44558. }
  44559. onError();
  44560. });
  44561. };
  44562. return MeshAssetTask;
  44563. }());
  44564. BABYLON.MeshAssetTask = MeshAssetTask;
  44565. var TextFileAssetTask = (function () {
  44566. function TextFileAssetTask(name, url) {
  44567. this.name = name;
  44568. this.url = url;
  44569. this.isCompleted = false;
  44570. }
  44571. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44572. var _this = this;
  44573. BABYLON.Tools.LoadFile(this.url, function (data) {
  44574. _this.text = data;
  44575. _this.isCompleted = true;
  44576. if (_this.onSuccess) {
  44577. _this.onSuccess(_this);
  44578. }
  44579. onSuccess();
  44580. }, null, scene.database, false, function () {
  44581. if (_this.onError) {
  44582. _this.onError(_this);
  44583. }
  44584. onError();
  44585. });
  44586. };
  44587. return TextFileAssetTask;
  44588. }());
  44589. BABYLON.TextFileAssetTask = TextFileAssetTask;
  44590. var BinaryFileAssetTask = (function () {
  44591. function BinaryFileAssetTask(name, url) {
  44592. this.name = name;
  44593. this.url = url;
  44594. this.isCompleted = false;
  44595. }
  44596. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44597. var _this = this;
  44598. BABYLON.Tools.LoadFile(this.url, function (data) {
  44599. _this.data = data;
  44600. _this.isCompleted = true;
  44601. if (_this.onSuccess) {
  44602. _this.onSuccess(_this);
  44603. }
  44604. onSuccess();
  44605. }, null, scene.database, true, function () {
  44606. if (_this.onError) {
  44607. _this.onError(_this);
  44608. }
  44609. onError();
  44610. });
  44611. };
  44612. return BinaryFileAssetTask;
  44613. }());
  44614. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  44615. var ImageAssetTask = (function () {
  44616. function ImageAssetTask(name, url) {
  44617. this.name = name;
  44618. this.url = url;
  44619. this.isCompleted = false;
  44620. }
  44621. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44622. var _this = this;
  44623. var img = new Image();
  44624. BABYLON.Tools.SetCorsBehavior(this.url, img);
  44625. img.onload = function () {
  44626. _this.image = img;
  44627. _this.isCompleted = true;
  44628. if (_this.onSuccess) {
  44629. _this.onSuccess(_this);
  44630. }
  44631. onSuccess();
  44632. };
  44633. img.onerror = function () {
  44634. if (_this.onError) {
  44635. _this.onError(_this);
  44636. }
  44637. onError();
  44638. };
  44639. img.src = this.url;
  44640. };
  44641. return ImageAssetTask;
  44642. }());
  44643. BABYLON.ImageAssetTask = ImageAssetTask;
  44644. var TextureAssetTask = (function () {
  44645. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  44646. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44647. this.name = name;
  44648. this.url = url;
  44649. this.noMipmap = noMipmap;
  44650. this.invertY = invertY;
  44651. this.samplingMode = samplingMode;
  44652. this.isCompleted = false;
  44653. }
  44654. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44655. var _this = this;
  44656. var onload = function () {
  44657. _this.isCompleted = true;
  44658. if (_this.onSuccess) {
  44659. _this.onSuccess(_this);
  44660. }
  44661. onSuccess();
  44662. };
  44663. var onerror = function () {
  44664. if (_this.onError) {
  44665. _this.onError(_this);
  44666. }
  44667. onError();
  44668. };
  44669. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  44670. };
  44671. return TextureAssetTask;
  44672. }());
  44673. BABYLON.TextureAssetTask = TextureAssetTask;
  44674. var CubeTextureAssetTask = (function () {
  44675. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  44676. this.name = name;
  44677. this.url = url;
  44678. this.extensions = extensions;
  44679. this.noMipmap = noMipmap;
  44680. this.files = files;
  44681. this.isCompleted = false;
  44682. }
  44683. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44684. var _this = this;
  44685. var onload = function () {
  44686. _this.isCompleted = true;
  44687. if (_this.onSuccess) {
  44688. _this.onSuccess(_this);
  44689. }
  44690. onSuccess();
  44691. };
  44692. var onerror = function () {
  44693. if (_this.onError) {
  44694. _this.onError(_this);
  44695. }
  44696. onError();
  44697. };
  44698. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  44699. };
  44700. return CubeTextureAssetTask;
  44701. }());
  44702. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  44703. var AssetsManager = (function () {
  44704. function AssetsManager(scene) {
  44705. this.tasks = new Array();
  44706. this.waitingTasksCount = 0;
  44707. this.useDefaultLoadingScreen = true;
  44708. this._scene = scene;
  44709. }
  44710. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  44711. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  44712. this.tasks.push(task);
  44713. return task;
  44714. };
  44715. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  44716. var task = new TextFileAssetTask(taskName, url);
  44717. this.tasks.push(task);
  44718. return task;
  44719. };
  44720. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  44721. var task = new BinaryFileAssetTask(taskName, url);
  44722. this.tasks.push(task);
  44723. return task;
  44724. };
  44725. AssetsManager.prototype.addImageTask = function (taskName, url) {
  44726. var task = new ImageAssetTask(taskName, url);
  44727. this.tasks.push(task);
  44728. return task;
  44729. };
  44730. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  44731. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44732. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  44733. this.tasks.push(task);
  44734. return task;
  44735. };
  44736. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  44737. this.waitingTasksCount--;
  44738. if (this.waitingTasksCount === 0) {
  44739. if (this.onFinish) {
  44740. this.onFinish(this.tasks);
  44741. }
  44742. this._scene.getEngine().hideLoadingUI();
  44743. }
  44744. };
  44745. AssetsManager.prototype._runTask = function (task) {
  44746. var _this = this;
  44747. task.run(this._scene, function () {
  44748. if (_this.onTaskSuccess) {
  44749. _this.onTaskSuccess(task);
  44750. }
  44751. _this._decreaseWaitingTasksCount();
  44752. }, function () {
  44753. if (_this.onTaskError) {
  44754. _this.onTaskError(task);
  44755. }
  44756. _this._decreaseWaitingTasksCount();
  44757. });
  44758. };
  44759. AssetsManager.prototype.reset = function () {
  44760. this.tasks = new Array();
  44761. return this;
  44762. };
  44763. AssetsManager.prototype.load = function () {
  44764. this.waitingTasksCount = this.tasks.length;
  44765. if (this.waitingTasksCount === 0) {
  44766. if (this.onFinish) {
  44767. this.onFinish(this.tasks);
  44768. }
  44769. return this;
  44770. }
  44771. if (this.useDefaultLoadingScreen) {
  44772. this._scene.getEngine().displayLoadingUI();
  44773. }
  44774. for (var index = 0; index < this.tasks.length; index++) {
  44775. var task = this.tasks[index];
  44776. this._runTask(task);
  44777. }
  44778. return this;
  44779. };
  44780. return AssetsManager;
  44781. }());
  44782. BABYLON.AssetsManager = AssetsManager;
  44783. })(BABYLON || (BABYLON = {}));
  44784. //# sourceMappingURL=babylon.assetsManager.js.map
  44785. var BABYLON;
  44786. (function (BABYLON) {
  44787. var VRCameraMetrics = (function () {
  44788. function VRCameraMetrics() {
  44789. this.compensateDistortion = true;
  44790. }
  44791. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  44792. get: function () {
  44793. return this.hResolution / (2 * this.vResolution);
  44794. },
  44795. enumerable: true,
  44796. configurable: true
  44797. });
  44798. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  44799. get: function () {
  44800. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  44801. },
  44802. enumerable: true,
  44803. configurable: true
  44804. });
  44805. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  44806. get: function () {
  44807. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44808. var h = (4 * meters) / this.hScreenSize;
  44809. return BABYLON.Matrix.Translation(h, 0, 0);
  44810. },
  44811. enumerable: true,
  44812. configurable: true
  44813. });
  44814. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  44815. get: function () {
  44816. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44817. var h = (4 * meters) / this.hScreenSize;
  44818. return BABYLON.Matrix.Translation(-h, 0, 0);
  44819. },
  44820. enumerable: true,
  44821. configurable: true
  44822. });
  44823. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  44824. get: function () {
  44825. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  44826. },
  44827. enumerable: true,
  44828. configurable: true
  44829. });
  44830. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  44831. get: function () {
  44832. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  44833. },
  44834. enumerable: true,
  44835. configurable: true
  44836. });
  44837. VRCameraMetrics.GetDefault = function () {
  44838. var result = new VRCameraMetrics();
  44839. result.hResolution = 1280;
  44840. result.vResolution = 800;
  44841. result.hScreenSize = 0.149759993;
  44842. result.vScreenSize = 0.0935999975;
  44843. result.vScreenCenter = 0.0467999987,
  44844. result.eyeToScreenDistance = 0.0410000011;
  44845. result.lensSeparationDistance = 0.0635000020;
  44846. result.interpupillaryDistance = 0.0640000030;
  44847. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  44848. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  44849. result.postProcessScaleFactor = 1.714605507808412;
  44850. result.lensCenterOffset = 0.151976421;
  44851. return result;
  44852. };
  44853. return VRCameraMetrics;
  44854. }());
  44855. BABYLON.VRCameraMetrics = VRCameraMetrics;
  44856. })(BABYLON || (BABYLON = {}));
  44857. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  44858. var BABYLON;
  44859. (function (BABYLON) {
  44860. var WebVRFreeCamera = (function (_super) {
  44861. __extends(WebVRFreeCamera, _super);
  44862. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  44863. if (compensateDistortion === void 0) { compensateDistortion = false; }
  44864. if (webVROptions === void 0) { webVROptions = {}; }
  44865. var _this = _super.call(this, name, position, scene) || this;
  44866. _this.webVROptions = webVROptions;
  44867. _this._vrDevice = null;
  44868. _this._cacheState = null;
  44869. _this._vrEnabled = false;
  44870. _this._attached = false;
  44871. //using the position provided as the current position offset
  44872. _this._positionOffset = position;
  44873. //enable VR
  44874. _this.getEngine().initWebVR();
  44875. if (!_this.getEngine().vrDisplaysPromise) {
  44876. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  44877. }
  44878. else {
  44879. //TODO get the metrics updated using the device's eye parameters!
  44880. //TODO also check that the device has the right capabilities!
  44881. _this._frameData = new VRFrameData();
  44882. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  44883. if (devices.length > 0) {
  44884. _this._vrEnabled = true;
  44885. if (_this.webVROptions.displayName) {
  44886. var found = devices.some(function (device) {
  44887. if (device.displayName === _this.webVROptions.displayName) {
  44888. _this._vrDevice = device;
  44889. return true;
  44890. }
  44891. else {
  44892. return false;
  44893. }
  44894. });
  44895. if (!found) {
  44896. _this._vrDevice = devices[0];
  44897. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  44898. }
  44899. }
  44900. else {
  44901. //choose the first one
  44902. _this._vrDevice = devices[0];
  44903. }
  44904. //reset the rig parameters.
  44905. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  44906. if (_this._attached) {
  44907. _this.getEngine().enableVR(_this._vrDevice);
  44908. }
  44909. }
  44910. else {
  44911. BABYLON.Tools.Error("No WebVR devices found!");
  44912. }
  44913. });
  44914. }
  44915. _this.rotationQuaternion = new BABYLON.Quaternion();
  44916. _this._quaternionCache = new BABYLON.Quaternion();
  44917. return _this;
  44918. }
  44919. WebVRFreeCamera.prototype._checkInputs = function () {
  44920. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  44921. var currentPost = this._frameData.pose;
  44922. //make sure we have data
  44923. if (currentPost && currentPost.orientation) {
  44924. this._cacheState = currentPost;
  44925. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  44926. if (this.webVROptions.trackPosition && this._cacheState.position) {
  44927. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  44928. //scale the position accordingly
  44929. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  44930. //add the position offset
  44931. this.position.addInPlace(this._positionOffset);
  44932. }
  44933. }
  44934. }
  44935. _super.prototype._checkInputs.call(this);
  44936. };
  44937. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44938. _super.prototype.attachControl.call(this, element, noPreventDefault);
  44939. this._attached = true;
  44940. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  44941. if (this._vrEnabled) {
  44942. this.getEngine().enableVR(this._vrDevice);
  44943. }
  44944. };
  44945. WebVRFreeCamera.prototype.detachControl = function (element) {
  44946. _super.prototype.detachControl.call(this, element);
  44947. this._vrEnabled = false;
  44948. this._attached = false;
  44949. this.getEngine().disableVR();
  44950. };
  44951. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  44952. //Backwards comp.
  44953. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  44954. //this.getEngine().switchFullscreen(requestPointerlock);
  44955. };
  44956. WebVRFreeCamera.prototype.getClassName = function () {
  44957. return "WebVRFreeCamera";
  44958. };
  44959. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  44960. //uses the vrDisplay's "resetPose()".
  44961. //pitch and roll won't be affected.
  44962. this._vrDevice.resetPose();
  44963. };
  44964. /**
  44965. *
  44966. * Set the position offset of the VR camera
  44967. * The offset will be added to the WebVR pose, after scaling it (if set).
  44968. *
  44969. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  44970. *
  44971. * @memberOf WebVRFreeCamera
  44972. */
  44973. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  44974. if (newPosition) {
  44975. this._positionOffset = newPosition;
  44976. }
  44977. else {
  44978. this._positionOffset.copyFrom(this.position);
  44979. }
  44980. };
  44981. return WebVRFreeCamera;
  44982. }(BABYLON.FreeCamera));
  44983. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  44984. })(BABYLON || (BABYLON = {}));
  44985. //# sourceMappingURL=babylon.webVRCamera.js.map
  44986. var BABYLON;
  44987. (function (BABYLON) {
  44988. // Standard optimizations
  44989. var SceneOptimization = (function () {
  44990. function SceneOptimization(priority) {
  44991. if (priority === void 0) { priority = 0; }
  44992. this.priority = priority;
  44993. this.apply = function (scene) {
  44994. return true; // Return true if everything that can be done was applied
  44995. };
  44996. }
  44997. return SceneOptimization;
  44998. }());
  44999. BABYLON.SceneOptimization = SceneOptimization;
  45000. var TextureOptimization = (function (_super) {
  45001. __extends(TextureOptimization, _super);
  45002. function TextureOptimization(priority, maximumSize) {
  45003. if (priority === void 0) { priority = 0; }
  45004. if (maximumSize === void 0) { maximumSize = 1024; }
  45005. var _this = _super.call(this, priority) || this;
  45006. _this.priority = priority;
  45007. _this.maximumSize = maximumSize;
  45008. _this.apply = function (scene) {
  45009. var allDone = true;
  45010. for (var index = 0; index < scene.textures.length; index++) {
  45011. var texture = scene.textures[index];
  45012. if (!texture.canRescale) {
  45013. continue;
  45014. }
  45015. var currentSize = texture.getSize();
  45016. var maxDimension = Math.max(currentSize.width, currentSize.height);
  45017. if (maxDimension > _this.maximumSize) {
  45018. texture.scale(0.5);
  45019. allDone = false;
  45020. }
  45021. }
  45022. return allDone;
  45023. };
  45024. return _this;
  45025. }
  45026. return TextureOptimization;
  45027. }(SceneOptimization));
  45028. BABYLON.TextureOptimization = TextureOptimization;
  45029. var HardwareScalingOptimization = (function (_super) {
  45030. __extends(HardwareScalingOptimization, _super);
  45031. function HardwareScalingOptimization(priority, maximumScale) {
  45032. if (priority === void 0) { priority = 0; }
  45033. if (maximumScale === void 0) { maximumScale = 2; }
  45034. var _this = _super.call(this, priority) || this;
  45035. _this.priority = priority;
  45036. _this.maximumScale = maximumScale;
  45037. _this._currentScale = 1;
  45038. _this.apply = function (scene) {
  45039. _this._currentScale++;
  45040. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  45041. return _this._currentScale >= _this.maximumScale;
  45042. };
  45043. return _this;
  45044. }
  45045. return HardwareScalingOptimization;
  45046. }(SceneOptimization));
  45047. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  45048. var ShadowsOptimization = (function (_super) {
  45049. __extends(ShadowsOptimization, _super);
  45050. function ShadowsOptimization() {
  45051. var _this = _super.apply(this, arguments) || this;
  45052. _this.apply = function (scene) {
  45053. scene.shadowsEnabled = false;
  45054. return true;
  45055. };
  45056. return _this;
  45057. }
  45058. return ShadowsOptimization;
  45059. }(SceneOptimization));
  45060. BABYLON.ShadowsOptimization = ShadowsOptimization;
  45061. var PostProcessesOptimization = (function (_super) {
  45062. __extends(PostProcessesOptimization, _super);
  45063. function PostProcessesOptimization() {
  45064. var _this = _super.apply(this, arguments) || this;
  45065. _this.apply = function (scene) {
  45066. scene.postProcessesEnabled = false;
  45067. return true;
  45068. };
  45069. return _this;
  45070. }
  45071. return PostProcessesOptimization;
  45072. }(SceneOptimization));
  45073. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45074. var LensFlaresOptimization = (function (_super) {
  45075. __extends(LensFlaresOptimization, _super);
  45076. function LensFlaresOptimization() {
  45077. var _this = _super.apply(this, arguments) || this;
  45078. _this.apply = function (scene) {
  45079. scene.lensFlaresEnabled = false;
  45080. return true;
  45081. };
  45082. return _this;
  45083. }
  45084. return LensFlaresOptimization;
  45085. }(SceneOptimization));
  45086. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45087. var ParticlesOptimization = (function (_super) {
  45088. __extends(ParticlesOptimization, _super);
  45089. function ParticlesOptimization() {
  45090. var _this = _super.apply(this, arguments) || this;
  45091. _this.apply = function (scene) {
  45092. scene.particlesEnabled = false;
  45093. return true;
  45094. };
  45095. return _this;
  45096. }
  45097. return ParticlesOptimization;
  45098. }(SceneOptimization));
  45099. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45100. var RenderTargetsOptimization = (function (_super) {
  45101. __extends(RenderTargetsOptimization, _super);
  45102. function RenderTargetsOptimization() {
  45103. var _this = _super.apply(this, arguments) || this;
  45104. _this.apply = function (scene) {
  45105. scene.renderTargetsEnabled = false;
  45106. return true;
  45107. };
  45108. return _this;
  45109. }
  45110. return RenderTargetsOptimization;
  45111. }(SceneOptimization));
  45112. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45113. var MergeMeshesOptimization = (function (_super) {
  45114. __extends(MergeMeshesOptimization, _super);
  45115. function MergeMeshesOptimization() {
  45116. var _this = _super.apply(this, arguments) || this;
  45117. _this._canBeMerged = function (abstractMesh) {
  45118. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45119. return false;
  45120. }
  45121. var mesh = abstractMesh;
  45122. if (!mesh.isVisible || !mesh.isEnabled()) {
  45123. return false;
  45124. }
  45125. if (mesh.instances.length > 0) {
  45126. return false;
  45127. }
  45128. if (mesh.skeleton || mesh.hasLODLevels) {
  45129. return false;
  45130. }
  45131. if (mesh.parent) {
  45132. return false;
  45133. }
  45134. return true;
  45135. };
  45136. _this.apply = function (scene, updateSelectionTree) {
  45137. var globalPool = scene.meshes.slice(0);
  45138. var globalLength = globalPool.length;
  45139. for (var index = 0; index < globalLength; index++) {
  45140. var currentPool = new Array();
  45141. var current = globalPool[index];
  45142. // Checks
  45143. if (!_this._canBeMerged(current)) {
  45144. continue;
  45145. }
  45146. currentPool.push(current);
  45147. // Find compatible meshes
  45148. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45149. var otherMesh = globalPool[subIndex];
  45150. if (!_this._canBeMerged(otherMesh)) {
  45151. continue;
  45152. }
  45153. if (otherMesh.material !== current.material) {
  45154. continue;
  45155. }
  45156. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45157. continue;
  45158. }
  45159. currentPool.push(otherMesh);
  45160. globalLength--;
  45161. globalPool.splice(subIndex, 1);
  45162. subIndex--;
  45163. }
  45164. if (currentPool.length < 2) {
  45165. continue;
  45166. }
  45167. // Merge meshes
  45168. BABYLON.Mesh.MergeMeshes(currentPool);
  45169. }
  45170. if (updateSelectionTree != undefined) {
  45171. if (updateSelectionTree) {
  45172. scene.createOrUpdateSelectionOctree();
  45173. }
  45174. }
  45175. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45176. scene.createOrUpdateSelectionOctree();
  45177. }
  45178. return true;
  45179. };
  45180. return _this;
  45181. }
  45182. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45183. get: function () {
  45184. return MergeMeshesOptimization._UpdateSelectionTree;
  45185. },
  45186. set: function (value) {
  45187. MergeMeshesOptimization._UpdateSelectionTree = value;
  45188. },
  45189. enumerable: true,
  45190. configurable: true
  45191. });
  45192. return MergeMeshesOptimization;
  45193. }(SceneOptimization));
  45194. MergeMeshesOptimization._UpdateSelectionTree = false;
  45195. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45196. // Options
  45197. var SceneOptimizerOptions = (function () {
  45198. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45199. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45200. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45201. this.targetFrameRate = targetFrameRate;
  45202. this.trackerDuration = trackerDuration;
  45203. this.optimizations = new Array();
  45204. }
  45205. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45206. var result = new SceneOptimizerOptions(targetFrameRate);
  45207. var priority = 0;
  45208. result.optimizations.push(new MergeMeshesOptimization(priority));
  45209. result.optimizations.push(new ShadowsOptimization(priority));
  45210. result.optimizations.push(new LensFlaresOptimization(priority));
  45211. // Next priority
  45212. priority++;
  45213. result.optimizations.push(new PostProcessesOptimization(priority));
  45214. result.optimizations.push(new ParticlesOptimization(priority));
  45215. // Next priority
  45216. priority++;
  45217. result.optimizations.push(new TextureOptimization(priority, 1024));
  45218. return result;
  45219. };
  45220. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45221. var result = new SceneOptimizerOptions(targetFrameRate);
  45222. var priority = 0;
  45223. result.optimizations.push(new MergeMeshesOptimization(priority));
  45224. result.optimizations.push(new ShadowsOptimization(priority));
  45225. result.optimizations.push(new LensFlaresOptimization(priority));
  45226. // Next priority
  45227. priority++;
  45228. result.optimizations.push(new PostProcessesOptimization(priority));
  45229. result.optimizations.push(new ParticlesOptimization(priority));
  45230. // Next priority
  45231. priority++;
  45232. result.optimizations.push(new TextureOptimization(priority, 512));
  45233. // Next priority
  45234. priority++;
  45235. result.optimizations.push(new RenderTargetsOptimization(priority));
  45236. // Next priority
  45237. priority++;
  45238. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45239. return result;
  45240. };
  45241. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45242. var result = new SceneOptimizerOptions(targetFrameRate);
  45243. var priority = 0;
  45244. result.optimizations.push(new MergeMeshesOptimization(priority));
  45245. result.optimizations.push(new ShadowsOptimization(priority));
  45246. result.optimizations.push(new LensFlaresOptimization(priority));
  45247. // Next priority
  45248. priority++;
  45249. result.optimizations.push(new PostProcessesOptimization(priority));
  45250. result.optimizations.push(new ParticlesOptimization(priority));
  45251. // Next priority
  45252. priority++;
  45253. result.optimizations.push(new TextureOptimization(priority, 256));
  45254. // Next priority
  45255. priority++;
  45256. result.optimizations.push(new RenderTargetsOptimization(priority));
  45257. // Next priority
  45258. priority++;
  45259. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45260. return result;
  45261. };
  45262. return SceneOptimizerOptions;
  45263. }());
  45264. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45265. // Scene optimizer tool
  45266. var SceneOptimizer = (function () {
  45267. function SceneOptimizer() {
  45268. }
  45269. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45270. // TODO: add an epsilon
  45271. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45272. if (onSuccess) {
  45273. onSuccess();
  45274. }
  45275. return;
  45276. }
  45277. // Apply current level of optimizations
  45278. var allDone = true;
  45279. var noOptimizationApplied = true;
  45280. for (var index = 0; index < options.optimizations.length; index++) {
  45281. var optimization = options.optimizations[index];
  45282. if (optimization.priority === currentPriorityLevel) {
  45283. noOptimizationApplied = false;
  45284. allDone = allDone && optimization.apply(scene);
  45285. }
  45286. }
  45287. // If no optimization was applied, this is a failure :(
  45288. if (noOptimizationApplied) {
  45289. if (onFailure) {
  45290. onFailure();
  45291. }
  45292. return;
  45293. }
  45294. // If all optimizations were done, move to next level
  45295. if (allDone) {
  45296. currentPriorityLevel++;
  45297. }
  45298. // Let's the system running for a specific amount of time before checking FPS
  45299. scene.executeWhenReady(function () {
  45300. setTimeout(function () {
  45301. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45302. }, options.trackerDuration);
  45303. });
  45304. };
  45305. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45306. if (!options) {
  45307. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45308. }
  45309. // Let's the system running for a specific amount of time before checking FPS
  45310. scene.executeWhenReady(function () {
  45311. setTimeout(function () {
  45312. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45313. }, options.trackerDuration);
  45314. });
  45315. };
  45316. return SceneOptimizer;
  45317. }());
  45318. BABYLON.SceneOptimizer = SceneOptimizer;
  45319. })(BABYLON || (BABYLON = {}));
  45320. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45321. var BABYLON;
  45322. (function (BABYLON) {
  45323. var Internals;
  45324. (function (Internals) {
  45325. var MeshLODLevel = (function () {
  45326. function MeshLODLevel(distance, mesh) {
  45327. this.distance = distance;
  45328. this.mesh = mesh;
  45329. }
  45330. return MeshLODLevel;
  45331. }());
  45332. Internals.MeshLODLevel = MeshLODLevel;
  45333. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45334. })(BABYLON || (BABYLON = {}));
  45335. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45336. var BABYLON;
  45337. (function (BABYLON) {
  45338. var RawTexture = (function (_super) {
  45339. __extends(RawTexture, _super);
  45340. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45341. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45342. if (invertY === void 0) { invertY = false; }
  45343. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45344. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45345. _this.format = format;
  45346. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45347. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45348. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45349. return _this;
  45350. }
  45351. RawTexture.prototype.update = function (data) {
  45352. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45353. };
  45354. // Statics
  45355. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45356. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45357. if (invertY === void 0) { invertY = false; }
  45358. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45359. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45360. };
  45361. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45362. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45363. if (invertY === void 0) { invertY = false; }
  45364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45365. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45366. };
  45367. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45368. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45369. if (invertY === void 0) { invertY = false; }
  45370. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45371. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45372. };
  45373. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45374. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45375. if (invertY === void 0) { invertY = false; }
  45376. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45377. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45378. };
  45379. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45380. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45381. if (invertY === void 0) { invertY = false; }
  45382. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45383. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45384. };
  45385. return RawTexture;
  45386. }(BABYLON.Texture));
  45387. BABYLON.RawTexture = RawTexture;
  45388. })(BABYLON || (BABYLON = {}));
  45389. //# sourceMappingURL=babylon.rawTexture.js.map
  45390. var BABYLON;
  45391. (function (BABYLON) {
  45392. var IndexedVector2 = (function (_super) {
  45393. __extends(IndexedVector2, _super);
  45394. function IndexedVector2(original, index) {
  45395. var _this = _super.call(this, original.x, original.y) || this;
  45396. _this.index = index;
  45397. return _this;
  45398. }
  45399. return IndexedVector2;
  45400. }(BABYLON.Vector2));
  45401. var PolygonPoints = (function () {
  45402. function PolygonPoints() {
  45403. this.elements = new Array();
  45404. }
  45405. PolygonPoints.prototype.add = function (originalPoints) {
  45406. var _this = this;
  45407. var result = new Array();
  45408. originalPoints.forEach(function (point) {
  45409. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45410. var newPoint = new IndexedVector2(point, _this.elements.length);
  45411. result.push(newPoint);
  45412. _this.elements.push(newPoint);
  45413. }
  45414. });
  45415. return result;
  45416. };
  45417. PolygonPoints.prototype.computeBounds = function () {
  45418. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45419. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45420. this.elements.forEach(function (point) {
  45421. // x
  45422. if (point.x < lmin.x) {
  45423. lmin.x = point.x;
  45424. }
  45425. else if (point.x > lmax.x) {
  45426. lmax.x = point.x;
  45427. }
  45428. // y
  45429. if (point.y < lmin.y) {
  45430. lmin.y = point.y;
  45431. }
  45432. else if (point.y > lmax.y) {
  45433. lmax.y = point.y;
  45434. }
  45435. });
  45436. return {
  45437. min: lmin,
  45438. max: lmax,
  45439. width: lmax.x - lmin.x,
  45440. height: lmax.y - lmin.y
  45441. };
  45442. };
  45443. return PolygonPoints;
  45444. }());
  45445. var Polygon = (function () {
  45446. function Polygon() {
  45447. }
  45448. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45449. return [
  45450. new BABYLON.Vector2(xmin, ymin),
  45451. new BABYLON.Vector2(xmax, ymin),
  45452. new BABYLON.Vector2(xmax, ymax),
  45453. new BABYLON.Vector2(xmin, ymax)
  45454. ];
  45455. };
  45456. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45457. if (cx === void 0) { cx = 0; }
  45458. if (cy === void 0) { cy = 0; }
  45459. if (numberOfSides === void 0) { numberOfSides = 32; }
  45460. var result = new Array();
  45461. var angle = 0;
  45462. var increment = (Math.PI * 2) / numberOfSides;
  45463. for (var i = 0; i < numberOfSides; i++) {
  45464. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  45465. angle -= increment;
  45466. }
  45467. return result;
  45468. };
  45469. Polygon.Parse = function (input) {
  45470. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  45471. var i, result = [];
  45472. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  45473. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  45474. }
  45475. return result;
  45476. };
  45477. Polygon.StartingAt = function (x, y) {
  45478. return BABYLON.Path2.StartingAt(x, y);
  45479. };
  45480. return Polygon;
  45481. }());
  45482. BABYLON.Polygon = Polygon;
  45483. var PolygonMeshBuilder = (function () {
  45484. function PolygonMeshBuilder(name, contours, scene) {
  45485. this._points = new PolygonPoints();
  45486. this._outlinepoints = new PolygonPoints();
  45487. this._holes = [];
  45488. this._epoints = new Array();
  45489. this._eholes = new Array();
  45490. this._name = name;
  45491. this._scene = scene;
  45492. var points;
  45493. if (contours instanceof BABYLON.Path2) {
  45494. points = contours.getPoints();
  45495. }
  45496. else {
  45497. points = contours;
  45498. }
  45499. this._addToepoint(points);
  45500. this._points.add(points);
  45501. this._outlinepoints.add(points);
  45502. }
  45503. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  45504. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  45505. var p = points_1[_i];
  45506. this._epoints.push(p.x, p.y);
  45507. }
  45508. };
  45509. PolygonMeshBuilder.prototype.addHole = function (hole) {
  45510. this._points.add(hole);
  45511. var holepoints = new PolygonPoints();
  45512. holepoints.add(hole);
  45513. this._holes.push(holepoints);
  45514. this._eholes.push(this._epoints.length / 2);
  45515. this._addToepoint(hole);
  45516. return this;
  45517. };
  45518. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  45519. var _this = this;
  45520. if (updatable === void 0) { updatable = false; }
  45521. var result = new BABYLON.Mesh(this._name, this._scene);
  45522. var normals = [];
  45523. var positions = [];
  45524. var uvs = [];
  45525. var bounds = this._points.computeBounds();
  45526. this._points.elements.forEach(function (p) {
  45527. normals.push(0, 1.0, 0);
  45528. positions.push(p.x, 0, p.y);
  45529. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  45530. });
  45531. var indices = [];
  45532. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  45533. for (var i = 0; i < res.length; i++) {
  45534. indices.push(res[i]);
  45535. }
  45536. if (depth > 0) {
  45537. var positionscount = (positions.length / 3); //get the current pointcount
  45538. this._points.elements.forEach(function (p) {
  45539. normals.push(0, -1.0, 0);
  45540. positions.push(p.x, -depth, p.y);
  45541. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  45542. });
  45543. var totalCount = indices.length;
  45544. for (var i = 0; i < totalCount; i += 3) {
  45545. var i0 = indices[i + 0];
  45546. var i1 = indices[i + 1];
  45547. var i2 = indices[i + 2];
  45548. indices.push(i2 + positionscount);
  45549. indices.push(i1 + positionscount);
  45550. indices.push(i0 + positionscount);
  45551. }
  45552. //Add the sides
  45553. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  45554. this._holes.forEach(function (hole) {
  45555. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  45556. });
  45557. }
  45558. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  45559. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  45560. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  45561. result.setIndices(indices);
  45562. return result;
  45563. };
  45564. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  45565. var StartIndex = positions.length / 3;
  45566. var ulength = 0;
  45567. for (var i = 0; i < points.elements.length; i++) {
  45568. var p = points.elements[i];
  45569. var p1;
  45570. if ((i + 1) > points.elements.length - 1) {
  45571. p1 = points.elements[0];
  45572. }
  45573. else {
  45574. p1 = points.elements[i + 1];
  45575. }
  45576. positions.push(p.x, 0, p.y);
  45577. positions.push(p.x, -depth, p.y);
  45578. positions.push(p1.x, 0, p1.y);
  45579. positions.push(p1.x, -depth, p1.y);
  45580. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  45581. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  45582. var v3 = v2.subtract(v1);
  45583. var v4 = new BABYLON.Vector3(0, 1, 0);
  45584. var vn = BABYLON.Vector3.Cross(v3, v4);
  45585. vn = vn.normalize();
  45586. uvs.push(ulength / bounds.width, 0);
  45587. uvs.push(ulength / bounds.width, 1);
  45588. ulength += v3.length();
  45589. uvs.push((ulength / bounds.width), 0);
  45590. uvs.push((ulength / bounds.width), 1);
  45591. if (!flip) {
  45592. normals.push(-vn.x, -vn.y, -vn.z);
  45593. normals.push(-vn.x, -vn.y, -vn.z);
  45594. normals.push(-vn.x, -vn.y, -vn.z);
  45595. normals.push(-vn.x, -vn.y, -vn.z);
  45596. indices.push(StartIndex);
  45597. indices.push(StartIndex + 1);
  45598. indices.push(StartIndex + 2);
  45599. indices.push(StartIndex + 1);
  45600. indices.push(StartIndex + 3);
  45601. indices.push(StartIndex + 2);
  45602. }
  45603. else {
  45604. normals.push(vn.x, vn.y, vn.z);
  45605. normals.push(vn.x, vn.y, vn.z);
  45606. normals.push(vn.x, vn.y, vn.z);
  45607. normals.push(vn.x, vn.y, vn.z);
  45608. indices.push(StartIndex);
  45609. indices.push(StartIndex + 2);
  45610. indices.push(StartIndex + 1);
  45611. indices.push(StartIndex + 1);
  45612. indices.push(StartIndex + 2);
  45613. indices.push(StartIndex + 3);
  45614. }
  45615. StartIndex += 4;
  45616. }
  45617. ;
  45618. };
  45619. return PolygonMeshBuilder;
  45620. }());
  45621. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  45622. })(BABYLON || (BABYLON = {}));
  45623. //# sourceMappingURL=babylon.polygonMesh.js.map
  45624. var BABYLON;
  45625. (function (BABYLON) {
  45626. var Octree = (function () {
  45627. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  45628. if (maxDepth === void 0) { maxDepth = 2; }
  45629. this.maxDepth = maxDepth;
  45630. this.dynamicContent = new Array();
  45631. this._maxBlockCapacity = maxBlockCapacity || 64;
  45632. this._selectionContent = new BABYLON.SmartArray(1024);
  45633. this._creationFunc = creationFunc;
  45634. }
  45635. // Methods
  45636. Octree.prototype.update = function (worldMin, worldMax, entries) {
  45637. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  45638. };
  45639. Octree.prototype.addMesh = function (entry) {
  45640. for (var index = 0; index < this.blocks.length; index++) {
  45641. var block = this.blocks[index];
  45642. block.addEntry(entry);
  45643. }
  45644. };
  45645. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  45646. this._selectionContent.reset();
  45647. for (var index = 0; index < this.blocks.length; index++) {
  45648. var block = this.blocks[index];
  45649. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  45650. }
  45651. if (allowDuplicate) {
  45652. this._selectionContent.concat(this.dynamicContent);
  45653. }
  45654. else {
  45655. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45656. }
  45657. return this._selectionContent;
  45658. };
  45659. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  45660. this._selectionContent.reset();
  45661. for (var index = 0; index < this.blocks.length; index++) {
  45662. var block = this.blocks[index];
  45663. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  45664. }
  45665. if (allowDuplicate) {
  45666. this._selectionContent.concat(this.dynamicContent);
  45667. }
  45668. else {
  45669. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45670. }
  45671. return this._selectionContent;
  45672. };
  45673. Octree.prototype.intersectsRay = function (ray) {
  45674. this._selectionContent.reset();
  45675. for (var index = 0; index < this.blocks.length; index++) {
  45676. var block = this.blocks[index];
  45677. block.intersectsRay(ray, this._selectionContent);
  45678. }
  45679. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45680. return this._selectionContent;
  45681. };
  45682. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  45683. target.blocks = new Array();
  45684. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  45685. // Segmenting space
  45686. for (var x = 0; x < 2; x++) {
  45687. for (var y = 0; y < 2; y++) {
  45688. for (var z = 0; z < 2; z++) {
  45689. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  45690. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  45691. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  45692. block.addEntries(entries);
  45693. target.blocks.push(block);
  45694. }
  45695. }
  45696. }
  45697. };
  45698. return Octree;
  45699. }());
  45700. Octree.CreationFuncForMeshes = function (entry, block) {
  45701. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45702. block.entries.push(entry);
  45703. }
  45704. };
  45705. Octree.CreationFuncForSubMeshes = function (entry, block) {
  45706. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45707. block.entries.push(entry);
  45708. }
  45709. };
  45710. BABYLON.Octree = Octree;
  45711. })(BABYLON || (BABYLON = {}));
  45712. //# sourceMappingURL=babylon.octree.js.map
  45713. var BABYLON;
  45714. (function (BABYLON) {
  45715. var OctreeBlock = (function () {
  45716. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  45717. this.entries = new Array();
  45718. this._boundingVectors = new Array();
  45719. this._capacity = capacity;
  45720. this._depth = depth;
  45721. this._maxDepth = maxDepth;
  45722. this._creationFunc = creationFunc;
  45723. this._minPoint = minPoint;
  45724. this._maxPoint = maxPoint;
  45725. this._boundingVectors.push(minPoint.clone());
  45726. this._boundingVectors.push(maxPoint.clone());
  45727. this._boundingVectors.push(minPoint.clone());
  45728. this._boundingVectors[2].x = maxPoint.x;
  45729. this._boundingVectors.push(minPoint.clone());
  45730. this._boundingVectors[3].y = maxPoint.y;
  45731. this._boundingVectors.push(minPoint.clone());
  45732. this._boundingVectors[4].z = maxPoint.z;
  45733. this._boundingVectors.push(maxPoint.clone());
  45734. this._boundingVectors[5].z = minPoint.z;
  45735. this._boundingVectors.push(maxPoint.clone());
  45736. this._boundingVectors[6].x = minPoint.x;
  45737. this._boundingVectors.push(maxPoint.clone());
  45738. this._boundingVectors[7].y = minPoint.y;
  45739. }
  45740. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  45741. // Property
  45742. get: function () {
  45743. return this._capacity;
  45744. },
  45745. enumerable: true,
  45746. configurable: true
  45747. });
  45748. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  45749. get: function () {
  45750. return this._minPoint;
  45751. },
  45752. enumerable: true,
  45753. configurable: true
  45754. });
  45755. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  45756. get: function () {
  45757. return this._maxPoint;
  45758. },
  45759. enumerable: true,
  45760. configurable: true
  45761. });
  45762. // Methods
  45763. OctreeBlock.prototype.addEntry = function (entry) {
  45764. if (this.blocks) {
  45765. for (var index = 0; index < this.blocks.length; index++) {
  45766. var block = this.blocks[index];
  45767. block.addEntry(entry);
  45768. }
  45769. return;
  45770. }
  45771. this._creationFunc(entry, this);
  45772. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  45773. this.createInnerBlocks();
  45774. }
  45775. };
  45776. OctreeBlock.prototype.addEntries = function (entries) {
  45777. for (var index = 0; index < entries.length; index++) {
  45778. var mesh = entries[index];
  45779. this.addEntry(mesh);
  45780. }
  45781. };
  45782. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  45783. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  45784. if (this.blocks) {
  45785. for (var index = 0; index < this.blocks.length; index++) {
  45786. var block = this.blocks[index];
  45787. block.select(frustumPlanes, selection, allowDuplicate);
  45788. }
  45789. return;
  45790. }
  45791. if (allowDuplicate) {
  45792. selection.concat(this.entries);
  45793. }
  45794. else {
  45795. selection.concatWithNoDuplicate(this.entries);
  45796. }
  45797. }
  45798. };
  45799. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  45800. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  45801. if (this.blocks) {
  45802. for (var index = 0; index < this.blocks.length; index++) {
  45803. var block = this.blocks[index];
  45804. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  45805. }
  45806. return;
  45807. }
  45808. if (allowDuplicate) {
  45809. selection.concat(this.entries);
  45810. }
  45811. else {
  45812. selection.concatWithNoDuplicate(this.entries);
  45813. }
  45814. }
  45815. };
  45816. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  45817. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  45818. if (this.blocks) {
  45819. for (var index = 0; index < this.blocks.length; index++) {
  45820. var block = this.blocks[index];
  45821. block.intersectsRay(ray, selection);
  45822. }
  45823. return;
  45824. }
  45825. selection.concatWithNoDuplicate(this.entries);
  45826. }
  45827. };
  45828. OctreeBlock.prototype.createInnerBlocks = function () {
  45829. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  45830. };
  45831. return OctreeBlock;
  45832. }());
  45833. BABYLON.OctreeBlock = OctreeBlock;
  45834. })(BABYLON || (BABYLON = {}));
  45835. //# sourceMappingURL=babylon.octreeBlock.js.map
  45836. var BABYLON;
  45837. (function (BABYLON) {
  45838. var BlurPostProcess = (function (_super) {
  45839. __extends(BlurPostProcess, _super);
  45840. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  45841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45842. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  45843. _this.direction = direction;
  45844. _this.blurWidth = blurWidth;
  45845. _this.onApplyObservable.add(function (effect) {
  45846. effect.setFloat2("screenSize", _this.width, _this.height);
  45847. effect.setVector2("direction", _this.direction);
  45848. effect.setFloat("blurWidth", _this.blurWidth);
  45849. });
  45850. return _this;
  45851. }
  45852. return BlurPostProcess;
  45853. }(BABYLON.PostProcess));
  45854. BABYLON.BlurPostProcess = BlurPostProcess;
  45855. })(BABYLON || (BABYLON = {}));
  45856. //# sourceMappingURL=babylon.blurPostProcess.js.map
  45857. var BABYLON;
  45858. (function (BABYLON) {
  45859. var RefractionPostProcess = (function (_super) {
  45860. __extends(RefractionPostProcess, _super);
  45861. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  45862. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  45863. _this.color = color;
  45864. _this.depth = depth;
  45865. _this.colorLevel = colorLevel;
  45866. _this.onActivateObservable.add(function (cam) {
  45867. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  45868. });
  45869. _this.onApplyObservable.add(function (effect) {
  45870. effect.setColor3("baseColor", _this.color);
  45871. effect.setFloat("depth", _this.depth);
  45872. effect.setFloat("colorLevel", _this.colorLevel);
  45873. effect.setTexture("refractionSampler", _this._refRexture);
  45874. });
  45875. return _this;
  45876. }
  45877. // Methods
  45878. RefractionPostProcess.prototype.dispose = function (camera) {
  45879. if (this._refRexture) {
  45880. this._refRexture.dispose();
  45881. }
  45882. _super.prototype.dispose.call(this, camera);
  45883. };
  45884. return RefractionPostProcess;
  45885. }(BABYLON.PostProcess));
  45886. BABYLON.RefractionPostProcess = RefractionPostProcess;
  45887. })(BABYLON || (BABYLON = {}));
  45888. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  45889. var BABYLON;
  45890. (function (BABYLON) {
  45891. var BlackAndWhitePostProcess = (function (_super) {
  45892. __extends(BlackAndWhitePostProcess, _super);
  45893. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  45894. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  45895. }
  45896. return BlackAndWhitePostProcess;
  45897. }(BABYLON.PostProcess));
  45898. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  45899. })(BABYLON || (BABYLON = {}));
  45900. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  45901. var BABYLON;
  45902. (function (BABYLON) {
  45903. var ConvolutionPostProcess = (function (_super) {
  45904. __extends(ConvolutionPostProcess, _super);
  45905. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  45906. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  45907. _this.kernel = kernel;
  45908. _this.onApply = function (effect) {
  45909. effect.setFloat2("screenSize", _this.width, _this.height);
  45910. effect.setArray("kernel", _this.kernel);
  45911. };
  45912. return _this;
  45913. }
  45914. return ConvolutionPostProcess;
  45915. }(BABYLON.PostProcess));
  45916. // Statics
  45917. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  45918. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  45919. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  45920. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  45921. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  45922. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  45923. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  45924. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  45925. })(BABYLON || (BABYLON = {}));
  45926. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  45927. var BABYLON;
  45928. (function (BABYLON) {
  45929. var FilterPostProcess = (function (_super) {
  45930. __extends(FilterPostProcess, _super);
  45931. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  45932. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  45933. _this.kernelMatrix = kernelMatrix;
  45934. _this.onApply = function (effect) {
  45935. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  45936. };
  45937. return _this;
  45938. }
  45939. return FilterPostProcess;
  45940. }(BABYLON.PostProcess));
  45941. BABYLON.FilterPostProcess = FilterPostProcess;
  45942. })(BABYLON || (BABYLON = {}));
  45943. //# sourceMappingURL=babylon.filterPostProcess.js.map
  45944. var BABYLON;
  45945. (function (BABYLON) {
  45946. var FxaaPostProcess = (function (_super) {
  45947. __extends(FxaaPostProcess, _super);
  45948. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  45949. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  45950. _this.onSizeChangedObservable.add(function () {
  45951. _this.texelWidth = 1.0 / _this.width;
  45952. _this.texelHeight = 1.0 / _this.height;
  45953. });
  45954. _this.onApplyObservable.add(function (effect) {
  45955. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  45956. });
  45957. return _this;
  45958. }
  45959. return FxaaPostProcess;
  45960. }(BABYLON.PostProcess));
  45961. BABYLON.FxaaPostProcess = FxaaPostProcess;
  45962. })(BABYLON || (BABYLON = {}));
  45963. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  45964. var BABYLON;
  45965. (function (BABYLON) {
  45966. var StereoscopicInterlacePostProcess = (function (_super) {
  45967. __extends(StereoscopicInterlacePostProcess, _super);
  45968. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  45969. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  45970. _this._passedProcess = rigCameras[0]._rigPostProcess;
  45971. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45972. _this.onSizeChangedObservable.add(function () {
  45973. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45974. });
  45975. _this.onApplyObservable.add(function (effect) {
  45976. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  45977. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  45978. });
  45979. return _this;
  45980. }
  45981. return StereoscopicInterlacePostProcess;
  45982. }(BABYLON.PostProcess));
  45983. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  45984. })(BABYLON || (BABYLON = {}));
  45985. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  45986. var BABYLON;
  45987. (function (BABYLON) {
  45988. var LensFlare = (function () {
  45989. function LensFlare(size, position, color, imgUrl, system) {
  45990. this.size = size;
  45991. this.position = position;
  45992. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  45993. this.dispose = function () {
  45994. if (this.texture) {
  45995. this.texture.dispose();
  45996. }
  45997. // Remove from scene
  45998. var index = this._system.lensFlares.indexOf(this);
  45999. this._system.lensFlares.splice(index, 1);
  46000. };
  46001. this.color = color || new BABYLON.Color3(1, 1, 1);
  46002. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  46003. this._system = system;
  46004. system.lensFlares.push(this);
  46005. }
  46006. return LensFlare;
  46007. }());
  46008. BABYLON.LensFlare = LensFlare;
  46009. })(BABYLON || (BABYLON = {}));
  46010. //# sourceMappingURL=babylon.lensFlare.js.map
  46011. var BABYLON;
  46012. (function (BABYLON) {
  46013. var LensFlareSystem = (function () {
  46014. function LensFlareSystem(name, emitter, scene) {
  46015. this.name = name;
  46016. this.lensFlares = new Array();
  46017. this.borderLimit = 300;
  46018. this.viewportBorder = 0;
  46019. this.layerMask = 0x0FFFFFFF;
  46020. this._vertexBuffers = {};
  46021. this._isEnabled = true;
  46022. this._scene = scene;
  46023. this._emitter = emitter;
  46024. this.id = name;
  46025. scene.lensFlareSystems.push(this);
  46026. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  46027. var engine = scene.getEngine();
  46028. // VBO
  46029. var vertices = [];
  46030. vertices.push(1, 1);
  46031. vertices.push(-1, 1);
  46032. vertices.push(-1, -1);
  46033. vertices.push(1, -1);
  46034. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46035. // Indices
  46036. var indices = [];
  46037. indices.push(0);
  46038. indices.push(1);
  46039. indices.push(2);
  46040. indices.push(0);
  46041. indices.push(2);
  46042. indices.push(3);
  46043. this._indexBuffer = engine.createIndexBuffer(indices);
  46044. // Effects
  46045. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  46046. }
  46047. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  46048. get: function () {
  46049. return this._isEnabled;
  46050. },
  46051. set: function (value) {
  46052. this._isEnabled = value;
  46053. },
  46054. enumerable: true,
  46055. configurable: true
  46056. });
  46057. LensFlareSystem.prototype.getScene = function () {
  46058. return this._scene;
  46059. };
  46060. LensFlareSystem.prototype.getEmitter = function () {
  46061. return this._emitter;
  46062. };
  46063. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  46064. this._emitter = newEmitter;
  46065. };
  46066. LensFlareSystem.prototype.getEmitterPosition = function () {
  46067. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  46068. };
  46069. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  46070. var position = this.getEmitterPosition();
  46071. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  46072. this._positionX = position.x;
  46073. this._positionY = position.y;
  46074. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  46075. if (this.viewportBorder > 0) {
  46076. globalViewport.x -= this.viewportBorder;
  46077. globalViewport.y -= this.viewportBorder;
  46078. globalViewport.width += this.viewportBorder * 2;
  46079. globalViewport.height += this.viewportBorder * 2;
  46080. position.x += this.viewportBorder;
  46081. position.y += this.viewportBorder;
  46082. this._positionX += this.viewportBorder;
  46083. this._positionY += this.viewportBorder;
  46084. }
  46085. if (position.z > 0) {
  46086. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46087. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46088. return true;
  46089. }
  46090. return true;
  46091. }
  46092. return false;
  46093. };
  46094. LensFlareSystem.prototype._isVisible = function () {
  46095. if (!this._isEnabled) {
  46096. return false;
  46097. }
  46098. var emitterPosition = this.getEmitterPosition();
  46099. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  46100. var distance = direction.length();
  46101. direction.normalize();
  46102. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  46103. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46104. return !pickInfo.hit || pickInfo.distance > distance;
  46105. };
  46106. LensFlareSystem.prototype.render = function () {
  46107. if (!this._effect.isReady())
  46108. return false;
  46109. var engine = this._scene.getEngine();
  46110. var viewport = this._scene.activeCamera.viewport;
  46111. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46112. // Position
  46113. if (!this.computeEffectivePosition(globalViewport)) {
  46114. return false;
  46115. }
  46116. // Visibility
  46117. if (!this._isVisible()) {
  46118. return false;
  46119. }
  46120. // Intensity
  46121. var awayX;
  46122. var awayY;
  46123. if (this._positionX < this.borderLimit + globalViewport.x) {
  46124. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46125. }
  46126. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46127. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46128. }
  46129. else {
  46130. awayX = 0;
  46131. }
  46132. if (this._positionY < this.borderLimit + globalViewport.y) {
  46133. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46134. }
  46135. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46136. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46137. }
  46138. else {
  46139. awayY = 0;
  46140. }
  46141. var away = (awayX > awayY) ? awayX : awayY;
  46142. away -= this.viewportBorder;
  46143. if (away > this.borderLimit) {
  46144. away = this.borderLimit;
  46145. }
  46146. var intensity = 1.0 - (away / this.borderLimit);
  46147. if (intensity < 0) {
  46148. return false;
  46149. }
  46150. if (intensity > 1.0) {
  46151. intensity = 1.0;
  46152. }
  46153. if (this.viewportBorder > 0) {
  46154. globalViewport.x += this.viewportBorder;
  46155. globalViewport.y += this.viewportBorder;
  46156. globalViewport.width -= this.viewportBorder * 2;
  46157. globalViewport.height -= this.viewportBorder * 2;
  46158. this._positionX -= this.viewportBorder;
  46159. this._positionY -= this.viewportBorder;
  46160. }
  46161. // Position
  46162. var centerX = globalViewport.x + globalViewport.width / 2;
  46163. var centerY = globalViewport.y + globalViewport.height / 2;
  46164. var distX = centerX - this._positionX;
  46165. var distY = centerY - this._positionY;
  46166. // Effects
  46167. engine.enableEffect(this._effect);
  46168. engine.setState(false);
  46169. engine.setDepthBuffer(false);
  46170. // VBOs
  46171. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46172. // Flares
  46173. for (var index = 0; index < this.lensFlares.length; index++) {
  46174. var flare = this.lensFlares[index];
  46175. engine.setAlphaMode(flare.alphaMode);
  46176. var x = centerX - (distX * flare.position);
  46177. var y = centerY - (distY * flare.position);
  46178. var cw = flare.size;
  46179. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46180. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46181. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46182. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46183. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46184. // Texture
  46185. this._effect.setTexture("textureSampler", flare.texture);
  46186. // Color
  46187. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46188. // Draw order
  46189. engine.draw(true, 0, 6);
  46190. }
  46191. engine.setDepthBuffer(true);
  46192. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46193. return true;
  46194. };
  46195. LensFlareSystem.prototype.dispose = function () {
  46196. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46197. if (vertexBuffer) {
  46198. vertexBuffer.dispose();
  46199. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46200. }
  46201. if (this._indexBuffer) {
  46202. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46203. this._indexBuffer = null;
  46204. }
  46205. while (this.lensFlares.length) {
  46206. this.lensFlares[0].dispose();
  46207. }
  46208. // Remove from scene
  46209. var index = this._scene.lensFlareSystems.indexOf(this);
  46210. this._scene.lensFlareSystems.splice(index, 1);
  46211. };
  46212. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46213. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46214. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46215. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46216. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46217. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46218. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46219. var parsedFlare = parsedLensFlareSystem.flares[index];
  46220. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46221. }
  46222. return lensFlareSystem;
  46223. };
  46224. LensFlareSystem.prototype.serialize = function () {
  46225. var serializationObject = {};
  46226. serializationObject.id = this.id;
  46227. serializationObject.name = this.name;
  46228. serializationObject.emitterId = this.getEmitter().id;
  46229. serializationObject.borderLimit = this.borderLimit;
  46230. serializationObject.flares = [];
  46231. for (var index = 0; index < this.lensFlares.length; index++) {
  46232. var flare = this.lensFlares[index];
  46233. serializationObject.flares.push({
  46234. size: flare.size,
  46235. position: flare.position,
  46236. color: flare.color.asArray(),
  46237. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46238. });
  46239. }
  46240. return serializationObject;
  46241. };
  46242. return LensFlareSystem;
  46243. }());
  46244. BABYLON.LensFlareSystem = LensFlareSystem;
  46245. })(BABYLON || (BABYLON = {}));
  46246. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46247. var BABYLON;
  46248. (function (BABYLON) {
  46249. // We're mainly based on the logic defined into the FreeCamera code
  46250. var DeviceOrientationCamera = (function (_super) {
  46251. __extends(DeviceOrientationCamera, _super);
  46252. function DeviceOrientationCamera(name, position, scene) {
  46253. var _this = _super.call(this, name, position, scene) || this;
  46254. _this._quaternionCache = new BABYLON.Quaternion();
  46255. _this.inputs.addDeviceOrientation();
  46256. return _this;
  46257. }
  46258. DeviceOrientationCamera.prototype.getClassName = function () {
  46259. return "DeviceOrientationCamera";
  46260. };
  46261. DeviceOrientationCamera.prototype._checkInputs = function () {
  46262. _super.prototype._checkInputs.call(this);
  46263. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46264. if (this._initialQuaternion) {
  46265. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46266. }
  46267. };
  46268. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46269. var _this = this;
  46270. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46271. //can only work if this camera has a rotation quaternion already.
  46272. if (!this.rotationQuaternion)
  46273. return;
  46274. if (!this._initialQuaternion) {
  46275. this._initialQuaternion = new BABYLON.Quaternion();
  46276. }
  46277. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46278. ['x', 'y', 'z'].forEach(function (axisName) {
  46279. if (!axis[axisName]) {
  46280. _this._initialQuaternion[axisName] = 0;
  46281. }
  46282. else {
  46283. _this._initialQuaternion[axisName] *= -1;
  46284. }
  46285. });
  46286. this._initialQuaternion.normalize();
  46287. //force rotation update
  46288. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46289. };
  46290. return DeviceOrientationCamera;
  46291. }(BABYLON.FreeCamera));
  46292. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46293. })(BABYLON || (BABYLON = {}));
  46294. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46295. var BABYLON;
  46296. (function (BABYLON) {
  46297. var VRDeviceOrientationFreeCamera = (function (_super) {
  46298. __extends(VRDeviceOrientationFreeCamera, _super);
  46299. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46300. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46301. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46302. var _this = _super.call(this, name, position, scene) || this;
  46303. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46304. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46305. return _this;
  46306. }
  46307. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46308. return "VRDeviceOrientationFreeCamera";
  46309. };
  46310. return VRDeviceOrientationFreeCamera;
  46311. }(BABYLON.DeviceOrientationCamera));
  46312. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46313. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46314. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46315. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46316. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46317. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46318. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  46319. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46320. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46321. _this.inputs.addVRDeviceOrientation();
  46322. return _this;
  46323. }
  46324. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  46325. return "VRDeviceOrientationArcRotateCamera";
  46326. };
  46327. return VRDeviceOrientationArcRotateCamera;
  46328. }(BABYLON.ArcRotateCamera));
  46329. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46330. })(BABYLON || (BABYLON = {}));
  46331. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46332. var BABYLON;
  46333. (function (BABYLON) {
  46334. // We're mainly based on the logic defined into the FreeCamera code
  46335. var UniversalCamera = (function (_super) {
  46336. __extends(UniversalCamera, _super);
  46337. //-- end properties for backward compatibility for inputs
  46338. function UniversalCamera(name, position, scene) {
  46339. var _this = _super.call(this, name, position, scene) || this;
  46340. _this.inputs.addGamepad();
  46341. return _this;
  46342. }
  46343. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46344. //-- Begin properties for backward compatibility for inputs
  46345. get: function () {
  46346. var gamepad = this.inputs.attached["gamepad"];
  46347. if (gamepad)
  46348. return gamepad.gamepadAngularSensibility;
  46349. },
  46350. set: function (value) {
  46351. var gamepad = this.inputs.attached["gamepad"];
  46352. if (gamepad)
  46353. gamepad.gamepadAngularSensibility = value;
  46354. },
  46355. enumerable: true,
  46356. configurable: true
  46357. });
  46358. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46359. get: function () {
  46360. var gamepad = this.inputs.attached["gamepad"];
  46361. if (gamepad)
  46362. return gamepad.gamepadMoveSensibility;
  46363. },
  46364. set: function (value) {
  46365. var gamepad = this.inputs.attached["gamepad"];
  46366. if (gamepad)
  46367. gamepad.gamepadMoveSensibility = value;
  46368. },
  46369. enumerable: true,
  46370. configurable: true
  46371. });
  46372. UniversalCamera.prototype.getClassName = function () {
  46373. return "UniversalCamera";
  46374. };
  46375. return UniversalCamera;
  46376. }(BABYLON.TouchCamera));
  46377. BABYLON.UniversalCamera = UniversalCamera;
  46378. })(BABYLON || (BABYLON = {}));
  46379. //# sourceMappingURL=babylon.universalCamera.js.map
  46380. var BABYLON;
  46381. (function (BABYLON) {
  46382. var Gamepads = (function () {
  46383. function Gamepads(ongamedpadconnected) {
  46384. var _this = this;
  46385. this.babylonGamepads = [];
  46386. this.oneGamepadConnected = false;
  46387. this.isMonitoring = false;
  46388. this.gamepadEventSupported = 'GamepadEvent' in window;
  46389. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46390. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46391. this._callbackGamepadConnected = ongamedpadconnected;
  46392. if (this.gamepadSupportAvailable) {
  46393. // Checking if the gamepad connected event is supported (like in Firefox)
  46394. if (this.gamepadEventSupported) {
  46395. this._onGamepadConnectedEvent = function (evt) {
  46396. _this._onGamepadConnected(evt);
  46397. };
  46398. this._onGamepadDisonnectedEvent = function (evt) {
  46399. _this._onGamepadDisconnected(evt);
  46400. };
  46401. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46402. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46403. }
  46404. else {
  46405. this._startMonitoringGamepads();
  46406. }
  46407. }
  46408. }
  46409. Gamepads.prototype.dispose = function () {
  46410. if (Gamepads.gamepadDOMInfo) {
  46411. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46412. }
  46413. if (this._onGamepadConnectedEvent) {
  46414. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46415. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46416. this._onGamepadConnectedEvent = null;
  46417. this._onGamepadDisonnectedEvent = null;
  46418. }
  46419. };
  46420. Gamepads.prototype._onGamepadConnected = function (evt) {
  46421. var newGamepad = this._addNewGamepad(evt.gamepad);
  46422. if (this._callbackGamepadConnected)
  46423. this._callbackGamepadConnected(newGamepad);
  46424. this._startMonitoringGamepads();
  46425. };
  46426. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46427. if (!this.oneGamepadConnected) {
  46428. this.oneGamepadConnected = true;
  46429. if (Gamepads.gamepadDOMInfo) {
  46430. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46431. Gamepads.gamepadDOMInfo = null;
  46432. }
  46433. }
  46434. var newGamepad;
  46435. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46436. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46437. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46438. }
  46439. else {
  46440. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46441. }
  46442. this.babylonGamepads.push(newGamepad);
  46443. return newGamepad;
  46444. };
  46445. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  46446. // Remove the gamepad from the list of gamepads to monitor.
  46447. for (var i in this.babylonGamepads) {
  46448. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  46449. this.babylonGamepads.splice(+i, 1);
  46450. break;
  46451. }
  46452. }
  46453. // If no gamepads are left, stop the polling loop.
  46454. if (this.babylonGamepads.length == 0) {
  46455. this._stopMonitoringGamepads();
  46456. }
  46457. };
  46458. Gamepads.prototype._startMonitoringGamepads = function () {
  46459. if (!this.isMonitoring) {
  46460. this.isMonitoring = true;
  46461. this._checkGamepadsStatus();
  46462. }
  46463. };
  46464. Gamepads.prototype._stopMonitoringGamepads = function () {
  46465. this.isMonitoring = false;
  46466. };
  46467. Gamepads.prototype._checkGamepadsStatus = function () {
  46468. var _this = this;
  46469. // updating gamepad objects
  46470. this._updateGamepadObjects();
  46471. for (var i in this.babylonGamepads) {
  46472. this.babylonGamepads[i].update();
  46473. }
  46474. if (this.isMonitoring) {
  46475. if (window.requestAnimationFrame) {
  46476. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46477. }
  46478. else if (window.mozRequestAnimationFrame) {
  46479. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46480. }
  46481. else if (window.webkitRequestAnimationFrame) {
  46482. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46483. }
  46484. }
  46485. };
  46486. // This function is called only on Chrome, which does not yet support
  46487. // connection/disconnection events, but requires you to monitor
  46488. // an array for changes.
  46489. Gamepads.prototype._updateGamepadObjects = function () {
  46490. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  46491. for (var i = 0; i < gamepads.length; i++) {
  46492. if (gamepads[i]) {
  46493. if (!(gamepads[i].index in this.babylonGamepads)) {
  46494. var newGamepad = this._addNewGamepad(gamepads[i]);
  46495. if (this._callbackGamepadConnected) {
  46496. this._callbackGamepadConnected(newGamepad);
  46497. }
  46498. }
  46499. else {
  46500. this.babylonGamepads[i].browserGamepad = gamepads[i];
  46501. }
  46502. }
  46503. }
  46504. };
  46505. return Gamepads;
  46506. }());
  46507. BABYLON.Gamepads = Gamepads;
  46508. var StickValues = (function () {
  46509. function StickValues(x, y) {
  46510. this.x = x;
  46511. this.y = y;
  46512. }
  46513. return StickValues;
  46514. }());
  46515. BABYLON.StickValues = StickValues;
  46516. var Gamepad = (function () {
  46517. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  46518. if (leftStickX === void 0) { leftStickX = 0; }
  46519. if (leftStickY === void 0) { leftStickY = 1; }
  46520. if (rightStickX === void 0) { rightStickX = 2; }
  46521. if (rightStickY === void 0) { rightStickY = 3; }
  46522. this.id = id;
  46523. this.index = index;
  46524. this.browserGamepad = browserGamepad;
  46525. this._leftStickAxisX = leftStickX;
  46526. this._leftStickAxisY = leftStickY;
  46527. this._rightStickAxisX = rightStickX;
  46528. this._rightStickAxisY = rightStickY;
  46529. if (this.browserGamepad.axes.length >= 2) {
  46530. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46531. }
  46532. if (this.browserGamepad.axes.length >= 4) {
  46533. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46534. }
  46535. }
  46536. Gamepad.prototype.onleftstickchanged = function (callback) {
  46537. this._onleftstickchanged = callback;
  46538. };
  46539. Gamepad.prototype.onrightstickchanged = function (callback) {
  46540. this._onrightstickchanged = callback;
  46541. };
  46542. Object.defineProperty(Gamepad.prototype, "leftStick", {
  46543. get: function () {
  46544. return this._leftStick;
  46545. },
  46546. set: function (newValues) {
  46547. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  46548. this._onleftstickchanged(newValues);
  46549. }
  46550. this._leftStick = newValues;
  46551. },
  46552. enumerable: true,
  46553. configurable: true
  46554. });
  46555. Object.defineProperty(Gamepad.prototype, "rightStick", {
  46556. get: function () {
  46557. return this._rightStick;
  46558. },
  46559. set: function (newValues) {
  46560. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  46561. this._onrightstickchanged(newValues);
  46562. }
  46563. this._rightStick = newValues;
  46564. },
  46565. enumerable: true,
  46566. configurable: true
  46567. });
  46568. Gamepad.prototype.update = function () {
  46569. if (this._leftStick) {
  46570. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46571. }
  46572. if (this._rightStick) {
  46573. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46574. }
  46575. };
  46576. return Gamepad;
  46577. }());
  46578. BABYLON.Gamepad = Gamepad;
  46579. var GenericPad = (function (_super) {
  46580. __extends(GenericPad, _super);
  46581. function GenericPad(id, index, gamepad) {
  46582. var _this = _super.call(this, id, index, gamepad) || this;
  46583. _this.id = id;
  46584. _this.index = index;
  46585. _this.gamepad = gamepad;
  46586. _this._buttons = new Array(gamepad.buttons.length);
  46587. return _this;
  46588. }
  46589. GenericPad.prototype.onbuttondown = function (callback) {
  46590. this._onbuttondown = callback;
  46591. };
  46592. GenericPad.prototype.onbuttonup = function (callback) {
  46593. this._onbuttonup = callback;
  46594. };
  46595. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  46596. if (newValue !== currentValue) {
  46597. if (this._onbuttondown && newValue === 1) {
  46598. this._onbuttondown(buttonIndex);
  46599. }
  46600. if (this._onbuttonup && newValue === 0) {
  46601. this._onbuttonup(buttonIndex);
  46602. }
  46603. }
  46604. return newValue;
  46605. };
  46606. GenericPad.prototype.update = function () {
  46607. _super.prototype.update.call(this);
  46608. for (var index = 0; index < this._buttons.length; index++) {
  46609. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  46610. }
  46611. };
  46612. return GenericPad;
  46613. }(Gamepad));
  46614. BABYLON.GenericPad = GenericPad;
  46615. var Xbox360Button;
  46616. (function (Xbox360Button) {
  46617. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  46618. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  46619. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  46620. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  46621. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  46622. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  46623. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  46624. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  46625. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  46626. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  46627. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  46628. var Xbox360Dpad;
  46629. (function (Xbox360Dpad) {
  46630. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  46631. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  46632. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  46633. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  46634. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  46635. var Xbox360Pad = (function (_super) {
  46636. __extends(Xbox360Pad, _super);
  46637. function Xbox360Pad(id, index, gamepad, xboxOne) {
  46638. if (xboxOne === void 0) { xboxOne = false; }
  46639. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  46640. _this._leftTrigger = 0;
  46641. _this._rightTrigger = 0;
  46642. _this._buttonA = 0;
  46643. _this._buttonB = 0;
  46644. _this._buttonX = 0;
  46645. _this._buttonY = 0;
  46646. _this._buttonBack = 0;
  46647. _this._buttonStart = 0;
  46648. _this._buttonLB = 0;
  46649. _this._buttonRB = 0;
  46650. _this._buttonLeftStick = 0;
  46651. _this._buttonRightStick = 0;
  46652. _this._dPadUp = 0;
  46653. _this._dPadDown = 0;
  46654. _this._dPadLeft = 0;
  46655. _this._dPadRight = 0;
  46656. _this._isXboxOnePad = false;
  46657. _this._isXboxOnePad = xboxOne;
  46658. return _this;
  46659. }
  46660. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  46661. this._onlefttriggerchanged = callback;
  46662. };
  46663. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  46664. this._onrighttriggerchanged = callback;
  46665. };
  46666. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  46667. get: function () {
  46668. return this._leftTrigger;
  46669. },
  46670. set: function (newValue) {
  46671. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  46672. this._onlefttriggerchanged(newValue);
  46673. }
  46674. this._leftTrigger = newValue;
  46675. },
  46676. enumerable: true,
  46677. configurable: true
  46678. });
  46679. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  46680. get: function () {
  46681. return this._rightTrigger;
  46682. },
  46683. set: function (newValue) {
  46684. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  46685. this._onrighttriggerchanged(newValue);
  46686. }
  46687. this._rightTrigger = newValue;
  46688. },
  46689. enumerable: true,
  46690. configurable: true
  46691. });
  46692. Xbox360Pad.prototype.onbuttondown = function (callback) {
  46693. this._onbuttondown = callback;
  46694. };
  46695. Xbox360Pad.prototype.onbuttonup = function (callback) {
  46696. this._onbuttonup = callback;
  46697. };
  46698. Xbox360Pad.prototype.ondpaddown = function (callback) {
  46699. this._ondpaddown = callback;
  46700. };
  46701. Xbox360Pad.prototype.ondpadup = function (callback) {
  46702. this._ondpadup = callback;
  46703. };
  46704. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  46705. if (newValue !== currentValue) {
  46706. if (this._onbuttondown && newValue === 1) {
  46707. this._onbuttondown(buttonType);
  46708. }
  46709. if (this._onbuttonup && newValue === 0) {
  46710. this._onbuttonup(buttonType);
  46711. }
  46712. }
  46713. return newValue;
  46714. };
  46715. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  46716. if (newValue !== currentValue) {
  46717. if (this._ondpaddown && newValue === 1) {
  46718. this._ondpaddown(buttonType);
  46719. }
  46720. if (this._ondpadup && newValue === 0) {
  46721. this._ondpadup(buttonType);
  46722. }
  46723. }
  46724. return newValue;
  46725. };
  46726. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  46727. get: function () {
  46728. return this._buttonA;
  46729. },
  46730. set: function (value) {
  46731. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  46732. },
  46733. enumerable: true,
  46734. configurable: true
  46735. });
  46736. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  46737. get: function () {
  46738. return this._buttonB;
  46739. },
  46740. set: function (value) {
  46741. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  46742. },
  46743. enumerable: true,
  46744. configurable: true
  46745. });
  46746. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  46747. get: function () {
  46748. return this._buttonX;
  46749. },
  46750. set: function (value) {
  46751. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  46752. },
  46753. enumerable: true,
  46754. configurable: true
  46755. });
  46756. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  46757. get: function () {
  46758. return this._buttonY;
  46759. },
  46760. set: function (value) {
  46761. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  46762. },
  46763. enumerable: true,
  46764. configurable: true
  46765. });
  46766. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  46767. get: function () {
  46768. return this._buttonStart;
  46769. },
  46770. set: function (value) {
  46771. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  46772. },
  46773. enumerable: true,
  46774. configurable: true
  46775. });
  46776. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  46777. get: function () {
  46778. return this._buttonBack;
  46779. },
  46780. set: function (value) {
  46781. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  46782. },
  46783. enumerable: true,
  46784. configurable: true
  46785. });
  46786. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  46787. get: function () {
  46788. return this._buttonLB;
  46789. },
  46790. set: function (value) {
  46791. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  46792. },
  46793. enumerable: true,
  46794. configurable: true
  46795. });
  46796. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  46797. get: function () {
  46798. return this._buttonRB;
  46799. },
  46800. set: function (value) {
  46801. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  46802. },
  46803. enumerable: true,
  46804. configurable: true
  46805. });
  46806. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  46807. get: function () {
  46808. return this._buttonLeftStick;
  46809. },
  46810. set: function (value) {
  46811. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  46812. },
  46813. enumerable: true,
  46814. configurable: true
  46815. });
  46816. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  46817. get: function () {
  46818. return this._buttonRightStick;
  46819. },
  46820. set: function (value) {
  46821. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  46822. },
  46823. enumerable: true,
  46824. configurable: true
  46825. });
  46826. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  46827. get: function () {
  46828. return this._dPadUp;
  46829. },
  46830. set: function (value) {
  46831. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  46832. },
  46833. enumerable: true,
  46834. configurable: true
  46835. });
  46836. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  46837. get: function () {
  46838. return this._dPadDown;
  46839. },
  46840. set: function (value) {
  46841. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  46842. },
  46843. enumerable: true,
  46844. configurable: true
  46845. });
  46846. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  46847. get: function () {
  46848. return this._dPadLeft;
  46849. },
  46850. set: function (value) {
  46851. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  46852. },
  46853. enumerable: true,
  46854. configurable: true
  46855. });
  46856. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  46857. get: function () {
  46858. return this._dPadRight;
  46859. },
  46860. set: function (value) {
  46861. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  46862. },
  46863. enumerable: true,
  46864. configurable: true
  46865. });
  46866. Xbox360Pad.prototype.update = function () {
  46867. _super.prototype.update.call(this);
  46868. if (this._isXboxOnePad) {
  46869. this.buttonA = this.browserGamepad.buttons[0].value;
  46870. this.buttonB = this.browserGamepad.buttons[1].value;
  46871. this.buttonX = this.browserGamepad.buttons[2].value;
  46872. this.buttonY = this.browserGamepad.buttons[3].value;
  46873. this.buttonLB = this.browserGamepad.buttons[4].value;
  46874. this.buttonRB = this.browserGamepad.buttons[5].value;
  46875. this.leftTrigger = this.browserGamepad.axes[2];
  46876. this.rightTrigger = this.browserGamepad.axes[5];
  46877. this.buttonBack = this.browserGamepad.buttons[9].value;
  46878. this.buttonStart = this.browserGamepad.buttons[8].value;
  46879. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  46880. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  46881. this.dPadUp = this.browserGamepad.buttons[11].value;
  46882. this.dPadDown = this.browserGamepad.buttons[12].value;
  46883. this.dPadLeft = this.browserGamepad.buttons[13].value;
  46884. this.dPadRight = this.browserGamepad.buttons[14].value;
  46885. }
  46886. else {
  46887. this.buttonA = this.browserGamepad.buttons[0].value;
  46888. this.buttonB = this.browserGamepad.buttons[1].value;
  46889. this.buttonX = this.browserGamepad.buttons[2].value;
  46890. this.buttonY = this.browserGamepad.buttons[3].value;
  46891. this.buttonLB = this.browserGamepad.buttons[4].value;
  46892. this.buttonRB = this.browserGamepad.buttons[5].value;
  46893. this.leftTrigger = this.browserGamepad.buttons[6].value;
  46894. this.rightTrigger = this.browserGamepad.buttons[7].value;
  46895. this.buttonBack = this.browserGamepad.buttons[8].value;
  46896. this.buttonStart = this.browserGamepad.buttons[9].value;
  46897. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  46898. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  46899. this.dPadUp = this.browserGamepad.buttons[12].value;
  46900. this.dPadDown = this.browserGamepad.buttons[13].value;
  46901. this.dPadLeft = this.browserGamepad.buttons[14].value;
  46902. this.dPadRight = this.browserGamepad.buttons[15].value;
  46903. }
  46904. };
  46905. return Xbox360Pad;
  46906. }(Gamepad));
  46907. BABYLON.Xbox360Pad = Xbox360Pad;
  46908. })(BABYLON || (BABYLON = {}));
  46909. //# sourceMappingURL=babylon.gamepads.js.map
  46910. var BABYLON;
  46911. (function (BABYLON) {
  46912. // We're mainly based on the logic defined into the FreeCamera code
  46913. var GamepadCamera = (function (_super) {
  46914. __extends(GamepadCamera, _super);
  46915. //-- end properties for backward compatibility for inputs
  46916. function GamepadCamera(name, position, scene) {
  46917. var _this;
  46918. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  46919. _this = _super.call(this, name, position, scene) || this;
  46920. return _this;
  46921. }
  46922. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46923. //-- Begin properties for backward compatibility for inputs
  46924. get: function () {
  46925. var gamepad = this.inputs.attached["gamepad"];
  46926. if (gamepad)
  46927. return gamepad.gamepadAngularSensibility;
  46928. },
  46929. set: function (value) {
  46930. var gamepad = this.inputs.attached["gamepad"];
  46931. if (gamepad)
  46932. gamepad.gamepadAngularSensibility = value;
  46933. },
  46934. enumerable: true,
  46935. configurable: true
  46936. });
  46937. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46938. get: function () {
  46939. var gamepad = this.inputs.attached["gamepad"];
  46940. if (gamepad)
  46941. return gamepad.gamepadMoveSensibility;
  46942. },
  46943. set: function (value) {
  46944. var gamepad = this.inputs.attached["gamepad"];
  46945. if (gamepad)
  46946. gamepad.gamepadMoveSensibility = value;
  46947. },
  46948. enumerable: true,
  46949. configurable: true
  46950. });
  46951. GamepadCamera.prototype.getClassName = function () {
  46952. return "GamepadCamera";
  46953. };
  46954. return GamepadCamera;
  46955. }(BABYLON.UniversalCamera));
  46956. BABYLON.GamepadCamera = GamepadCamera;
  46957. })(BABYLON || (BABYLON = {}));
  46958. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46959. var BABYLON;
  46960. (function (BABYLON) {
  46961. var Analyser = (function () {
  46962. function Analyser(scene) {
  46963. this.SMOOTHING = 0.75;
  46964. this.FFT_SIZE = 512;
  46965. this.BARGRAPHAMPLITUDE = 256;
  46966. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  46967. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  46968. this._scene = scene;
  46969. this._audioEngine = BABYLON.Engine.audioEngine;
  46970. if (this._audioEngine.canUseWebAudio) {
  46971. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  46972. this._webAudioAnalyser.minDecibels = -140;
  46973. this._webAudioAnalyser.maxDecibels = 0;
  46974. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46975. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46976. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  46977. }
  46978. }
  46979. Analyser.prototype.getFrequencyBinCount = function () {
  46980. if (this._audioEngine.canUseWebAudio) {
  46981. return this._webAudioAnalyser.frequencyBinCount;
  46982. }
  46983. else {
  46984. return 0;
  46985. }
  46986. };
  46987. Analyser.prototype.getByteFrequencyData = function () {
  46988. if (this._audioEngine.canUseWebAudio) {
  46989. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46990. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46991. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  46992. }
  46993. return this._byteFreqs;
  46994. };
  46995. Analyser.prototype.getByteTimeDomainData = function () {
  46996. if (this._audioEngine.canUseWebAudio) {
  46997. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46998. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46999. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47000. }
  47001. return this._byteTime;
  47002. };
  47003. Analyser.prototype.getFloatFrequencyData = function () {
  47004. if (this._audioEngine.canUseWebAudio) {
  47005. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47006. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47007. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47008. }
  47009. return this._floatFreqs;
  47010. };
  47011. Analyser.prototype.drawDebugCanvas = function () {
  47012. var _this = this;
  47013. if (this._audioEngine.canUseWebAudio) {
  47014. if (!this._debugCanvas) {
  47015. this._debugCanvas = document.createElement("canvas");
  47016. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47017. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47018. this._debugCanvas.style.position = "absolute";
  47019. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47020. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47021. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47022. document.body.appendChild(this._debugCanvas);
  47023. this._registerFunc = function () {
  47024. _this.drawDebugCanvas();
  47025. };
  47026. this._scene.registerBeforeRender(this._registerFunc);
  47027. }
  47028. if (this._registerFunc) {
  47029. var workingArray = this.getByteFrequencyData();
  47030. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47031. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47032. // Draw the frequency domain chart.
  47033. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47034. var value = workingArray[i];
  47035. var percent = value / this.BARGRAPHAMPLITUDE;
  47036. var height = this.DEBUGCANVASSIZE.height * percent;
  47037. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47038. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47039. var hue = i / this.getFrequencyBinCount() * 360;
  47040. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47041. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47042. }
  47043. }
  47044. }
  47045. };
  47046. Analyser.prototype.stopDebugCanvas = function () {
  47047. if (this._debugCanvas) {
  47048. this._scene.unregisterBeforeRender(this._registerFunc);
  47049. this._registerFunc = null;
  47050. document.body.removeChild(this._debugCanvas);
  47051. this._debugCanvas = null;
  47052. this._debugCanvasContext = null;
  47053. }
  47054. };
  47055. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47056. if (this._audioEngine.canUseWebAudio) {
  47057. inputAudioNode.connect(this._webAudioAnalyser);
  47058. this._webAudioAnalyser.connect(outputAudioNode);
  47059. }
  47060. };
  47061. Analyser.prototype.dispose = function () {
  47062. if (this._audioEngine.canUseWebAudio) {
  47063. this._webAudioAnalyser.disconnect();
  47064. }
  47065. };
  47066. return Analyser;
  47067. }());
  47068. BABYLON.Analyser = Analyser;
  47069. })(BABYLON || (BABYLON = {}));
  47070. //# sourceMappingURL=babylon.analyser.js.map
  47071. var BABYLON;
  47072. (function (BABYLON) {
  47073. var DepthRenderer = (function () {
  47074. function DepthRenderer(scene, type) {
  47075. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  47076. var _this = this;
  47077. this._viewMatrix = BABYLON.Matrix.Zero();
  47078. this._projectionMatrix = BABYLON.Matrix.Zero();
  47079. this._transformMatrix = BABYLON.Matrix.Zero();
  47080. this._worldViewProjection = BABYLON.Matrix.Zero();
  47081. this._scene = scene;
  47082. var engine = scene.getEngine();
  47083. // Render target
  47084. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47085. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47086. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47087. this._depthMap.refreshRate = 1;
  47088. this._depthMap.renderParticles = false;
  47089. this._depthMap.renderList = null;
  47090. // set default depth value to 1.0 (far away)
  47091. this._depthMap.onClearObservable.add(function (engine) {
  47092. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47093. });
  47094. // Custom render function
  47095. var renderSubMesh = function (subMesh) {
  47096. var mesh = subMesh.getRenderingMesh();
  47097. var scene = _this._scene;
  47098. var engine = scene.getEngine();
  47099. // Culling
  47100. engine.setState(subMesh.getMaterial().backFaceCulling);
  47101. // Managing instances
  47102. var batch = mesh._getInstancesRenderList(subMesh._id);
  47103. if (batch.mustReturn) {
  47104. return;
  47105. }
  47106. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47107. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47108. engine.enableEffect(_this._effect);
  47109. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47110. var material = subMesh.getMaterial();
  47111. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47112. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47113. // Alpha test
  47114. if (material && material.needAlphaTesting()) {
  47115. var alphaTexture = material.getAlphaTestTexture();
  47116. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47117. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47118. }
  47119. // Bones
  47120. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47121. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47122. }
  47123. // Draw
  47124. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47125. }
  47126. };
  47127. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47128. var index;
  47129. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47130. renderSubMesh(opaqueSubMeshes.data[index]);
  47131. }
  47132. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47133. renderSubMesh(alphaTestSubMeshes.data[index]);
  47134. }
  47135. };
  47136. }
  47137. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47138. var material = subMesh.getMaterial();
  47139. if (material.disableDepthWrite) {
  47140. return false;
  47141. }
  47142. var defines = [];
  47143. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47144. var mesh = subMesh.getMesh();
  47145. var scene = mesh.getScene();
  47146. // Alpha test
  47147. if (material && material.needAlphaTesting()) {
  47148. defines.push("#define ALPHATEST");
  47149. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47150. attribs.push(BABYLON.VertexBuffer.UVKind);
  47151. defines.push("#define UV1");
  47152. }
  47153. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47154. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47155. defines.push("#define UV2");
  47156. }
  47157. }
  47158. // Bones
  47159. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47160. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47161. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47162. if (mesh.numBoneInfluencers > 4) {
  47163. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47164. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47165. }
  47166. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47167. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47168. }
  47169. else {
  47170. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47171. }
  47172. // Instances
  47173. if (useInstances) {
  47174. defines.push("#define INSTANCES");
  47175. attribs.push("world0");
  47176. attribs.push("world1");
  47177. attribs.push("world2");
  47178. attribs.push("world3");
  47179. }
  47180. // Get correct effect
  47181. var join = defines.join("\n");
  47182. if (this._cachedDefines !== join) {
  47183. this._cachedDefines = join;
  47184. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47185. }
  47186. return this._effect.isReady();
  47187. };
  47188. DepthRenderer.prototype.getDepthMap = function () {
  47189. return this._depthMap;
  47190. };
  47191. // Methods
  47192. DepthRenderer.prototype.dispose = function () {
  47193. this._depthMap.dispose();
  47194. };
  47195. return DepthRenderer;
  47196. }());
  47197. BABYLON.DepthRenderer = DepthRenderer;
  47198. })(BABYLON || (BABYLON = {}));
  47199. //# sourceMappingURL=babylon.depthRenderer.js.map
  47200. var BABYLON;
  47201. (function (BABYLON) {
  47202. var SSAORenderingPipeline = (function (_super) {
  47203. __extends(SSAORenderingPipeline, _super);
  47204. /**
  47205. * @constructor
  47206. * @param {string} name - The rendering pipeline name
  47207. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47208. * @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 }
  47209. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47210. */
  47211. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47212. var _this = _super.call(this, scene.getEngine(), name) || this;
  47213. // Members
  47214. /**
  47215. * The PassPostProcess id in the pipeline that contains the original scene color
  47216. * @type {string}
  47217. */
  47218. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47219. /**
  47220. * The SSAO PostProcess id in the pipeline
  47221. * @type {string}
  47222. */
  47223. _this.SSAORenderEffect = "SSAORenderEffect";
  47224. /**
  47225. * The horizontal blur PostProcess id in the pipeline
  47226. * @type {string}
  47227. */
  47228. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47229. /**
  47230. * The vertical blur PostProcess id in the pipeline
  47231. * @type {string}
  47232. */
  47233. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47234. /**
  47235. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47236. * @type {string}
  47237. */
  47238. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47239. /**
  47240. * The output strength of the SSAO post-process. Default value is 1.0.
  47241. * @type {number}
  47242. */
  47243. _this.totalStrength = 1.0;
  47244. /**
  47245. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47246. * @type {number}
  47247. */
  47248. _this.radius = 0.0001;
  47249. /**
  47250. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47251. * Must not be equal to fallOff and superior to fallOff.
  47252. * Default value is 0.975
  47253. * @type {number}
  47254. */
  47255. _this.area = 0.0075;
  47256. /**
  47257. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47258. * Must not be equal to area and inferior to area.
  47259. * Default value is 0.0
  47260. * @type {number}
  47261. */
  47262. _this.fallOff = 0.000001;
  47263. /**
  47264. * The base color of the SSAO post-process
  47265. * The final result is "base + ssao" between [0, 1]
  47266. * @type {number}
  47267. */
  47268. _this.base = 0.5;
  47269. _this._firstUpdate = true;
  47270. _this._scene = scene;
  47271. // Set up assets
  47272. _this._createRandomTexture();
  47273. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47274. var ssaoRatio = ratio.ssaoRatio || ratio;
  47275. var combineRatio = ratio.combineRatio || ratio;
  47276. _this._ratio = {
  47277. ssaoRatio: ssaoRatio,
  47278. combineRatio: combineRatio
  47279. };
  47280. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47281. _this._createSSAOPostProcess(ssaoRatio);
  47282. _this._createBlurPostProcess(ssaoRatio);
  47283. _this._createSSAOCombinePostProcess(combineRatio);
  47284. // Set up pipeline
  47285. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47286. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47287. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47288. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47289. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47290. // Finish
  47291. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47292. if (cameras)
  47293. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47294. return _this;
  47295. }
  47296. // Public Methods
  47297. /**
  47298. * Returns the horizontal blur PostProcess
  47299. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47300. */
  47301. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47302. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47303. return null;
  47304. };
  47305. /**
  47306. * Returns the vertical blur PostProcess
  47307. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47308. */
  47309. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47310. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47311. return null;
  47312. };
  47313. /**
  47314. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47315. */
  47316. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47317. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47318. for (var i = 0; i < this._scene.cameras.length; i++) {
  47319. var camera = this._scene.cameras[i];
  47320. this._originalColorPostProcess.dispose(camera);
  47321. this._ssaoPostProcess.dispose(camera);
  47322. this._blurHPostProcess.dispose(camera);
  47323. this._blurVPostProcess.dispose(camera);
  47324. this._ssaoCombinePostProcess.dispose(camera);
  47325. }
  47326. this._randomTexture.dispose();
  47327. if (disableDepthRender)
  47328. this._scene.disableDepthRenderer();
  47329. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47330. };
  47331. // Private Methods
  47332. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47333. var _this = this;
  47334. /*
  47335. var samplerOffsets = [
  47336. -8.0, -6.0, -4.0, -2.0,
  47337. 0.0,
  47338. 2.0, 4.0, 6.0, 8.0
  47339. ];
  47340. */
  47341. var samples = 16;
  47342. var samplerOffsets = [];
  47343. for (var i = -8; i < 8; i++) {
  47344. samplerOffsets.push(i * 2);
  47345. }
  47346. 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");
  47347. this._blurHPostProcess.onApply = function (effect) {
  47348. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47349. effect.setTexture("depthSampler", _this._depthTexture);
  47350. if (_this._firstUpdate) {
  47351. effect.setArray("samplerOffsets", samplerOffsets);
  47352. }
  47353. };
  47354. 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");
  47355. this._blurVPostProcess.onApply = function (effect) {
  47356. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47357. effect.setTexture("depthSampler", _this._depthTexture);
  47358. if (_this._firstUpdate) {
  47359. effect.setArray("samplerOffsets", samplerOffsets);
  47360. _this._firstUpdate = false;
  47361. }
  47362. };
  47363. };
  47364. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47365. var _this = this;
  47366. var numSamples = 16;
  47367. var sampleSphere = [
  47368. 0.5381, 0.1856, -0.4319,
  47369. 0.1379, 0.2486, 0.4430,
  47370. 0.3371, 0.5679, -0.0057,
  47371. -0.6999, -0.0451, -0.0019,
  47372. 0.0689, -0.1598, -0.8547,
  47373. 0.0560, 0.0069, -0.1843,
  47374. -0.0146, 0.1402, 0.0762,
  47375. 0.0100, -0.1924, -0.0344,
  47376. -0.3577, -0.5301, -0.4358,
  47377. -0.3169, 0.1063, 0.0158,
  47378. 0.0103, -0.5869, 0.0046,
  47379. -0.0897, -0.4940, 0.3287,
  47380. 0.7119, -0.0154, -0.0918,
  47381. -0.0533, 0.0596, -0.5411,
  47382. 0.0352, -0.0631, 0.5460,
  47383. -0.4776, 0.2847, -0.0271
  47384. ];
  47385. var samplesFactor = 1.0 / numSamples;
  47386. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47387. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47388. "area", "fallOff", "base", "range", "viewport"
  47389. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47390. var viewport = new BABYLON.Vector2(0, 0);
  47391. this._ssaoPostProcess.onApply = function (effect) {
  47392. if (_this._firstUpdate) {
  47393. effect.setArray3("sampleSphere", sampleSphere);
  47394. effect.setFloat("samplesFactor", samplesFactor);
  47395. effect.setFloat("randTextureTiles", 4.0);
  47396. }
  47397. effect.setFloat("totalStrength", _this.totalStrength);
  47398. effect.setFloat("radius", _this.radius);
  47399. effect.setFloat("area", _this.area);
  47400. effect.setFloat("fallOff", _this.fallOff);
  47401. effect.setFloat("base", _this.base);
  47402. effect.setTexture("textureSampler", _this._depthTexture);
  47403. effect.setTexture("randomSampler", _this._randomTexture);
  47404. };
  47405. };
  47406. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47407. var _this = this;
  47408. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47409. this._ssaoCombinePostProcess.onApply = function (effect) {
  47410. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47411. };
  47412. };
  47413. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47414. var size = 512;
  47415. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47416. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47417. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47418. var context = this._randomTexture.getContext();
  47419. var rand = function (min, max) {
  47420. return Math.random() * (max - min) + min;
  47421. };
  47422. var randVector = BABYLON.Vector3.Zero();
  47423. for (var x = 0; x < size; x++) {
  47424. for (var y = 0; y < size; y++) {
  47425. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47426. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47427. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47428. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47429. context.fillRect(x, y, 1, 1);
  47430. }
  47431. }
  47432. this._randomTexture.update(false);
  47433. };
  47434. return SSAORenderingPipeline;
  47435. }(BABYLON.PostProcessRenderPipeline));
  47436. __decorate([
  47437. BABYLON.serialize()
  47438. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47439. __decorate([
  47440. BABYLON.serialize()
  47441. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47442. __decorate([
  47443. BABYLON.serialize()
  47444. ], SSAORenderingPipeline.prototype, "area", void 0);
  47445. __decorate([
  47446. BABYLON.serialize()
  47447. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47448. __decorate([
  47449. BABYLON.serialize()
  47450. ], SSAORenderingPipeline.prototype, "base", void 0);
  47451. __decorate([
  47452. BABYLON.serialize()
  47453. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47454. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47455. })(BABYLON || (BABYLON = {}));
  47456. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47457. var BABYLON;
  47458. (function (BABYLON) {
  47459. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47460. var VolumetricLightScatteringPostProcess = (function (_super) {
  47461. __extends(VolumetricLightScatteringPostProcess, _super);
  47462. /**
  47463. * @constructor
  47464. * @param {string} name - The post-process name
  47465. * @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)
  47466. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47467. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47468. * @param {number} samples - The post-process quality, default 100
  47469. * @param {number} samplingMode - The post-process filtering mode
  47470. * @param {BABYLON.Engine} engine - The babylon engine
  47471. * @param {boolean} reusable - If the post-process is reusable
  47472. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47473. */
  47474. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47475. if (samples === void 0) { samples = 100; }
  47476. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47477. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  47478. _this._screenCoordinates = BABYLON.Vector2.Zero();
  47479. /**
  47480. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47481. * @type {Vector3}
  47482. */
  47483. _this.customMeshPosition = BABYLON.Vector3.Zero();
  47484. /**
  47485. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47486. * @type {boolean}
  47487. */
  47488. _this.useCustomMeshPosition = false;
  47489. /**
  47490. * If the post-process should inverse the light scattering direction
  47491. * @type {boolean}
  47492. */
  47493. _this.invert = true;
  47494. /**
  47495. * Array containing the excluded meshes not rendered in the internal pass
  47496. */
  47497. _this.excludedMeshes = new Array();
  47498. /**
  47499. * Controls the overall intensity of the post-process
  47500. * @type {number}
  47501. */
  47502. _this.exposure = 0.3;
  47503. /**
  47504. * Dissipates each sample's contribution in range [0, 1]
  47505. * @type {number}
  47506. */
  47507. _this.decay = 0.96815;
  47508. /**
  47509. * Controls the overall intensity of each sample
  47510. * @type {number}
  47511. */
  47512. _this.weight = 0.58767;
  47513. /**
  47514. * Controls the density of each sample
  47515. * @type {number}
  47516. */
  47517. _this.density = 0.926;
  47518. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47519. var engine = scene.getEngine();
  47520. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47521. // Configure mesh
  47522. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47523. // Configure
  47524. _this._createPass(scene, ratio.passRatio || ratio);
  47525. _this.onActivate = function (camera) {
  47526. if (!_this.isSupported) {
  47527. _this.dispose(camera);
  47528. }
  47529. _this.onActivate = null;
  47530. };
  47531. _this.onApplyObservable.add(function (effect) {
  47532. _this._updateMeshScreenCoordinates(scene);
  47533. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47534. effect.setFloat("exposure", _this.exposure);
  47535. effect.setFloat("decay", _this.decay);
  47536. effect.setFloat("weight", _this.weight);
  47537. effect.setFloat("density", _this.density);
  47538. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47539. });
  47540. return _this;
  47541. }
  47542. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47543. get: function () {
  47544. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47545. return false;
  47546. },
  47547. set: function (useDiffuseColor) {
  47548. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47549. },
  47550. enumerable: true,
  47551. configurable: true
  47552. });
  47553. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47554. var mesh = subMesh.getMesh();
  47555. // Render this.mesh as default
  47556. if (mesh === this.mesh) {
  47557. return mesh.material.isReady(mesh);
  47558. }
  47559. var defines = [];
  47560. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47561. var material = subMesh.getMaterial();
  47562. var needUV = false;
  47563. // Alpha test
  47564. if (material) {
  47565. if (material.needAlphaTesting()) {
  47566. defines.push("#define ALPHATEST");
  47567. }
  47568. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47569. attribs.push(BABYLON.VertexBuffer.UVKind);
  47570. defines.push("#define UV1");
  47571. }
  47572. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47573. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47574. defines.push("#define UV2");
  47575. }
  47576. }
  47577. // Bones
  47578. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47579. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47580. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47581. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47582. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47583. }
  47584. else {
  47585. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47586. }
  47587. // Instances
  47588. if (useInstances) {
  47589. defines.push("#define INSTANCES");
  47590. attribs.push("world0");
  47591. attribs.push("world1");
  47592. attribs.push("world2");
  47593. attribs.push("world3");
  47594. }
  47595. // Get correct effect
  47596. var join = defines.join("\n");
  47597. if (this._cachedDefines !== join) {
  47598. this._cachedDefines = join;
  47599. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47600. }
  47601. return this._volumetricLightScatteringPass.isReady();
  47602. };
  47603. /**
  47604. * Sets the new light position for light scattering effect
  47605. * @param {BABYLON.Vector3} The new custom light position
  47606. */
  47607. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47608. this.customMeshPosition = position;
  47609. };
  47610. /**
  47611. * Returns the light position for light scattering effect
  47612. * @return {BABYLON.Vector3} The custom light position
  47613. */
  47614. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47615. return this.customMeshPosition;
  47616. };
  47617. /**
  47618. * Disposes the internal assets and detaches the post-process from the camera
  47619. */
  47620. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47621. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47622. if (rttIndex !== -1) {
  47623. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47624. }
  47625. this._volumetricLightScatteringRTT.dispose();
  47626. _super.prototype.dispose.call(this, camera);
  47627. };
  47628. /**
  47629. * Returns the render target texture used by the post-process
  47630. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47631. */
  47632. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47633. return this._volumetricLightScatteringRTT;
  47634. };
  47635. // Private methods
  47636. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47637. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47638. return true;
  47639. }
  47640. return false;
  47641. };
  47642. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47643. var _this = this;
  47644. var engine = scene.getEngine();
  47645. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47646. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47647. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47648. this._volumetricLightScatteringRTT.renderList = null;
  47649. this._volumetricLightScatteringRTT.renderParticles = false;
  47650. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47651. // Custom render function for submeshes
  47652. var renderSubMesh = function (subMesh) {
  47653. var mesh = subMesh.getRenderingMesh();
  47654. if (_this._meshExcluded(mesh)) {
  47655. return;
  47656. }
  47657. var scene = mesh.getScene();
  47658. var engine = scene.getEngine();
  47659. // Culling
  47660. engine.setState(subMesh.getMaterial().backFaceCulling);
  47661. // Managing instances
  47662. var batch = mesh._getInstancesRenderList(subMesh._id);
  47663. if (batch.mustReturn) {
  47664. return;
  47665. }
  47666. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47667. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47668. var effect = _this._volumetricLightScatteringPass;
  47669. if (mesh === _this.mesh) {
  47670. effect = subMesh.getMaterial().getEffect();
  47671. }
  47672. engine.enableEffect(effect);
  47673. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47674. if (mesh === _this.mesh) {
  47675. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47676. }
  47677. else {
  47678. var material = subMesh.getMaterial();
  47679. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47680. // Alpha test
  47681. if (material && material.needAlphaTesting()) {
  47682. var alphaTexture = material.getAlphaTestTexture();
  47683. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47684. if (alphaTexture) {
  47685. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47686. }
  47687. }
  47688. // Bones
  47689. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47690. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47691. }
  47692. }
  47693. // Draw
  47694. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47695. }
  47696. };
  47697. // Render target texture callbacks
  47698. var savedSceneClearColor;
  47699. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47700. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47701. savedSceneClearColor = scene.clearColor;
  47702. scene.clearColor = sceneClearColor;
  47703. });
  47704. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47705. scene.clearColor = savedSceneClearColor;
  47706. });
  47707. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47708. var engine = scene.getEngine();
  47709. var index;
  47710. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47711. renderSubMesh(opaqueSubMeshes.data[index]);
  47712. }
  47713. engine.setAlphaTesting(true);
  47714. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47715. renderSubMesh(alphaTestSubMeshes.data[index]);
  47716. }
  47717. engine.setAlphaTesting(false);
  47718. if (transparentSubMeshes.length) {
  47719. // Sort sub meshes
  47720. for (index = 0; index < transparentSubMeshes.length; index++) {
  47721. var submesh = transparentSubMeshes.data[index];
  47722. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47723. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47724. }
  47725. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47726. sortedArray.sort(function (a, b) {
  47727. // Alpha index first
  47728. if (a._alphaIndex > b._alphaIndex) {
  47729. return 1;
  47730. }
  47731. if (a._alphaIndex < b._alphaIndex) {
  47732. return -1;
  47733. }
  47734. // Then distance to camera
  47735. if (a._distanceToCamera < b._distanceToCamera) {
  47736. return 1;
  47737. }
  47738. if (a._distanceToCamera > b._distanceToCamera) {
  47739. return -1;
  47740. }
  47741. return 0;
  47742. });
  47743. // Render sub meshes
  47744. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47745. for (index = 0; index < sortedArray.length; index++) {
  47746. renderSubMesh(sortedArray[index]);
  47747. }
  47748. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47749. }
  47750. };
  47751. };
  47752. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47753. var transform = scene.getTransformMatrix();
  47754. var meshPosition;
  47755. if (this.useCustomMeshPosition) {
  47756. meshPosition = this.customMeshPosition;
  47757. }
  47758. else if (this.attachedNode) {
  47759. meshPosition = this.attachedNode.position;
  47760. }
  47761. else {
  47762. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47763. }
  47764. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47765. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47766. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47767. if (this.invert)
  47768. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47769. };
  47770. // Static methods
  47771. /**
  47772. * Creates a default mesh for the Volumeric Light Scattering post-process
  47773. * @param {string} The mesh name
  47774. * @param {BABYLON.Scene} The scene where to create the mesh
  47775. * @return {BABYLON.Mesh} the default mesh
  47776. */
  47777. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47778. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47779. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47780. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47781. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47782. mesh.material = material;
  47783. return mesh;
  47784. };
  47785. return VolumetricLightScatteringPostProcess;
  47786. }(BABYLON.PostProcess));
  47787. __decorate([
  47788. BABYLON.serializeAsVector3()
  47789. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47790. __decorate([
  47791. BABYLON.serialize()
  47792. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47793. __decorate([
  47794. BABYLON.serialize()
  47795. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47796. __decorate([
  47797. BABYLON.serializeAsMeshReference()
  47798. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47799. __decorate([
  47800. BABYLON.serialize()
  47801. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47802. __decorate([
  47803. BABYLON.serialize()
  47804. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47805. __decorate([
  47806. BABYLON.serialize()
  47807. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47808. __decorate([
  47809. BABYLON.serialize()
  47810. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47811. __decorate([
  47812. BABYLON.serialize()
  47813. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47814. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47815. })(BABYLON || (BABYLON = {}));
  47816. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  47817. // BABYLON.JS Chromatic Aberration GLSL Shader
  47818. // Author: Olivier Guyot
  47819. // Separates very slightly R, G and B colors on the edges of the screen
  47820. // Inspired by Francois Tarlier & Martins Upitis
  47821. var BABYLON;
  47822. (function (BABYLON) {
  47823. var LensRenderingPipeline = (function (_super) {
  47824. __extends(LensRenderingPipeline, _super);
  47825. /**
  47826. * @constructor
  47827. *
  47828. * Effect parameters are as follow:
  47829. * {
  47830. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47831. * edge_blur: number; // from 0 to x (1 for realism)
  47832. * distortion: number; // from 0 to x (1 for realism)
  47833. * grain_amount: number; // from 0 to 1
  47834. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47835. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47836. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47837. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47838. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47839. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47840. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47841. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47842. * }
  47843. * Note: if an effect parameter is unset, effect is disabled
  47844. *
  47845. * @param {string} name - The rendering pipeline name
  47846. * @param {object} parameters - An object containing all parameters (see above)
  47847. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47848. * @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)
  47849. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47850. */
  47851. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47852. if (ratio === void 0) { ratio = 1.0; }
  47853. var _this = _super.call(this, scene.getEngine(), name) || this;
  47854. // Lens effects can be of the following:
  47855. // - chromatic aberration (slight shift of RGB colors)
  47856. // - blur on the edge of the lens
  47857. // - lens distortion
  47858. // - depth-of-field blur & highlights enhancing
  47859. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47860. // - grain effect (noise or custom texture)
  47861. // Two additional texture samplers are needed:
  47862. // - depth map (for depth-of-field)
  47863. // - grain texture
  47864. /**
  47865. * The chromatic aberration PostProcess id in the pipeline
  47866. * @type {string}
  47867. */
  47868. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47869. /**
  47870. * The highlights enhancing PostProcess id in the pipeline
  47871. * @type {string}
  47872. */
  47873. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47874. /**
  47875. * The depth-of-field PostProcess id in the pipeline
  47876. * @type {string}
  47877. */
  47878. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47879. _this._scene = scene;
  47880. // Fetch texture samplers
  47881. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47882. if (parameters.grain_texture) {
  47883. _this._grainTexture = parameters.grain_texture;
  47884. }
  47885. else {
  47886. _this._createGrainTexture();
  47887. }
  47888. // save parameters
  47889. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47890. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47891. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47892. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  47893. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47894. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47895. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47896. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47897. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47898. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47899. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47900. // Create effects
  47901. _this._createChromaticAberrationPostProcess(ratio);
  47902. _this._createHighlightsPostProcess(ratio);
  47903. _this._createDepthOfFieldPostProcess(ratio / 4);
  47904. // Set up pipeline
  47905. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47906. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47907. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47908. if (_this._highlightsGain === -1) {
  47909. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  47910. }
  47911. // Finish
  47912. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47913. if (cameras) {
  47914. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47915. }
  47916. return _this;
  47917. }
  47918. // public methods (self explanatory)
  47919. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47920. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47921. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47922. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47923. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47924. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47925. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47926. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47927. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47928. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47929. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47930. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47931. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47932. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47933. };
  47934. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47935. this._highlightsPostProcess.updateEffect();
  47936. };
  47937. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47938. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47939. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47940. this._highlightsGain = amount;
  47941. };
  47942. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47943. if (this._highlightsGain === -1) {
  47944. this._highlightsGain = 1.0;
  47945. }
  47946. this._highlightsThreshold = amount;
  47947. };
  47948. LensRenderingPipeline.prototype.disableHighlights = function () {
  47949. this._highlightsGain = -1;
  47950. };
  47951. /**
  47952. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47953. */
  47954. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47955. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47956. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47957. this._chromaticAberrationPostProcess = undefined;
  47958. this._highlightsPostProcess = undefined;
  47959. this._depthOfFieldPostProcess = undefined;
  47960. this._grainTexture.dispose();
  47961. if (disableDepthRender)
  47962. this._scene.disableDepthRenderer();
  47963. };
  47964. // colors shifting and distortion
  47965. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47966. var _this = this;
  47967. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47968. [], // samplers
  47969. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47970. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47971. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47972. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47973. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47974. };
  47975. };
  47976. // highlights enhancing
  47977. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47978. var _this = this;
  47979. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47980. [], // samplers
  47981. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47982. this._highlightsPostProcess.onApply = function (effect) {
  47983. effect.setFloat('gain', _this._highlightsGain);
  47984. effect.setFloat('threshold', _this._highlightsThreshold);
  47985. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47986. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47987. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47988. };
  47989. };
  47990. // colors shifting and distortion
  47991. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47992. var _this = this;
  47993. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47994. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47995. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47996. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47997. this._depthOfFieldPostProcess.onApply = function (effect) {
  47998. effect.setTexture("depthSampler", _this._depthTexture);
  47999. effect.setTexture("grainSampler", _this._grainTexture);
  48000. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  48001. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  48002. effect.setFloat('grain_amount', _this._grainAmount);
  48003. effect.setBool('blur_noise', _this._blurNoise);
  48004. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48005. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48006. effect.setFloat('distortion', _this._distortion);
  48007. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  48008. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  48009. effect.setFloat('aperture', _this._dofAperture);
  48010. effect.setFloat('darken', _this._dofDarken);
  48011. effect.setFloat('edge_blur', _this._edgeBlur);
  48012. effect.setBool('highlights', (_this._highlightsGain !== -1));
  48013. effect.setFloat('near', _this._scene.activeCamera.minZ);
  48014. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  48015. };
  48016. };
  48017. // creates a black and white random noise texture, 512x512
  48018. LensRenderingPipeline.prototype._createGrainTexture = function () {
  48019. var size = 512;
  48020. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48021. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48022. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48023. var context = this._grainTexture.getContext();
  48024. var rand = function (min, max) {
  48025. return Math.random() * (max - min) + min;
  48026. };
  48027. var value;
  48028. for (var x = 0; x < size; x++) {
  48029. for (var y = 0; y < size; y++) {
  48030. value = Math.floor(rand(0.42, 0.58) * 255);
  48031. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  48032. context.fillRect(x, y, 1, 1);
  48033. }
  48034. }
  48035. this._grainTexture.update(false);
  48036. };
  48037. return LensRenderingPipeline;
  48038. }(BABYLON.PostProcessRenderPipeline));
  48039. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  48040. })(BABYLON || (BABYLON = {}));
  48041. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  48042. //
  48043. // This post-process allows the modification of rendered colors by using
  48044. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48045. //
  48046. // The object needs to be provided an url to a texture containing the color
  48047. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48048. // Use an image editing software to tweak the LUT to match your needs.
  48049. //
  48050. // For an example of a color LUT, see here:
  48051. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48052. // For explanations on color grading, see here:
  48053. // http://udn.epicgames.com/Three/ColorGrading.html
  48054. //
  48055. var BABYLON;
  48056. (function (BABYLON) {
  48057. var ColorCorrectionPostProcess = (function (_super) {
  48058. __extends(ColorCorrectionPostProcess, _super);
  48059. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48060. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48061. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48062. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48063. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48064. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48065. _this.onApply = function (effect) {
  48066. effect.setTexture("colorTable", _this._colorTableTexture);
  48067. };
  48068. return _this;
  48069. }
  48070. return ColorCorrectionPostProcess;
  48071. }(BABYLON.PostProcess));
  48072. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48073. })(BABYLON || (BABYLON = {}));
  48074. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48075. var BABYLON;
  48076. (function (BABYLON) {
  48077. var AnaglyphFreeCamera = (function (_super) {
  48078. __extends(AnaglyphFreeCamera, _super);
  48079. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  48080. var _this = _super.call(this, name, position, scene) || this;
  48081. _this.interaxialDistance = interaxialDistance;
  48082. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48083. return _this;
  48084. }
  48085. AnaglyphFreeCamera.prototype.getClassName = function () {
  48086. return "AnaglyphFreeCamera";
  48087. };
  48088. return AnaglyphFreeCamera;
  48089. }(BABYLON.FreeCamera));
  48090. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48091. var AnaglyphArcRotateCamera = (function (_super) {
  48092. __extends(AnaglyphArcRotateCamera, _super);
  48093. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48094. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48095. _this.interaxialDistance = interaxialDistance;
  48096. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48097. return _this;
  48098. }
  48099. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  48100. return "AnaglyphArcRotateCamera";
  48101. };
  48102. return AnaglyphArcRotateCamera;
  48103. }(BABYLON.ArcRotateCamera));
  48104. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48105. var AnaglyphGamepadCamera = (function (_super) {
  48106. __extends(AnaglyphGamepadCamera, _super);
  48107. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48108. var _this = _super.call(this, name, position, scene) || this;
  48109. _this.interaxialDistance = interaxialDistance;
  48110. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48111. return _this;
  48112. }
  48113. AnaglyphGamepadCamera.prototype.getClassName = function () {
  48114. return "AnaglyphGamepadCamera";
  48115. };
  48116. return AnaglyphGamepadCamera;
  48117. }(BABYLON.GamepadCamera));
  48118. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48119. var AnaglyphUniversalCamera = (function (_super) {
  48120. __extends(AnaglyphUniversalCamera, _super);
  48121. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48122. var _this = _super.call(this, name, position, scene) || this;
  48123. _this.interaxialDistance = interaxialDistance;
  48124. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48125. return _this;
  48126. }
  48127. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48128. return "AnaglyphUniversalCamera";
  48129. };
  48130. return AnaglyphUniversalCamera;
  48131. }(BABYLON.UniversalCamera));
  48132. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48133. var StereoscopicFreeCamera = (function (_super) {
  48134. __extends(StereoscopicFreeCamera, _super);
  48135. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48136. var _this = _super.call(this, name, position, scene) || this;
  48137. _this.interaxialDistance = interaxialDistance;
  48138. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48139. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48140. return _this;
  48141. }
  48142. StereoscopicFreeCamera.prototype.getClassName = function () {
  48143. return "StereoscopicFreeCamera";
  48144. };
  48145. return StereoscopicFreeCamera;
  48146. }(BABYLON.FreeCamera));
  48147. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48148. var StereoscopicArcRotateCamera = (function (_super) {
  48149. __extends(StereoscopicArcRotateCamera, _super);
  48150. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48151. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48152. _this.interaxialDistance = interaxialDistance;
  48153. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48154. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48155. return _this;
  48156. }
  48157. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48158. return "StereoscopicArcRotateCamera";
  48159. };
  48160. return StereoscopicArcRotateCamera;
  48161. }(BABYLON.ArcRotateCamera));
  48162. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48163. var StereoscopicGamepadCamera = (function (_super) {
  48164. __extends(StereoscopicGamepadCamera, _super);
  48165. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48166. var _this = _super.call(this, name, position, scene) || this;
  48167. _this.interaxialDistance = interaxialDistance;
  48168. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48169. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48170. return _this;
  48171. }
  48172. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48173. return "StereoscopicGamepadCamera";
  48174. };
  48175. return StereoscopicGamepadCamera;
  48176. }(BABYLON.GamepadCamera));
  48177. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48178. var StereoscopicUniversalCamera = (function (_super) {
  48179. __extends(StereoscopicUniversalCamera, _super);
  48180. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48181. var _this = _super.call(this, name, position, scene) || this;
  48182. _this.interaxialDistance = interaxialDistance;
  48183. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48184. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48185. return _this;
  48186. }
  48187. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48188. return "StereoscopicUniversalCamera";
  48189. };
  48190. return StereoscopicUniversalCamera;
  48191. }(BABYLON.UniversalCamera));
  48192. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48193. })(BABYLON || (BABYLON = {}));
  48194. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48195. var BABYLON;
  48196. (function (BABYLON) {
  48197. var HDRRenderingPipeline = (function (_super) {
  48198. __extends(HDRRenderingPipeline, _super);
  48199. /**
  48200. * @constructor
  48201. * @param {string} name - The rendering pipeline name
  48202. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48203. * @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)
  48204. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48205. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48206. */
  48207. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48208. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48209. var _this = _super.call(this, scene.getEngine(), name) || this;
  48210. /**
  48211. * Public members
  48212. */
  48213. // Gaussian Blur
  48214. /**
  48215. * Gaussian blur coefficient
  48216. * @type {number}
  48217. */
  48218. _this.gaussCoeff = 0.3;
  48219. /**
  48220. * Gaussian blur mean
  48221. * @type {number}
  48222. */
  48223. _this.gaussMean = 1.0;
  48224. /**
  48225. * Gaussian blur standard deviation
  48226. * @type {number}
  48227. */
  48228. _this.gaussStandDev = 0.8;
  48229. /**
  48230. * Gaussian blur multiplier. Multiplies the blur effect
  48231. * @type {number}
  48232. */
  48233. _this.gaussMultiplier = 4.0;
  48234. // HDR
  48235. /**
  48236. * Exposure, controls the overall intensity of the pipeline
  48237. * @type {number}
  48238. */
  48239. _this.exposure = 1.0;
  48240. /**
  48241. * Minimum luminance that the post-process can output. Luminance is >= 0
  48242. * @type {number}
  48243. */
  48244. _this.minimumLuminance = 1.0;
  48245. /**
  48246. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48247. * @type {number}
  48248. */
  48249. _this.maximumLuminance = 1e20;
  48250. /**
  48251. * Increase rate for luminance: eye adaptation speed to dark
  48252. * @type {number}
  48253. */
  48254. _this.luminanceIncreaserate = 0.5;
  48255. /**
  48256. * Decrease rate for luminance: eye adaptation speed to bright
  48257. * @type {number}
  48258. */
  48259. _this.luminanceDecreaseRate = 0.5;
  48260. // Bright pass
  48261. /**
  48262. * Minimum luminance needed to compute HDR
  48263. * @type {number}
  48264. */
  48265. _this.brightThreshold = 0.8;
  48266. _this._needUpdate = true;
  48267. _this._scene = scene;
  48268. // Bright pass
  48269. _this._createBrightPassPostProcess(scene, ratio);
  48270. // Down sample X4
  48271. _this._createDownSampleX4PostProcess(scene, ratio);
  48272. // Create gaussian blur post-processes
  48273. _this._createGaussianBlurPostProcess(scene, ratio);
  48274. // Texture adder
  48275. _this._createTextureAdderPostProcess(scene, ratio);
  48276. // Luminance generator
  48277. _this._createLuminanceGeneratorPostProcess(scene);
  48278. // HDR
  48279. _this._createHDRPostProcess(scene, ratio);
  48280. // Pass postprocess
  48281. if (originalPostProcess === null) {
  48282. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48283. }
  48284. else {
  48285. _this._originalPostProcess = originalPostProcess;
  48286. }
  48287. // Configure pipeline
  48288. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48289. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48290. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48291. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48292. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48293. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48294. var addDownSamplerPostProcess = function (id) {
  48295. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48296. };
  48297. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48298. addDownSamplerPostProcess(i);
  48299. }
  48300. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48301. // Finish
  48302. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48303. if (cameras !== null) {
  48304. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48305. }
  48306. _this.update();
  48307. return _this;
  48308. }
  48309. /**
  48310. * Tells the pipeline to update its post-processes
  48311. */
  48312. HDRRenderingPipeline.prototype.update = function () {
  48313. this._needUpdate = true;
  48314. };
  48315. /**
  48316. * Returns the current calculated luminance
  48317. */
  48318. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48319. return this._hdrCurrentLuminance;
  48320. };
  48321. /**
  48322. * Returns the currently drawn luminance
  48323. */
  48324. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48325. return this._hdrOutputLuminance;
  48326. };
  48327. /**
  48328. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48329. */
  48330. HDRRenderingPipeline.prototype.dispose = function () {
  48331. this._originalPostProcess = undefined;
  48332. this._brightPassPostProcess = undefined;
  48333. this._downSampleX4PostProcess = undefined;
  48334. this._guassianBlurHPostProcess = undefined;
  48335. this._guassianBlurVPostProcess = undefined;
  48336. this._textureAdderPostProcess = undefined;
  48337. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48338. this._downSamplePostProcesses[i] = undefined;
  48339. }
  48340. this._hdrPostProcess = undefined;
  48341. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48342. };
  48343. /**
  48344. * Creates the HDR post-process and computes the luminance adaptation
  48345. */
  48346. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  48347. var _this = this;
  48348. var hdrLastLuminance = 0.0;
  48349. this._hdrOutputLuminance = -1.0;
  48350. this._hdrCurrentLuminance = 1.0;
  48351. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  48352. this._hdrPostProcess.onApply = function (effect) {
  48353. if (_this._hdrOutputLuminance < 0.0) {
  48354. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48355. }
  48356. else {
  48357. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  48358. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  48359. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  48360. }
  48361. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  48362. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  48363. }
  48364. else {
  48365. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48366. }
  48367. }
  48368. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  48369. hdrLastLuminance += scene.getEngine().getDeltaTime();
  48370. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48371. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48372. effect.setFloat("exposure", _this.exposure);
  48373. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  48374. _this._needUpdate = false;
  48375. };
  48376. };
  48377. /**
  48378. * Texture Adder post-process
  48379. */
  48380. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48381. var _this = this;
  48382. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  48383. this._textureAdderPostProcess.onApply = function (effect) {
  48384. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48385. };
  48386. };
  48387. /**
  48388. * Down sample X4 post-process
  48389. */
  48390. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48391. var _this = this;
  48392. var downSampleX4Offsets = new Array(32);
  48393. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  48394. this._downSampleX4PostProcess.onApply = function (effect) {
  48395. if (_this._needUpdate) {
  48396. var id = 0;
  48397. for (var i = -2; i < 2; i++) {
  48398. for (var j = -2; j < 2; j++) {
  48399. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  48400. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  48401. id += 2;
  48402. }
  48403. }
  48404. }
  48405. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48406. };
  48407. };
  48408. /**
  48409. * Bright pass post-process
  48410. */
  48411. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48412. var _this = this;
  48413. var brightOffsets = new Array(8);
  48414. var brightPassCallback = function (effect) {
  48415. if (_this._needUpdate) {
  48416. var sU = (1.0 / _this._brightPassPostProcess.width);
  48417. var sV = (1.0 / _this._brightPassPostProcess.height);
  48418. brightOffsets[0] = -0.5 * sU;
  48419. brightOffsets[1] = 0.5 * sV;
  48420. brightOffsets[2] = 0.5 * sU;
  48421. brightOffsets[3] = 0.5 * sV;
  48422. brightOffsets[4] = -0.5 * sU;
  48423. brightOffsets[5] = -0.5 * sV;
  48424. brightOffsets[6] = 0.5 * sU;
  48425. brightOffsets[7] = -0.5 * sV;
  48426. }
  48427. effect.setArray2("dsOffsets", brightOffsets);
  48428. effect.setFloat("brightThreshold", _this.brightThreshold);
  48429. };
  48430. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  48431. this._brightPassPostProcess.onApply = brightPassCallback;
  48432. };
  48433. /**
  48434. * Luminance generator. Creates the luminance post-process and down sample post-processes
  48435. */
  48436. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  48437. var _this = this;
  48438. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  48439. var luminanceOffsets = new Array(8);
  48440. var downSampleOffsets = new Array(18);
  48441. var halfDestPixelSize;
  48442. this._downSamplePostProcesses = new Array(lumSteps);
  48443. // Utils for luminance
  48444. var luminanceUpdateSourceOffsets = function (width, height) {
  48445. var sU = (1.0 / width);
  48446. var sV = (1.0 / height);
  48447. luminanceOffsets[0] = -0.5 * sU;
  48448. luminanceOffsets[1] = 0.5 * sV;
  48449. luminanceOffsets[2] = 0.5 * sU;
  48450. luminanceOffsets[3] = 0.5 * sV;
  48451. luminanceOffsets[4] = -0.5 * sU;
  48452. luminanceOffsets[5] = -0.5 * sV;
  48453. luminanceOffsets[6] = 0.5 * sU;
  48454. luminanceOffsets[7] = -0.5 * sV;
  48455. };
  48456. var luminanceUpdateDestOffsets = function (width, height) {
  48457. var id = 0;
  48458. for (var x = -1; x < 2; x++) {
  48459. for (var y = -1; y < 2; y++) {
  48460. downSampleOffsets[id] = (x) / width;
  48461. downSampleOffsets[id + 1] = (y) / height;
  48462. id += 2;
  48463. }
  48464. }
  48465. };
  48466. // Luminance callback
  48467. var luminanceCallback = function (effect) {
  48468. if (_this._needUpdate) {
  48469. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  48470. }
  48471. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48472. effect.setArray2("lumOffsets", luminanceOffsets);
  48473. };
  48474. // Down sample callbacks
  48475. var downSampleCallback = function (indice) {
  48476. var i = indice;
  48477. return function (effect) {
  48478. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48479. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48480. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  48481. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  48482. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  48483. effect.setArray2("dsOffsets", downSampleOffsets);
  48484. };
  48485. };
  48486. var downSampleAfterRenderCallback = function (effect) {
  48487. // Unpack result
  48488. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48489. 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);
  48490. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48491. };
  48492. // Create luminance post-process
  48493. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  48494. 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);
  48495. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  48496. // Create down sample post-processes
  48497. for (var i = lumSteps - 2; i >= 0; i--) {
  48498. var length = Math.pow(3, i);
  48499. ratio = { width: length, height: length };
  48500. var defines = "#define DOWN_SAMPLE\n";
  48501. if (i === 0) {
  48502. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  48503. }
  48504. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48505. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  48506. if (i === 0) {
  48507. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  48508. }
  48509. }
  48510. };
  48511. /**
  48512. * Gaussian blur post-processes. Horizontal and Vertical
  48513. */
  48514. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  48515. var _this = this;
  48516. var blurOffsetsW = new Array(9);
  48517. var blurOffsetsH = new Array(9);
  48518. var blurWeights = new Array(9);
  48519. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  48520. // Utils for gaussian blur
  48521. var calculateBlurOffsets = function (height) {
  48522. var lastOutputDimensions = {
  48523. width: scene.getEngine().getRenderWidth(),
  48524. height: scene.getEngine().getRenderHeight()
  48525. };
  48526. for (var i = 0; i < 9; i++) {
  48527. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48528. if (height) {
  48529. blurOffsetsH[i] = value;
  48530. }
  48531. else {
  48532. blurOffsetsW[i] = value;
  48533. }
  48534. }
  48535. };
  48536. var calculateWeights = function () {
  48537. var x = 0.0;
  48538. for (var i = 0; i < 9; i++) {
  48539. x = (i - 4.0) / 4.0;
  48540. 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));
  48541. }
  48542. };
  48543. // Callback
  48544. var gaussianBlurCallback = function (height) {
  48545. return function (effect) {
  48546. if (_this._needUpdate) {
  48547. calculateWeights();
  48548. calculateBlurOffsets(height);
  48549. }
  48550. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  48551. effect.setArray("blurWeights", blurWeights);
  48552. effect.setFloat("multiplier", _this.gaussMultiplier);
  48553. };
  48554. };
  48555. // Create horizontal gaussian blur post-processes
  48556. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  48557. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  48558. // Create vertical gaussian blur post-process
  48559. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  48560. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  48561. };
  48562. return HDRRenderingPipeline;
  48563. }(BABYLON.PostProcessRenderPipeline));
  48564. // Luminance generator
  48565. HDRRenderingPipeline.LUM_STEPS = 6;
  48566. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  48567. })(BABYLON || (BABYLON = {}));
  48568. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  48569. var BABYLON;
  48570. (function (BABYLON) {
  48571. var FaceAdjacencies = (function () {
  48572. function FaceAdjacencies() {
  48573. this.edges = new Array();
  48574. this.edgesConnectedCount = 0;
  48575. }
  48576. return FaceAdjacencies;
  48577. }());
  48578. var EdgesRenderer = (function () {
  48579. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  48580. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  48581. if (epsilon === void 0) { epsilon = 0.95; }
  48582. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  48583. this.edgesWidthScalerForOrthographic = 1000.0;
  48584. this.edgesWidthScalerForPerspective = 50.0;
  48585. this._linesPositions = new Array();
  48586. this._linesNormals = new Array();
  48587. this._linesIndices = new Array();
  48588. this._buffers = {};
  48589. this._checkVerticesInsteadOfIndices = false;
  48590. this._source = source;
  48591. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  48592. this._epsilon = epsilon;
  48593. this._prepareRessources();
  48594. this._generateEdgesLines();
  48595. }
  48596. EdgesRenderer.prototype._prepareRessources = function () {
  48597. if (this._lineShader) {
  48598. return;
  48599. }
  48600. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  48601. attributes: ["position", "normal"],
  48602. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  48603. });
  48604. this._lineShader.disableDepthWrite = true;
  48605. this._lineShader.backFaceCulling = false;
  48606. };
  48607. EdgesRenderer.prototype.dispose = function () {
  48608. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  48609. if (buffer) {
  48610. buffer.dispose();
  48611. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  48612. }
  48613. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  48614. if (buffer) {
  48615. buffer.dispose();
  48616. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  48617. }
  48618. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  48619. this._lineShader.dispose();
  48620. };
  48621. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  48622. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  48623. return 0;
  48624. }
  48625. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  48626. return 1;
  48627. }
  48628. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  48629. return 2;
  48630. }
  48631. return -1;
  48632. };
  48633. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  48634. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  48635. return 0;
  48636. }
  48637. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  48638. return 1;
  48639. }
  48640. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  48641. return 2;
  48642. }
  48643. return -1;
  48644. };
  48645. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  48646. var needToCreateLine;
  48647. if (edge === undefined) {
  48648. needToCreateLine = true;
  48649. }
  48650. else {
  48651. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  48652. needToCreateLine = dotProduct < this._epsilon;
  48653. }
  48654. if (needToCreateLine) {
  48655. var offset = this._linesPositions.length / 3;
  48656. var normal = p0.subtract(p1);
  48657. normal.normalize();
  48658. // Positions
  48659. this._linesPositions.push(p0.x);
  48660. this._linesPositions.push(p0.y);
  48661. this._linesPositions.push(p0.z);
  48662. this._linesPositions.push(p0.x);
  48663. this._linesPositions.push(p0.y);
  48664. this._linesPositions.push(p0.z);
  48665. this._linesPositions.push(p1.x);
  48666. this._linesPositions.push(p1.y);
  48667. this._linesPositions.push(p1.z);
  48668. this._linesPositions.push(p1.x);
  48669. this._linesPositions.push(p1.y);
  48670. this._linesPositions.push(p1.z);
  48671. // Normals
  48672. this._linesNormals.push(p1.x);
  48673. this._linesNormals.push(p1.y);
  48674. this._linesNormals.push(p1.z);
  48675. this._linesNormals.push(-1);
  48676. this._linesNormals.push(p1.x);
  48677. this._linesNormals.push(p1.y);
  48678. this._linesNormals.push(p1.z);
  48679. this._linesNormals.push(1);
  48680. this._linesNormals.push(p0.x);
  48681. this._linesNormals.push(p0.y);
  48682. this._linesNormals.push(p0.z);
  48683. this._linesNormals.push(-1);
  48684. this._linesNormals.push(p0.x);
  48685. this._linesNormals.push(p0.y);
  48686. this._linesNormals.push(p0.z);
  48687. this._linesNormals.push(1);
  48688. // Indices
  48689. this._linesIndices.push(offset);
  48690. this._linesIndices.push(offset + 1);
  48691. this._linesIndices.push(offset + 2);
  48692. this._linesIndices.push(offset);
  48693. this._linesIndices.push(offset + 2);
  48694. this._linesIndices.push(offset + 3);
  48695. }
  48696. };
  48697. EdgesRenderer.prototype._generateEdgesLines = function () {
  48698. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48699. var indices = this._source.getIndices();
  48700. // First let's find adjacencies
  48701. var adjacencies = new Array();
  48702. var faceNormals = new Array();
  48703. var index;
  48704. var faceAdjacencies;
  48705. // Prepare faces
  48706. for (index = 0; index < indices.length; index += 3) {
  48707. faceAdjacencies = new FaceAdjacencies();
  48708. var p0Index = indices[index];
  48709. var p1Index = indices[index + 1];
  48710. var p2Index = indices[index + 2];
  48711. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  48712. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  48713. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  48714. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  48715. faceNormal.normalize();
  48716. faceNormals.push(faceNormal);
  48717. adjacencies.push(faceAdjacencies);
  48718. }
  48719. // Scan
  48720. for (index = 0; index < adjacencies.length; index++) {
  48721. faceAdjacencies = adjacencies[index];
  48722. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  48723. var otherFaceAdjacencies = adjacencies[otherIndex];
  48724. if (faceAdjacencies.edgesConnectedCount === 3) {
  48725. break;
  48726. }
  48727. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  48728. continue;
  48729. }
  48730. var otherP0 = indices[otherIndex * 3];
  48731. var otherP1 = indices[otherIndex * 3 + 1];
  48732. var otherP2 = indices[otherIndex * 3 + 2];
  48733. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  48734. var otherEdgeIndex;
  48735. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  48736. continue;
  48737. }
  48738. switch (edgeIndex) {
  48739. case 0:
  48740. if (this._checkVerticesInsteadOfIndices) {
  48741. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48742. }
  48743. else {
  48744. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  48745. }
  48746. break;
  48747. case 1:
  48748. if (this._checkVerticesInsteadOfIndices) {
  48749. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48750. }
  48751. else {
  48752. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  48753. }
  48754. break;
  48755. case 2:
  48756. if (this._checkVerticesInsteadOfIndices) {
  48757. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48758. }
  48759. else {
  48760. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  48761. }
  48762. break;
  48763. }
  48764. if (otherEdgeIndex === -1) {
  48765. continue;
  48766. }
  48767. faceAdjacencies.edges[edgeIndex] = otherIndex;
  48768. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  48769. faceAdjacencies.edgesConnectedCount++;
  48770. otherFaceAdjacencies.edgesConnectedCount++;
  48771. if (faceAdjacencies.edgesConnectedCount === 3) {
  48772. break;
  48773. }
  48774. }
  48775. }
  48776. }
  48777. // Create lines
  48778. for (index = 0; index < adjacencies.length; index++) {
  48779. // 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
  48780. var current = adjacencies[index];
  48781. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  48782. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  48783. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  48784. }
  48785. // Merge into a single mesh
  48786. var engine = this._source.getScene().getEngine();
  48787. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  48788. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  48789. this._ib = engine.createIndexBuffer(this._linesIndices);
  48790. this._indicesCount = this._linesIndices.length;
  48791. };
  48792. EdgesRenderer.prototype.render = function () {
  48793. if (!this._lineShader.isReady()) {
  48794. return;
  48795. }
  48796. var scene = this._source.getScene();
  48797. var engine = scene.getEngine();
  48798. this._lineShader._preBind();
  48799. // VBOs
  48800. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  48801. scene.resetCachedMaterial();
  48802. this._lineShader.setColor4("color", this._source.edgesColor);
  48803. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  48804. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  48805. }
  48806. else {
  48807. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  48808. }
  48809. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  48810. this._lineShader.bind(this._source.getWorldMatrix());
  48811. // Draw order
  48812. engine.draw(true, 0, this._indicesCount);
  48813. this._lineShader.unbind();
  48814. engine.setDepthWrite(true);
  48815. };
  48816. return EdgesRenderer;
  48817. }());
  48818. BABYLON.EdgesRenderer = EdgesRenderer;
  48819. })(BABYLON || (BABYLON = {}));
  48820. //# sourceMappingURL=babylon.edgesRenderer.js.map
  48821. var BABYLON;
  48822. (function (BABYLON) {
  48823. var TonemappingOperator;
  48824. (function (TonemappingOperator) {
  48825. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48826. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48827. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48828. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48829. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48830. ;
  48831. var TonemapPostProcess = (function (_super) {
  48832. __extends(TonemapPostProcess, _super);
  48833. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48834. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48835. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48836. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  48837. _this._operator = _operator;
  48838. _this.exposureAdjustment = exposureAdjustment;
  48839. var defines = "#define ";
  48840. if (_this._operator === TonemappingOperator.Hable)
  48841. defines += "HABLE_TONEMAPPING";
  48842. else if (_this._operator === TonemappingOperator.Reinhard)
  48843. defines += "REINHARD_TONEMAPPING";
  48844. else if (_this._operator === TonemappingOperator.HejiDawson)
  48845. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48846. else if (_this._operator === TonemappingOperator.Photographic)
  48847. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48848. //sadly a second call to create the effect.
  48849. _this.updateEffect(defines);
  48850. _this.onApply = function (effect) {
  48851. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48852. };
  48853. return _this;
  48854. }
  48855. return TonemapPostProcess;
  48856. }(BABYLON.PostProcess));
  48857. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48858. })(BABYLON || (BABYLON = {}));
  48859. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48860. var BABYLON;
  48861. (function (BABYLON) {
  48862. var ReflectionProbe = (function () {
  48863. function ReflectionProbe(name, size, scene, generateMipMaps) {
  48864. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48865. var _this = this;
  48866. this.name = name;
  48867. this._viewMatrix = BABYLON.Matrix.Identity();
  48868. this._target = BABYLON.Vector3.Zero();
  48869. this._add = BABYLON.Vector3.Zero();
  48870. this.invertYAxis = false;
  48871. this.position = BABYLON.Vector3.Zero();
  48872. this._scene = scene;
  48873. this._scene.reflectionProbes.push(this);
  48874. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  48875. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  48876. switch (faceIndex) {
  48877. case 0:
  48878. _this._add.copyFromFloats(1, 0, 0);
  48879. break;
  48880. case 1:
  48881. _this._add.copyFromFloats(-1, 0, 0);
  48882. break;
  48883. case 2:
  48884. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  48885. break;
  48886. case 3:
  48887. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  48888. break;
  48889. case 4:
  48890. _this._add.copyFromFloats(0, 0, 1);
  48891. break;
  48892. case 5:
  48893. _this._add.copyFromFloats(0, 0, -1);
  48894. break;
  48895. }
  48896. if (_this._attachedMesh) {
  48897. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  48898. }
  48899. _this.position.addToRef(_this._add, _this._target);
  48900. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  48901. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  48902. });
  48903. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  48904. scene.updateTransformMatrix(true);
  48905. });
  48906. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  48907. }
  48908. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  48909. get: function () {
  48910. return this._renderTargetTexture.refreshRate;
  48911. },
  48912. set: function (value) {
  48913. this._renderTargetTexture.refreshRate = value;
  48914. },
  48915. enumerable: true,
  48916. configurable: true
  48917. });
  48918. ReflectionProbe.prototype.getScene = function () {
  48919. return this._scene;
  48920. };
  48921. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  48922. get: function () {
  48923. return this._renderTargetTexture;
  48924. },
  48925. enumerable: true,
  48926. configurable: true
  48927. });
  48928. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  48929. get: function () {
  48930. return this._renderTargetTexture.renderList;
  48931. },
  48932. enumerable: true,
  48933. configurable: true
  48934. });
  48935. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  48936. this._attachedMesh = mesh;
  48937. };
  48938. ReflectionProbe.prototype.dispose = function () {
  48939. var index = this._scene.reflectionProbes.indexOf(this);
  48940. if (index !== -1) {
  48941. // Remove from the scene if found
  48942. this._scene.reflectionProbes.splice(index, 1);
  48943. }
  48944. if (this._renderTargetTexture) {
  48945. this._renderTargetTexture.dispose();
  48946. this._renderTargetTexture = null;
  48947. }
  48948. };
  48949. return ReflectionProbe;
  48950. }());
  48951. BABYLON.ReflectionProbe = ReflectionProbe;
  48952. })(BABYLON || (BABYLON = {}));
  48953. //# sourceMappingURL=babylon.reflectionProbe.js.map
  48954. var BABYLON;
  48955. (function (BABYLON) {
  48956. var SolidParticle = (function () {
  48957. /**
  48958. * Creates a Solid Particle object.
  48959. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48960. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48961. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48962. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  48963. * `shapeId` (integer) is the model shape identifier in the SPS.
  48964. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48965. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  48966. */
  48967. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48968. this.idx = 0; // particle global index
  48969. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  48970. this.position = BABYLON.Vector3.Zero(); // position
  48971. this.rotation = BABYLON.Vector3.Zero(); // rotation
  48972. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  48973. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  48974. this.velocity = BABYLON.Vector3.Zero(); // velocity
  48975. this.alive = true; // alive
  48976. this.isVisible = true; // visibility
  48977. this._pos = 0; // index of this particle in the global "positions" array
  48978. this.shapeId = 0; // model shape id
  48979. this.idxInShape = 0; // index of the particle in its shape id
  48980. this.idx = particleIndex;
  48981. this._pos = positionIndex;
  48982. this._model = model;
  48983. this.shapeId = shapeId;
  48984. this.idxInShape = idxInShape;
  48985. this._sps = sps;
  48986. if (modelBoundingInfo) {
  48987. this._modelBoundingInfo = modelBoundingInfo;
  48988. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48989. }
  48990. }
  48991. Object.defineProperty(SolidParticle.prototype, "scale", {
  48992. /**
  48993. * legacy support, changed scale to scaling
  48994. */
  48995. get: function () {
  48996. return this.scaling;
  48997. },
  48998. set: function (scale) {
  48999. this.scaling = scale;
  49000. },
  49001. enumerable: true,
  49002. configurable: true
  49003. });
  49004. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49005. /**
  49006. * legacy support, changed quaternion to rotationQuaternion
  49007. */
  49008. get: function () {
  49009. return this.rotationQuaternion;
  49010. },
  49011. set: function (q) {
  49012. this.rotationQuaternion = q;
  49013. },
  49014. enumerable: true,
  49015. configurable: true
  49016. });
  49017. /**
  49018. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49019. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49020. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  49021. */
  49022. SolidParticle.prototype.intersectsMesh = function (target) {
  49023. if (!this._boundingInfo || !target._boundingInfo) {
  49024. return false;
  49025. }
  49026. if (this._sps._bSphereOnly) {
  49027. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49028. }
  49029. return this._boundingInfo.intersects(target._boundingInfo, false);
  49030. };
  49031. return SolidParticle;
  49032. }());
  49033. BABYLON.SolidParticle = SolidParticle;
  49034. var ModelShape = (function () {
  49035. /**
  49036. * 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.
  49037. * SPS internal tool, don't use it manually.
  49038. */
  49039. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  49040. this.shapeID = id;
  49041. this._shape = shape;
  49042. this._shapeUV = shapeUV;
  49043. this._positionFunction = posFunction;
  49044. this._vertexFunction = vtxFunction;
  49045. }
  49046. return ModelShape;
  49047. }());
  49048. BABYLON.ModelShape = ModelShape;
  49049. })(BABYLON || (BABYLON = {}));
  49050. //# sourceMappingURL=babylon.solidParticle.js.map
  49051. var BABYLON;
  49052. (function (BABYLON) {
  49053. /**
  49054. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49055. */
  49056. var SolidParticleSystem = (function () {
  49057. /**
  49058. * Creates a SPS (Solid Particle System) object.
  49059. * `name` (String) is the SPS name, this will be the underlying mesh name.
  49060. * `scene` (Scene) is the scene in which the SPS is added.
  49061. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  49062. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  49063. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  49064. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49065. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49066. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49067. */
  49068. function SolidParticleSystem(name, scene, options) {
  49069. // public members
  49070. /**
  49071. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49072. * Example : var p = SPS.particles[i];
  49073. */
  49074. this.particles = new Array();
  49075. /**
  49076. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49077. */
  49078. this.nbParticles = 0;
  49079. /**
  49080. * If the particles must ever face the camera (default false). Useful for planar particles.
  49081. */
  49082. this.billboard = false;
  49083. /**
  49084. * Recompute normals when adding a shape
  49085. */
  49086. this.recomputeNormals = true;
  49087. /**
  49088. * This a counter ofr your own usage. It's not set by any SPS functions.
  49089. */
  49090. this.counter = 0;
  49091. /**
  49092. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49093. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49094. */
  49095. this.vars = {};
  49096. this._positions = new Array();
  49097. this._indices = new Array();
  49098. this._normals = new Array();
  49099. this._colors = new Array();
  49100. this._uvs = new Array();
  49101. this._index = 0; // indices index
  49102. this._updatable = true;
  49103. this._pickable = false;
  49104. this._isVisibilityBoxLocked = false;
  49105. this._alwaysVisible = false;
  49106. this._shapeCounter = 0;
  49107. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  49108. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49109. this._computeParticleColor = true;
  49110. this._computeParticleTexture = true;
  49111. this._computeParticleRotation = true;
  49112. this._computeParticleVertex = false;
  49113. this._computeBoundingBox = false;
  49114. this._cam_axisZ = BABYLON.Vector3.Zero();
  49115. this._cam_axisY = BABYLON.Vector3.Zero();
  49116. this._cam_axisX = BABYLON.Vector3.Zero();
  49117. this._axisX = BABYLON.Axis.X;
  49118. this._axisY = BABYLON.Axis.Y;
  49119. this._axisZ = BABYLON.Axis.Z;
  49120. this._camDir = BABYLON.Vector3.Zero();
  49121. this._rotMatrix = new BABYLON.Matrix();
  49122. this._invertMatrix = new BABYLON.Matrix();
  49123. this._rotated = BABYLON.Vector3.Zero();
  49124. this._quaternion = new BABYLON.Quaternion();
  49125. this._vertex = BABYLON.Vector3.Zero();
  49126. this._normal = BABYLON.Vector3.Zero();
  49127. this._yaw = 0.0;
  49128. this._pitch = 0.0;
  49129. this._roll = 0.0;
  49130. this._halfroll = 0.0;
  49131. this._halfpitch = 0.0;
  49132. this._halfyaw = 0.0;
  49133. this._sinRoll = 0.0;
  49134. this._cosRoll = 0.0;
  49135. this._sinPitch = 0.0;
  49136. this._cosPitch = 0.0;
  49137. this._sinYaw = 0.0;
  49138. this._cosYaw = 0.0;
  49139. this._w = 0.0;
  49140. this._minimum = BABYLON.Tmp.Vector3[0];
  49141. this._maximum = BABYLON.Tmp.Vector3[1];
  49142. this._scale = BABYLON.Tmp.Vector3[2];
  49143. this._translation = BABYLON.Tmp.Vector3[3];
  49144. this._minBbox = BABYLON.Tmp.Vector3[4];
  49145. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49146. this._particlesIntersect = false;
  49147. this._bSphereOnly = false;
  49148. this._bSphereRadiusFactor = 1.0;
  49149. this.name = name;
  49150. this._scene = scene;
  49151. this._camera = scene.activeCamera;
  49152. this._pickable = options ? options.isPickable : false;
  49153. this._particlesIntersect = options ? options.particleIntersection : false;
  49154. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49155. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49156. if (options && options.updatable) {
  49157. this._updatable = options.updatable;
  49158. }
  49159. else {
  49160. this._updatable = true;
  49161. }
  49162. if (this._pickable) {
  49163. this.pickedParticles = [];
  49164. }
  49165. }
  49166. /**
  49167. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49168. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49169. */
  49170. SolidParticleSystem.prototype.buildMesh = function () {
  49171. if (this.nbParticles === 0) {
  49172. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49173. this.addShape(triangle, 1);
  49174. triangle.dispose();
  49175. }
  49176. this._positions32 = new Float32Array(this._positions);
  49177. this._uvs32 = new Float32Array(this._uvs);
  49178. this._colors32 = new Float32Array(this._colors);
  49179. if (this.recomputeNormals) {
  49180. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49181. }
  49182. this._normals32 = new Float32Array(this._normals);
  49183. this._fixedNormal32 = new Float32Array(this._normals);
  49184. var vertexData = new BABYLON.VertexData();
  49185. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49186. vertexData.indices = this._indices;
  49187. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49188. if (this._uvs32) {
  49189. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49190. ;
  49191. }
  49192. if (this._colors32) {
  49193. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49194. }
  49195. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49196. vertexData.applyToMesh(mesh, this._updatable);
  49197. this.mesh = mesh;
  49198. this.mesh.isPickable = this._pickable;
  49199. // free memory
  49200. this._positions = null;
  49201. this._normals = null;
  49202. this._uvs = null;
  49203. this._colors = null;
  49204. if (!this._updatable) {
  49205. this.particles.length = 0;
  49206. }
  49207. return mesh;
  49208. };
  49209. /**
  49210. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49211. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49212. * Thus the particles generated from `digest()` have their property `position` set yet.
  49213. * `mesh` ( Mesh ) is the mesh to be digested
  49214. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49215. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49216. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49217. */
  49218. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49219. var size = (options && options.facetNb) || 1;
  49220. var number = (options && options.number);
  49221. var delta = (options && options.delta) || 0;
  49222. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49223. var meshInd = mesh.getIndices();
  49224. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49225. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49226. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49227. var f = 0; // facet counter
  49228. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49229. // compute size from number
  49230. if (number) {
  49231. number = (number > totalFacets) ? totalFacets : number;
  49232. size = Math.round(totalFacets / number);
  49233. delta = 0;
  49234. }
  49235. else {
  49236. size = (size > totalFacets) ? totalFacets : size;
  49237. }
  49238. var facetPos = []; // submesh positions
  49239. var facetInd = []; // submesh indices
  49240. var facetUV = []; // submesh UV
  49241. var facetCol = []; // submesh colors
  49242. var barycenter = BABYLON.Tmp.Vector3[0];
  49243. var rand;
  49244. var sizeO = size;
  49245. while (f < totalFacets) {
  49246. size = sizeO + Math.floor((1 + delta) * Math.random());
  49247. if (f > totalFacets - size) {
  49248. size = totalFacets - f;
  49249. }
  49250. // reset temp arrays
  49251. facetPos.length = 0;
  49252. facetInd.length = 0;
  49253. facetUV.length = 0;
  49254. facetCol.length = 0;
  49255. // iterate over "size" facets
  49256. var fi = 0;
  49257. for (var j = f * 3; j < (f + size) * 3; j++) {
  49258. facetInd.push(fi);
  49259. var i = meshInd[j];
  49260. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49261. if (meshUV) {
  49262. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49263. }
  49264. if (meshCol) {
  49265. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49266. }
  49267. fi++;
  49268. }
  49269. // create a model shape for each single particle
  49270. var idx = this.nbParticles;
  49271. var shape = this._posToShape(facetPos);
  49272. var shapeUV = this._uvsToShapeUV(facetUV);
  49273. // compute the barycenter of the shape
  49274. var v;
  49275. for (v = 0; v < shape.length; v++) {
  49276. barycenter.addInPlace(shape[v]);
  49277. }
  49278. barycenter.scaleInPlace(1 / shape.length);
  49279. // shift the shape from its barycenter to the origin
  49280. for (v = 0; v < shape.length; v++) {
  49281. shape[v].subtractInPlace(barycenter);
  49282. }
  49283. var bInfo;
  49284. if (this._particlesIntersect) {
  49285. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49286. }
  49287. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49288. // add the particle in the SPS
  49289. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49290. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49291. // initialize the particle position
  49292. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49293. this._index += shape.length;
  49294. idx++;
  49295. this.nbParticles++;
  49296. this._shapeCounter++;
  49297. f += size;
  49298. }
  49299. return this;
  49300. };
  49301. //reset copy
  49302. SolidParticleSystem.prototype._resetCopy = function () {
  49303. this._copy.position.x = 0;
  49304. this._copy.position.y = 0;
  49305. this._copy.position.z = 0;
  49306. this._copy.rotation.x = 0;
  49307. this._copy.rotation.y = 0;
  49308. this._copy.rotation.z = 0;
  49309. this._copy.rotationQuaternion = null;
  49310. this._copy.scaling.x = 1;
  49311. this._copy.scaling.y = 1;
  49312. this._copy.scaling.z = 1;
  49313. this._copy.uvs.x = 0;
  49314. this._copy.uvs.y = 0;
  49315. this._copy.uvs.z = 1;
  49316. this._copy.uvs.w = 1;
  49317. this._copy.color = null;
  49318. };
  49319. // _meshBuilder : inserts the shape model in the global SPS mesh
  49320. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49321. var i;
  49322. var u = 0;
  49323. var c = 0;
  49324. var n = 0;
  49325. this._resetCopy();
  49326. if (options && options.positionFunction) {
  49327. options.positionFunction(this._copy, idx, idxInShape);
  49328. }
  49329. if (this._copy.rotationQuaternion) {
  49330. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49331. }
  49332. else {
  49333. this._yaw = this._copy.rotation.y;
  49334. this._pitch = this._copy.rotation.x;
  49335. this._roll = this._copy.rotation.z;
  49336. this._quaternionRotationYPR();
  49337. }
  49338. this._quaternionToRotationMatrix();
  49339. for (i = 0; i < shape.length; i++) {
  49340. this._vertex.x = shape[i].x;
  49341. this._vertex.y = shape[i].y;
  49342. this._vertex.z = shape[i].z;
  49343. if (options && options.vertexFunction) {
  49344. options.vertexFunction(this._copy, this._vertex, i);
  49345. }
  49346. this._vertex.x *= this._copy.scaling.x;
  49347. this._vertex.y *= this._copy.scaling.y;
  49348. this._vertex.z *= this._copy.scaling.z;
  49349. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49350. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49351. if (meshUV) {
  49352. 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);
  49353. u += 2;
  49354. }
  49355. if (this._copy.color) {
  49356. this._color = this._copy.color;
  49357. }
  49358. else if (meshCol && meshCol[c] !== undefined) {
  49359. this._color.r = meshCol[c];
  49360. this._color.g = meshCol[c + 1];
  49361. this._color.b = meshCol[c + 2];
  49362. this._color.a = meshCol[c + 3];
  49363. }
  49364. else {
  49365. this._color.r = 1;
  49366. this._color.g = 1;
  49367. this._color.b = 1;
  49368. this._color.a = 1;
  49369. }
  49370. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49371. c += 4;
  49372. if (!this.recomputeNormals && meshNor) {
  49373. this._normal.x = meshNor[n];
  49374. this._normal.y = meshNor[n + 1];
  49375. this._normal.z = meshNor[n + 2];
  49376. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  49377. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49378. n += 3;
  49379. }
  49380. }
  49381. for (i = 0; i < meshInd.length; i++) {
  49382. indices.push(p + meshInd[i]);
  49383. }
  49384. if (this._pickable) {
  49385. var nbfaces = meshInd.length / 3;
  49386. for (i = 0; i < nbfaces; i++) {
  49387. this.pickedParticles.push({ idx: idx, faceId: i });
  49388. }
  49389. }
  49390. };
  49391. // returns a shape array from positions array
  49392. SolidParticleSystem.prototype._posToShape = function (positions) {
  49393. var shape = [];
  49394. for (var i = 0; i < positions.length; i += 3) {
  49395. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49396. }
  49397. return shape;
  49398. };
  49399. // returns a shapeUV array from a Vector4 uvs
  49400. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49401. var shapeUV = [];
  49402. if (uvs) {
  49403. for (var i = 0; i < uvs.length; i++)
  49404. shapeUV.push(uvs[i]);
  49405. }
  49406. return shapeUV;
  49407. };
  49408. // adds a new particle object in the particles array
  49409. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  49410. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  49411. };
  49412. /**
  49413. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49414. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49415. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  49416. * `nb` (positive integer) the number of particles to be created from this model
  49417. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  49418. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  49419. */
  49420. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49421. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49422. var meshInd = mesh.getIndices();
  49423. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49424. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49425. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49426. var bbInfo;
  49427. if (this._particlesIntersect) {
  49428. bbInfo = mesh.getBoundingInfo();
  49429. }
  49430. var shape = this._posToShape(meshPos);
  49431. var shapeUV = this._uvsToShapeUV(meshUV);
  49432. var posfunc = options ? options.positionFunction : null;
  49433. var vtxfunc = options ? options.vertexFunction : null;
  49434. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  49435. // particles
  49436. var idx = this.nbParticles;
  49437. for (var i = 0; i < nb; i++) {
  49438. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49439. if (this._updatable) {
  49440. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  49441. }
  49442. this._index += shape.length;
  49443. idx++;
  49444. }
  49445. this.nbParticles += nb;
  49446. this._shapeCounter++;
  49447. return this._shapeCounter - 1;
  49448. };
  49449. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49450. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49451. this._resetCopy();
  49452. if (particle._model._positionFunction) {
  49453. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49454. }
  49455. if (this._copy.rotationQuaternion) {
  49456. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49457. }
  49458. else {
  49459. this._yaw = this._copy.rotation.y;
  49460. this._pitch = this._copy.rotation.x;
  49461. this._roll = this._copy.rotation.z;
  49462. this._quaternionRotationYPR();
  49463. }
  49464. this._quaternionToRotationMatrix();
  49465. this._shape = particle._model._shape;
  49466. for (var pt = 0; pt < this._shape.length; pt++) {
  49467. this._vertex.x = this._shape[pt].x;
  49468. this._vertex.y = this._shape[pt].y;
  49469. this._vertex.z = this._shape[pt].z;
  49470. if (particle._model._vertexFunction) {
  49471. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49472. }
  49473. this._vertex.x *= this._copy.scaling.x;
  49474. this._vertex.y *= this._copy.scaling.y;
  49475. this._vertex.z *= this._copy.scaling.z;
  49476. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49477. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49478. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49479. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49480. }
  49481. particle.position.x = 0.0;
  49482. particle.position.y = 0.0;
  49483. particle.position.z = 0.0;
  49484. particle.rotation.x = 0.0;
  49485. particle.rotation.y = 0.0;
  49486. particle.rotation.z = 0.0;
  49487. particle.rotationQuaternion = null;
  49488. particle.scaling.x = 1.0;
  49489. particle.scaling.y = 1.0;
  49490. particle.scaling.z = 1.0;
  49491. };
  49492. /**
  49493. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49494. */
  49495. SolidParticleSystem.prototype.rebuildMesh = function () {
  49496. for (var p = 0; p < this.particles.length; p++) {
  49497. this._rebuildParticle(this.particles[p]);
  49498. }
  49499. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49500. };
  49501. /**
  49502. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49503. * This method calls `updateParticle()` for each particle of the SPS.
  49504. * For an animated SPS, it is usually called within the render loop.
  49505. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49506. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49507. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49508. */
  49509. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49510. if (start === void 0) { start = 0; }
  49511. if (end === void 0) { end = this.nbParticles - 1; }
  49512. if (update === void 0) { update = true; }
  49513. if (!this._updatable) {
  49514. return;
  49515. }
  49516. // custom beforeUpdate
  49517. this.beforeUpdateParticles(start, end, update);
  49518. this._cam_axisX.x = 1.0;
  49519. this._cam_axisX.y = 0.0;
  49520. this._cam_axisX.z = 0.0;
  49521. this._cam_axisY.x = 0.0;
  49522. this._cam_axisY.y = 1.0;
  49523. this._cam_axisY.z = 0.0;
  49524. this._cam_axisZ.x = 0.0;
  49525. this._cam_axisZ.y = 0.0;
  49526. this._cam_axisZ.z = 1.0;
  49527. // if the particles will always face the camera
  49528. if (this.billboard) {
  49529. // compute the camera position and un-rotate it by the current mesh rotation
  49530. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  49531. this._quaternionToRotationMatrix();
  49532. this._rotMatrix.invertToRef(this._invertMatrix);
  49533. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  49534. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49535. this._cam_axisZ.normalize();
  49536. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  49537. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  49538. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49539. this._cam_axisY.normalize();
  49540. this._cam_axisX.normalize();
  49541. }
  49542. }
  49543. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49544. var idx = 0;
  49545. var index = 0;
  49546. var colidx = 0;
  49547. var colorIndex = 0;
  49548. var uvidx = 0;
  49549. var uvIndex = 0;
  49550. var pt = 0;
  49551. if (this._computeBoundingBox) {
  49552. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49553. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49554. }
  49555. // particle loop
  49556. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  49557. for (var p = start; p <= end; p++) {
  49558. this._particle = this.particles[p];
  49559. this._shape = this._particle._model._shape;
  49560. this._shapeUV = this._particle._model._shapeUV;
  49561. // call to custom user function to update the particle properties
  49562. this.updateParticle(this._particle);
  49563. if (this._particle.isVisible) {
  49564. // particle rotation matrix
  49565. if (this.billboard) {
  49566. this._particle.rotation.x = 0.0;
  49567. this._particle.rotation.y = 0.0;
  49568. }
  49569. if (this._computeParticleRotation || this.billboard) {
  49570. if (this._particle.rotationQuaternion) {
  49571. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49572. }
  49573. else {
  49574. this._yaw = this._particle.rotation.y;
  49575. this._pitch = this._particle.rotation.x;
  49576. this._roll = this._particle.rotation.z;
  49577. this._quaternionRotationYPR();
  49578. }
  49579. this._quaternionToRotationMatrix();
  49580. }
  49581. // particle vertex loop
  49582. for (pt = 0; pt < this._shape.length; pt++) {
  49583. idx = index + pt * 3;
  49584. colidx = colorIndex + pt * 4;
  49585. uvidx = uvIndex + pt * 2;
  49586. this._vertex.x = this._shape[pt].x;
  49587. this._vertex.y = this._shape[pt].y;
  49588. this._vertex.z = this._shape[pt].z;
  49589. if (this._computeParticleVertex) {
  49590. this.updateParticleVertex(this._particle, this._vertex, pt);
  49591. }
  49592. // positions
  49593. this._vertex.x *= this._particle.scaling.x;
  49594. this._vertex.y *= this._particle.scaling.y;
  49595. this._vertex.z *= this._particle.scaling.z;
  49596. 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];
  49597. 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;
  49598. 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;
  49599. 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;
  49600. 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;
  49601. 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;
  49602. 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;
  49603. if (this._computeBoundingBox) {
  49604. if (this._positions32[idx] < this._minimum.x) {
  49605. this._minimum.x = this._positions32[idx];
  49606. }
  49607. if (this._positions32[idx] > this._maximum.x) {
  49608. this._maximum.x = this._positions32[idx];
  49609. }
  49610. if (this._positions32[idx + 1] < this._minimum.y) {
  49611. this._minimum.y = this._positions32[idx + 1];
  49612. }
  49613. if (this._positions32[idx + 1] > this._maximum.y) {
  49614. this._maximum.y = this._positions32[idx + 1];
  49615. }
  49616. if (this._positions32[idx + 2] < this._minimum.z) {
  49617. this._minimum.z = this._positions32[idx + 2];
  49618. }
  49619. if (this._positions32[idx + 2] > this._maximum.z) {
  49620. this._maximum.z = this._positions32[idx + 2];
  49621. }
  49622. }
  49623. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  49624. if (!this._computeParticleVertex) {
  49625. this._normal.x = this._fixedNormal32[idx];
  49626. this._normal.y = this._fixedNormal32[idx + 1];
  49627. this._normal.z = this._fixedNormal32[idx + 2];
  49628. 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];
  49629. 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;
  49630. 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;
  49631. 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;
  49632. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49633. 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;
  49634. 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;
  49635. }
  49636. if (this._computeParticleColor) {
  49637. this._colors32[colidx] = this._particle.color.r;
  49638. this._colors32[colidx + 1] = this._particle.color.g;
  49639. this._colors32[colidx + 2] = this._particle.color.b;
  49640. this._colors32[colidx + 3] = this._particle.color.a;
  49641. }
  49642. if (this._computeParticleTexture) {
  49643. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49644. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49645. }
  49646. }
  49647. }
  49648. else {
  49649. for (pt = 0; pt < this._shape.length; pt++) {
  49650. idx = index + pt * 3;
  49651. colidx = colorIndex + pt * 4;
  49652. uvidx = uvIndex + pt * 2;
  49653. this._positions32[idx] = this._camera.position.x;
  49654. this._positions32[idx + 1] = this._camera.position.y;
  49655. this._positions32[idx + 2] = this._camera.position.z;
  49656. this._normals32[idx] = 0.0;
  49657. this._normals32[idx + 1] = 0.0;
  49658. this._normals32[idx + 2] = 0.0;
  49659. if (this._computeParticleColor) {
  49660. this._colors32[colidx] = this._particle.color.r;
  49661. this._colors32[colidx + 1] = this._particle.color.g;
  49662. this._colors32[colidx + 2] = this._particle.color.b;
  49663. this._colors32[colidx + 3] = this._particle.color.a;
  49664. }
  49665. if (this._computeParticleTexture) {
  49666. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49667. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49668. }
  49669. }
  49670. }
  49671. // if the particle intersections must be computed : update the bbInfo
  49672. if (this._particlesIntersect) {
  49673. var bInfo = this._particle._boundingInfo;
  49674. var bBox = bInfo.boundingBox;
  49675. var bSphere = bInfo.boundingSphere;
  49676. if (!this._bSphereOnly) {
  49677. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49678. for (var b = 0; b < bBox.vectors.length; b++) {
  49679. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49680. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49681. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49682. 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];
  49683. 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;
  49684. 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;
  49685. 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;
  49686. 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;
  49687. 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;
  49688. 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;
  49689. }
  49690. bBox._update(this.mesh._worldMatrix);
  49691. }
  49692. // place and scale the particle bouding sphere in the SPS local system, then update it
  49693. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49694. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49695. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49696. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49697. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49698. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49699. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49700. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49701. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49702. 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));
  49703. bSphere._update(this.mesh._worldMatrix);
  49704. }
  49705. // increment indexes for the next particle
  49706. index = idx + 3;
  49707. colorIndex = colidx + 4;
  49708. uvIndex = uvidx + 2;
  49709. }
  49710. // if the VBO must be updated
  49711. if (update) {
  49712. if (this._computeParticleColor) {
  49713. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49714. }
  49715. if (this._computeParticleTexture) {
  49716. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49717. }
  49718. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49719. if (!this.mesh.areNormalsFrozen) {
  49720. if (this._computeParticleVertex) {
  49721. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49722. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  49723. for (var i = 0; i < this._normals32.length; i++) {
  49724. this._fixedNormal32[i] = this._normals32[i];
  49725. }
  49726. }
  49727. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49728. }
  49729. }
  49730. if (this._computeBoundingBox) {
  49731. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49732. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49733. }
  49734. this.afterUpdateParticles(start, end, update);
  49735. };
  49736. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49737. this._halfroll = this._roll * 0.5;
  49738. this._halfpitch = this._pitch * 0.5;
  49739. this._halfyaw = this._yaw * 0.5;
  49740. this._sinRoll = Math.sin(this._halfroll);
  49741. this._cosRoll = Math.cos(this._halfroll);
  49742. this._sinPitch = Math.sin(this._halfpitch);
  49743. this._cosPitch = Math.cos(this._halfpitch);
  49744. this._sinYaw = Math.sin(this._halfyaw);
  49745. this._cosYaw = Math.cos(this._halfyaw);
  49746. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  49747. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  49748. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  49749. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  49750. };
  49751. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49752. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49753. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49754. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49755. this._rotMatrix.m[3] = 0;
  49756. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49757. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49758. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49759. this._rotMatrix.m[7] = 0;
  49760. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49761. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49762. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49763. this._rotMatrix.m[11] = 0;
  49764. this._rotMatrix.m[12] = 0;
  49765. this._rotMatrix.m[13] = 0;
  49766. this._rotMatrix.m[14] = 0;
  49767. this._rotMatrix.m[15] = 1.0;
  49768. };
  49769. /**
  49770. * Disposes the SPS
  49771. */
  49772. SolidParticleSystem.prototype.dispose = function () {
  49773. this.mesh.dispose();
  49774. this.vars = null;
  49775. // drop references to internal big arrays for the GC
  49776. this._positions = null;
  49777. this._indices = null;
  49778. this._normals = null;
  49779. this._uvs = null;
  49780. this._colors = null;
  49781. this._positions32 = null;
  49782. this._normals32 = null;
  49783. this._fixedNormal32 = null;
  49784. this._uvs32 = null;
  49785. this._colors32 = null;
  49786. this.pickedParticles = null;
  49787. };
  49788. /**
  49789. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49790. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49791. */
  49792. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49793. if (!this._isVisibilityBoxLocked) {
  49794. this.mesh.refreshBoundingInfo();
  49795. }
  49796. };
  49797. /**
  49798. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49799. * @param size the size (float) of the visibility box
  49800. * note : this doesn't lock the SPS mesh bounding box.
  49801. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49802. */
  49803. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49804. var vis = size / 2;
  49805. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49806. };
  49807. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49808. // getter and setter
  49809. get: function () {
  49810. return this._alwaysVisible;
  49811. },
  49812. /**
  49813. * Sets the SPS as always visible or not
  49814. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49815. */
  49816. set: function (val) {
  49817. this._alwaysVisible = val;
  49818. this.mesh.alwaysSelectAsActiveMesh = val;
  49819. },
  49820. enumerable: true,
  49821. configurable: true
  49822. });
  49823. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49824. get: function () {
  49825. return this._isVisibilityBoxLocked;
  49826. },
  49827. /**
  49828. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49829. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49830. */
  49831. set: function (val) {
  49832. this._isVisibilityBoxLocked = val;
  49833. this.mesh.getBoundingInfo().isLocked = val;
  49834. },
  49835. enumerable: true,
  49836. configurable: true
  49837. });
  49838. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49839. // getters
  49840. get: function () {
  49841. return this._computeParticleRotation;
  49842. },
  49843. // Optimizer setters
  49844. /**
  49845. * Tells to `setParticles()` to compute the particle rotations or not.
  49846. * Default value : true. The SPS is faster when it's set to false.
  49847. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49848. */
  49849. set: function (val) {
  49850. this._computeParticleRotation = val;
  49851. },
  49852. enumerable: true,
  49853. configurable: true
  49854. });
  49855. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49856. get: function () {
  49857. return this._computeParticleColor;
  49858. },
  49859. /**
  49860. * Tells to `setParticles()` to compute the particle colors or not.
  49861. * Default value : true. The SPS is faster when it's set to false.
  49862. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49863. */
  49864. set: function (val) {
  49865. this._computeParticleColor = val;
  49866. },
  49867. enumerable: true,
  49868. configurable: true
  49869. });
  49870. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49871. get: function () {
  49872. return this._computeParticleTexture;
  49873. },
  49874. /**
  49875. * Tells to `setParticles()` to compute the particle textures or not.
  49876. * Default value : true. The SPS is faster when it's set to false.
  49877. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49878. */
  49879. set: function (val) {
  49880. this._computeParticleTexture = val;
  49881. },
  49882. enumerable: true,
  49883. configurable: true
  49884. });
  49885. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49886. get: function () {
  49887. return this._computeParticleVertex;
  49888. },
  49889. /**
  49890. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49891. * Default value : false. The SPS is faster when it's set to false.
  49892. * Note : the particle custom vertex positions aren't stored values.
  49893. */
  49894. set: function (val) {
  49895. this._computeParticleVertex = val;
  49896. },
  49897. enumerable: true,
  49898. configurable: true
  49899. });
  49900. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49901. get: function () {
  49902. return this._computeBoundingBox;
  49903. },
  49904. /**
  49905. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49906. */
  49907. set: function (val) {
  49908. this._computeBoundingBox = val;
  49909. },
  49910. enumerable: true,
  49911. configurable: true
  49912. });
  49913. // =======================================================================
  49914. // Particle behavior logic
  49915. // these following methods may be overwritten by the user to fit his needs
  49916. /**
  49917. * This function does nothing. It may be overwritten to set all the particle first values.
  49918. * The SPS doesn't call this function, you may have to call it by your own.
  49919. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49920. */
  49921. SolidParticleSystem.prototype.initParticles = function () {
  49922. };
  49923. /**
  49924. * This function does nothing. It may be overwritten to recycle a particle.
  49925. * The SPS doesn't call this function, you may have to call it by your own.
  49926. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49927. */
  49928. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49929. return particle;
  49930. };
  49931. /**
  49932. * Updates a particle : this function should be overwritten by the user.
  49933. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49934. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49935. * ex : just set a particle position or velocity and recycle conditions
  49936. */
  49937. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49938. return particle;
  49939. };
  49940. /**
  49941. * Updates a vertex of a particle : it can be overwritten by the user.
  49942. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49943. * @param particle the current particle
  49944. * @param vertex the current index of the current particle
  49945. * @param pt the index of the current vertex in the particle shape
  49946. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49947. * ex : just set a vertex particle position
  49948. */
  49949. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49950. return vertex;
  49951. };
  49952. /**
  49953. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49954. * This does nothing and may be overwritten by the user.
  49955. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49956. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49957. * @param update the boolean update value actually passed to setParticles()
  49958. */
  49959. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49960. };
  49961. /**
  49962. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49963. * This will be passed three parameters.
  49964. * This does nothing and may be overwritten by the user.
  49965. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49966. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49967. * @param update the boolean update value actually passed to setParticles()
  49968. */
  49969. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49970. };
  49971. return SolidParticleSystem;
  49972. }());
  49973. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49974. })(BABYLON || (BABYLON = {}));
  49975. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  49976. var BABYLON;
  49977. (function (BABYLON) {
  49978. var Internals;
  49979. (function (Internals) {
  49980. var FileFaceOrientation = (function () {
  49981. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  49982. this.name = name;
  49983. this.worldAxisForNormal = worldAxisForNormal;
  49984. this.worldAxisForFileX = worldAxisForFileX;
  49985. this.worldAxisForFileY = worldAxisForFileY;
  49986. }
  49987. return FileFaceOrientation;
  49988. }());
  49989. ;
  49990. /**
  49991. * Helper class dealing with the extraction of spherical polynomial dataArray
  49992. * from a cube map.
  49993. */
  49994. var CubeMapToSphericalPolynomialTools = (function () {
  49995. function CubeMapToSphericalPolynomialTools() {
  49996. }
  49997. /**
  49998. * Converts a cubemap to the according Spherical Polynomial data.
  49999. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50000. *
  50001. * @param cubeInfo The Cube map to extract the information from.
  50002. * @return The Spherical Polynomial data.
  50003. */
  50004. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50005. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50006. var totalSolidAngle = 0.0;
  50007. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50008. var du = 2.0 / cubeInfo.size;
  50009. var dv = du;
  50010. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50011. var minUV = du * 0.5 - 1.0;
  50012. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50013. var fileFace = this.FileFaces[faceIndex];
  50014. var dataArray = cubeInfo[fileFace.name];
  50015. var v = minUV;
  50016. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50017. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50018. // Because SP is still linear, so summation is fine in that basis.
  50019. for (var y = 0; y < cubeInfo.size; y++) {
  50020. var u = minUV;
  50021. for (var x = 0; x < cubeInfo.size; x++) {
  50022. // World direction (not normalised)
  50023. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50024. worldDirection.normalize();
  50025. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50026. if (1) {
  50027. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50028. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50029. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50030. var color = new BABYLON.Color3(r, g, b);
  50031. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50032. }
  50033. else {
  50034. if (faceIndex == 0) {
  50035. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50036. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50037. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50038. }
  50039. else if (faceIndex == 1) {
  50040. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50041. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50042. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50043. }
  50044. else if (faceIndex == 2) {
  50045. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50046. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50047. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50048. }
  50049. else if (faceIndex == 3) {
  50050. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50051. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50052. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50053. }
  50054. else if (faceIndex == 4) {
  50055. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50056. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50057. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50058. }
  50059. else if (faceIndex == 5) {
  50060. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50061. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50062. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50063. }
  50064. 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]);
  50065. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50066. }
  50067. totalSolidAngle += deltaSolidAngle;
  50068. u += du;
  50069. }
  50070. v += dv;
  50071. }
  50072. }
  50073. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50074. var correction = correctSolidAngle / totalSolidAngle;
  50075. sphericalHarmonics.scale(correction);
  50076. // Additionally scale by pi -- audit needed
  50077. sphericalHarmonics.scale(1.0 / Math.PI);
  50078. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50079. };
  50080. return CubeMapToSphericalPolynomialTools;
  50081. }());
  50082. CubeMapToSphericalPolynomialTools.FileFaces = [
  50083. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50084. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50085. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50086. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50087. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50088. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50089. ];
  50090. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50091. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50092. })(BABYLON || (BABYLON = {}));
  50093. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  50094. var BABYLON;
  50095. (function (BABYLON) {
  50096. var Internals;
  50097. (function (Internals) {
  50098. /**
  50099. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50100. */
  50101. var PanoramaToCubeMapTools = (function () {
  50102. function PanoramaToCubeMapTools() {
  50103. }
  50104. /**
  50105. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50106. *
  50107. * @param float32Array The source data.
  50108. * @param inputWidth The width of the input panorama.
  50109. * @param inputhHeight The height of the input panorama.
  50110. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50111. * @return The cubemap data
  50112. */
  50113. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50114. if (!float32Array) {
  50115. throw "ConvertPanoramaToCubemap: input cannot be null";
  50116. }
  50117. if (float32Array.length != inputWidth * inputHeight * 3) {
  50118. throw "ConvertPanoramaToCubemap: input size is wrong";
  50119. }
  50120. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50121. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50122. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50123. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50124. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50125. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50126. return {
  50127. front: textureFront,
  50128. back: textureBack,
  50129. left: textureLeft,
  50130. right: textureRight,
  50131. up: textureUp,
  50132. down: textureDown,
  50133. size: size
  50134. };
  50135. };
  50136. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50137. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50138. var textureArray = new Float32Array(buffer);
  50139. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50140. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50141. var dy = 1 / texSize;
  50142. var fy = 0;
  50143. for (var y = 0; y < texSize; y++) {
  50144. var xv1 = faceData[0];
  50145. var xv2 = faceData[2];
  50146. for (var x = 0; x < texSize; x++) {
  50147. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50148. v.normalize();
  50149. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50150. // 3 channels per pixels
  50151. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50152. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50153. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50154. xv1 = xv1.add(rotDX1);
  50155. xv2 = xv2.add(rotDX2);
  50156. }
  50157. fy += dy;
  50158. }
  50159. return textureArray;
  50160. };
  50161. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50162. var theta = Math.atan2(vDir.z, vDir.x);
  50163. var phi = Math.acos(vDir.y);
  50164. while (theta < -Math.PI)
  50165. theta += 2 * Math.PI;
  50166. while (theta > Math.PI)
  50167. theta -= 2 * Math.PI;
  50168. var dx = theta / Math.PI;
  50169. var dy = phi / Math.PI;
  50170. // recenter.
  50171. dx = dx * 0.5 + 0.5;
  50172. var px = Math.round(dx * inputWidth);
  50173. if (px < 0)
  50174. px = 0;
  50175. else if (px >= inputWidth)
  50176. px = inputWidth - 1;
  50177. var py = Math.round(dy * inputHeight);
  50178. if (py < 0)
  50179. py = 0;
  50180. else if (py >= inputHeight)
  50181. py = inputHeight - 1;
  50182. var inputY = (inputHeight - py - 1);
  50183. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50184. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50185. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50186. return {
  50187. r: r,
  50188. g: g,
  50189. b: b
  50190. };
  50191. };
  50192. return PanoramaToCubeMapTools;
  50193. }());
  50194. PanoramaToCubeMapTools.FACE_FRONT = [
  50195. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50196. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50197. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50198. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50199. ];
  50200. PanoramaToCubeMapTools.FACE_BACK = [
  50201. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50202. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50203. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50204. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50205. ];
  50206. PanoramaToCubeMapTools.FACE_RIGHT = [
  50207. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50208. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50209. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50210. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50211. ];
  50212. PanoramaToCubeMapTools.FACE_LEFT = [
  50213. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50214. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50215. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50216. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50217. ];
  50218. PanoramaToCubeMapTools.FACE_DOWN = [
  50219. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50220. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50221. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50222. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50223. ];
  50224. PanoramaToCubeMapTools.FACE_UP = [
  50225. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50226. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50227. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50228. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50229. ];
  50230. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50231. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50232. })(BABYLON || (BABYLON = {}));
  50233. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50234. var BABYLON;
  50235. (function (BABYLON) {
  50236. var Internals;
  50237. (function (Internals) {
  50238. ;
  50239. /**
  50240. * This groups tools to convert HDR texture to native colors array.
  50241. */
  50242. var HDRTools = (function () {
  50243. function HDRTools() {
  50244. }
  50245. HDRTools.Ldexp = function (mantissa, exponent) {
  50246. if (exponent > 1023) {
  50247. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50248. }
  50249. if (exponent < -1074) {
  50250. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50251. }
  50252. return mantissa * Math.pow(2, exponent);
  50253. };
  50254. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50255. if (exponent > 0) {
  50256. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50257. float32array[index + 0] = red * exponent;
  50258. float32array[index + 1] = green * exponent;
  50259. float32array[index + 2] = blue * exponent;
  50260. }
  50261. else {
  50262. float32array[index + 0] = 0;
  50263. float32array[index + 1] = 0;
  50264. float32array[index + 2] = 0;
  50265. }
  50266. };
  50267. HDRTools.readStringLine = function (uint8array, startIndex) {
  50268. var line = "";
  50269. var character = "";
  50270. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50271. character = String.fromCharCode(uint8array[i]);
  50272. if (character == "\n") {
  50273. break;
  50274. }
  50275. line += character;
  50276. }
  50277. return line;
  50278. };
  50279. /**
  50280. * Reads header information from an RGBE texture stored in a native array.
  50281. * More information on this format are available here:
  50282. * https://en.wikipedia.org/wiki/RGBE_image_format
  50283. *
  50284. * @param uint8array The binary file stored in native array.
  50285. * @return The header information.
  50286. */
  50287. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50288. var height = 0;
  50289. var width = 0;
  50290. var line = this.readStringLine(uint8array, 0);
  50291. if (line[0] != '#' || line[1] != '?') {
  50292. throw "Bad HDR Format.";
  50293. }
  50294. var endOfHeader = false;
  50295. var findFormat = false;
  50296. var lineIndex = 0;
  50297. do {
  50298. lineIndex += (line.length + 1);
  50299. line = this.readStringLine(uint8array, lineIndex);
  50300. if (line == "FORMAT=32-bit_rle_rgbe") {
  50301. findFormat = true;
  50302. }
  50303. else if (line.length == 0) {
  50304. endOfHeader = true;
  50305. }
  50306. } while (!endOfHeader);
  50307. if (!findFormat) {
  50308. throw "HDR Bad header format, unsupported FORMAT";
  50309. }
  50310. lineIndex += (line.length + 1);
  50311. line = this.readStringLine(uint8array, lineIndex);
  50312. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50313. var match = sizeRegexp.exec(line);
  50314. // TODO. Support +Y and -X if needed.
  50315. if (match.length < 3) {
  50316. throw "HDR Bad header format, no size";
  50317. }
  50318. width = parseInt(match[2]);
  50319. height = parseInt(match[1]);
  50320. if (width < 8 || width > 0x7fff) {
  50321. throw "HDR Bad header format, unsupported size";
  50322. }
  50323. lineIndex += (line.length + 1);
  50324. return {
  50325. height: height,
  50326. width: width,
  50327. dataPosition: lineIndex
  50328. };
  50329. };
  50330. /**
  50331. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50332. * This RGBE texture needs to store the information as a panorama.
  50333. *
  50334. * More information on this format are available here:
  50335. * https://en.wikipedia.org/wiki/RGBE_image_format
  50336. *
  50337. * @param buffer The binary file stored in an array buffer.
  50338. * @param size The expected size of the extracted cubemap.
  50339. * @return The Cube Map information.
  50340. */
  50341. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50342. var uint8array = new Uint8Array(buffer);
  50343. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50344. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50345. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50346. return cubeMapData;
  50347. };
  50348. /**
  50349. * Returns the pixels data extracted from an RGBE texture.
  50350. * This pixels will be stored left to right up to down in the R G B order in one array.
  50351. *
  50352. * More information on this format are available here:
  50353. * https://en.wikipedia.org/wiki/RGBE_image_format
  50354. *
  50355. * @param uint8array The binary file stored in an array buffer.
  50356. * @param hdrInfo The header information of the file.
  50357. * @return The pixels data in RGB right to left up to down order.
  50358. */
  50359. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50360. // Keep for multi format supports.
  50361. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50362. };
  50363. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50364. var num_scanlines = hdrInfo.height;
  50365. var scanline_width = hdrInfo.width;
  50366. var a, b, c, d, count;
  50367. var dataIndex = hdrInfo.dataPosition;
  50368. var index = 0, endIndex = 0, i = 0;
  50369. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50370. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50371. // 3 channels of 4 bytes per pixel in float.
  50372. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50373. var resultArray = new Float32Array(resultBuffer);
  50374. // read in each successive scanline
  50375. while (num_scanlines > 0) {
  50376. a = uint8array[dataIndex++];
  50377. b = uint8array[dataIndex++];
  50378. c = uint8array[dataIndex++];
  50379. d = uint8array[dataIndex++];
  50380. if (a != 2 || b != 2 || (c & 0x80)) {
  50381. // this file is not run length encoded
  50382. throw "HDR Bad header format, not RLE";
  50383. }
  50384. if (((c << 8) | d) != scanline_width) {
  50385. throw "HDR Bad header format, wrong scan line width";
  50386. }
  50387. index = 0;
  50388. // read each of the four channels for the scanline into the buffer
  50389. for (i = 0; i < 4; i++) {
  50390. endIndex = (i + 1) * scanline_width;
  50391. while (index < endIndex) {
  50392. a = uint8array[dataIndex++];
  50393. b = uint8array[dataIndex++];
  50394. if (a > 128) {
  50395. // a run of the same value
  50396. count = a - 128;
  50397. if ((count == 0) || (count > endIndex - index)) {
  50398. throw "HDR Bad Format, bad scanline data (run)";
  50399. }
  50400. while (count-- > 0) {
  50401. scanLineArray[index++] = b;
  50402. }
  50403. }
  50404. else {
  50405. // a non-run
  50406. count = a;
  50407. if ((count == 0) || (count > endIndex - index)) {
  50408. throw "HDR Bad Format, bad scanline data (non-run)";
  50409. }
  50410. scanLineArray[index++] = b;
  50411. if (--count > 0) {
  50412. for (var j = 0; j < count; j++) {
  50413. scanLineArray[index++] = uint8array[dataIndex++];
  50414. }
  50415. }
  50416. }
  50417. }
  50418. }
  50419. // now convert data from buffer into floats
  50420. for (i = 0; i < scanline_width; i++) {
  50421. a = scanLineArray[i];
  50422. b = scanLineArray[i + scanline_width];
  50423. c = scanLineArray[i + 2 * scanline_width];
  50424. d = scanLineArray[i + 3 * scanline_width];
  50425. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50426. }
  50427. num_scanlines--;
  50428. }
  50429. return resultArray;
  50430. };
  50431. return HDRTools;
  50432. }());
  50433. Internals.HDRTools = HDRTools;
  50434. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50435. })(BABYLON || (BABYLON = {}));
  50436. //# sourceMappingURL=babylon.tools.hdr.js.map
  50437. //_______________________________________________________________
  50438. // Extracted from CubeMapGen:
  50439. // https://code.google.com/archive/p/cubemapgen/
  50440. //
  50441. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50442. //_______________________________________________________________
  50443. var BABYLON;
  50444. (function (BABYLON) {
  50445. var Internals;
  50446. (function (Internals) {
  50447. /**
  50448. * The bounding box information used during the conversion process.
  50449. */
  50450. var CMGBoundinBox = (function () {
  50451. function CMGBoundinBox() {
  50452. this.min = new BABYLON.Vector3(0, 0, 0);
  50453. this.max = new BABYLON.Vector3(0, 0, 0);
  50454. this.clear();
  50455. }
  50456. CMGBoundinBox.prototype.clear = function () {
  50457. this.min.x = CMGBoundinBox.MAX;
  50458. this.min.y = CMGBoundinBox.MAX;
  50459. this.min.z = CMGBoundinBox.MAX;
  50460. this.max.x = CMGBoundinBox.MIN;
  50461. this.max.y = CMGBoundinBox.MIN;
  50462. this.max.z = CMGBoundinBox.MIN;
  50463. };
  50464. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50465. this.min.x = Math.min(this.min.x, x);
  50466. this.min.y = Math.min(this.min.y, y);
  50467. this.min.z = Math.min(this.min.z, z);
  50468. this.max.x = Math.max(this.max.x, x);
  50469. this.max.y = Math.max(this.max.y, y);
  50470. this.max.z = Math.max(this.max.z, z);
  50471. };
  50472. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50473. this.min.x = Math.max(this.min.x, x);
  50474. this.min.y = Math.max(this.min.y, y);
  50475. this.min.z = Math.max(this.min.z, z);
  50476. };
  50477. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50478. this.max.x = Math.min(this.max.x, x);
  50479. this.max.y = Math.min(this.max.y, y);
  50480. this.max.z = Math.min(this.max.z, z);
  50481. };
  50482. CMGBoundinBox.prototype.empty = function () {
  50483. if ((this.min.x > this.max.y) ||
  50484. (this.min.y > this.max.y) ||
  50485. (this.min.z > this.max.y)) {
  50486. return true;
  50487. }
  50488. else {
  50489. return false;
  50490. }
  50491. };
  50492. return CMGBoundinBox;
  50493. }());
  50494. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50495. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50496. /**
  50497. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50498. * required by the glossinees of a material.
  50499. *
  50500. * This only supports the cosine drop power as well as Warp fixup generation method.
  50501. *
  50502. * This is using the process from CubeMapGen described here:
  50503. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50504. */
  50505. var PMREMGenerator = (function () {
  50506. /**
  50507. * Constructor of the generator.
  50508. *
  50509. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50510. * @param inputSize The size of the cubemap faces
  50511. * @param outputSize The size of the output cubemap faces
  50512. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50513. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50514. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50515. * @param specularPower The max specular level of the desired cubemap
  50516. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50517. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50518. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50519. */
  50520. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50521. this.input = input;
  50522. this.inputSize = inputSize;
  50523. this.outputSize = outputSize;
  50524. this.maxNumMipLevels = maxNumMipLevels;
  50525. this.numChannels = numChannels;
  50526. this.isFloat = isFloat;
  50527. this.specularPower = specularPower;
  50528. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50529. this.excludeBase = excludeBase;
  50530. this.fixup = fixup;
  50531. this._outputSurface = [];
  50532. this._numMipLevels = 0;
  50533. }
  50534. /**
  50535. * Launches the filter process and return the result.
  50536. *
  50537. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50538. */
  50539. PMREMGenerator.prototype.filterCubeMap = function () {
  50540. // Init cubemap processor
  50541. this.init();
  50542. // Filters the cubemap
  50543. this.filterCubeMapMipChain();
  50544. // Returns the filtered mips.
  50545. return this._outputSurface;
  50546. };
  50547. PMREMGenerator.prototype.init = function () {
  50548. var i;
  50549. var j;
  50550. var mipLevelSize;
  50551. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50552. if (this.maxNumMipLevels == 0) {
  50553. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50554. }
  50555. //first miplevel size
  50556. mipLevelSize = this.outputSize;
  50557. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50558. for (j = 0; j < this.maxNumMipLevels; j++) {
  50559. this._outputSurface.length++;
  50560. this._outputSurface[j] = [];
  50561. //Iterate over faces for output images
  50562. for (i = 0; i < 6; i++) {
  50563. this._outputSurface[j].length++;
  50564. // Initializes a new array for the output.
  50565. if (this.isFloat) {
  50566. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50567. }
  50568. else {
  50569. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50570. }
  50571. }
  50572. //next mip level is half size
  50573. mipLevelSize >>= 1;
  50574. this._numMipLevels++;
  50575. //terminate if mip chain becomes too small
  50576. if (mipLevelSize == 0) {
  50577. this.maxNumMipLevels = j;
  50578. return;
  50579. }
  50580. }
  50581. };
  50582. //--------------------------------------------------------------------------------------
  50583. //Cube map filtering and mip chain generation.
  50584. // the cube map filtereing is specified using a number of parameters:
  50585. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50586. // indicates the region of the hemisphere to filter over for each tap.
  50587. //
  50588. // Note that the top mip level is also a filtered version of the original input images
  50589. // as well in order to create mip chains for diffuse environment illumination.
  50590. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50591. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50592. //
  50593. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50594. // is a_InitialMipAngle
  50595. //
  50596. // The angle for the subsequent levels of the mip chain are specified by their parents
  50597. // filtering angle and a per-level scale and bias
  50598. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50599. //
  50600. //--------------------------------------------------------------------------------------
  50601. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50602. // First, take count of the lighting model to modify SpecularPower
  50603. // 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;
  50604. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50605. //Cone angle start (for generating subsequent mip levels)
  50606. var currentSpecularPower = this.specularPower;
  50607. //Build filter lookup tables based on the source miplevel size
  50608. this.precomputeFilterLookupTables(this.inputSize);
  50609. // Note that we need to filter the first level before generating mipmap
  50610. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50611. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50612. // TODO : Write a function to copy and scale the base mipmap in output
  50613. // I am just lazy here and just put a high specular power value, and do some if.
  50614. if (this.excludeBase && (levelIndex == 0)) {
  50615. // 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).
  50616. currentSpecularPower = 100000.0;
  50617. }
  50618. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50619. var srcCubeImage = this.input;
  50620. var dstCubeImage = this._outputSurface[levelIndex];
  50621. var dstSize = this.outputSize >> levelIndex;
  50622. // Compute required angle.
  50623. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50624. // filter cube surfaces
  50625. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50626. // fix seams
  50627. if (this.fixup) {
  50628. this.fixupCubeEdges(dstCubeImage, dstSize);
  50629. }
  50630. // Decrease the specular power to generate the mipmap chain
  50631. // TODO : Use another method for Exclude (see first comment at start of the function
  50632. if (this.excludeBase && (levelIndex == 0)) {
  50633. currentSpecularPower = this.specularPower;
  50634. }
  50635. currentSpecularPower *= this.cosinePowerDropPerMip;
  50636. }
  50637. };
  50638. //--------------------------------------------------------------------------------------
  50639. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50640. // It allow to optimize the texel to access base on the specular power.
  50641. //--------------------------------------------------------------------------------------
  50642. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50643. // We want to find the alpha such that:
  50644. // cos(alpha)^cosinePower = epsilon
  50645. // That's: acos(epsilon^(1/cosinePower))
  50646. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50647. var angle = 180.0;
  50648. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50649. angle *= 180.0 / Math.PI; // Convert to degree
  50650. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50651. return angle;
  50652. };
  50653. //--------------------------------------------------------------------------------------
  50654. //Builds the following lookup tables prior to filtering:
  50655. // -normalizer cube map
  50656. // -tap weight lookup table
  50657. //
  50658. //--------------------------------------------------------------------------------------
  50659. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50660. var srcTexelAngle;
  50661. var iCubeFace;
  50662. //clear pre-existing normalizer cube map
  50663. this._normCubeMap = [];
  50664. //Normalized vectors per cubeface and per-texel solid angle
  50665. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50666. };
  50667. //--------------------------------------------------------------------------------------
  50668. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50669. //
  50670. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50671. //
  50672. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50673. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50674. // below
  50675. //--------------------------------------------------------------------------------------
  50676. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50677. var iCubeFace;
  50678. var u;
  50679. var v;
  50680. //iterate over cube faces
  50681. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50682. //First three channels for norm cube, and last channel for solid angle
  50683. this._normCubeMap.push(new Float32Array(size * size * 4));
  50684. //fast texture walk, build normalizer cube map
  50685. var facesData = this.input[iCubeFace];
  50686. for (v = 0; v < size; v++) {
  50687. for (u = 0; u < size; u++) {
  50688. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50689. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50690. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50691. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50692. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50693. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50694. }
  50695. }
  50696. }
  50697. };
  50698. //--------------------------------------------------------------------------------------
  50699. // Convert cubemap face texel coordinates and face idx to 3D vector
  50700. // note the U and V coords are integer coords and range from 0 to size-1
  50701. // this routine can be used to generate a normalizer cube map
  50702. //--------------------------------------------------------------------------------------
  50703. // SL BEGIN
  50704. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50705. var nvcU;
  50706. var nvcV;
  50707. var tempVec;
  50708. // Change from original AMD code
  50709. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50710. // + 0.5f is for texel center addressing
  50711. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50712. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50713. // warp fixup
  50714. if (fixup && size > 1) {
  50715. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50716. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50717. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50718. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50719. }
  50720. // Get current vector
  50721. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50722. // U contribution
  50723. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50724. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50725. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50726. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50727. // V contribution and Sum
  50728. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50729. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50730. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50731. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50732. //add face axis
  50733. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50734. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50735. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50736. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50737. //normalize vector
  50738. PMREMGenerator._vectorTemp.normalize();
  50739. return PMREMGenerator._vectorTemp;
  50740. };
  50741. //--------------------------------------------------------------------------------------
  50742. // Convert 3D vector to cubemap face texel coordinates and face idx
  50743. // note the U and V coords are integer coords and range from 0 to size-1
  50744. // this routine can be used to generate a normalizer cube map
  50745. //
  50746. // returns face IDX and texel coords
  50747. //--------------------------------------------------------------------------------------
  50748. // SL BEGIN
  50749. /*
  50750. Mapping Texture Coordinates to Cube Map Faces
  50751. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50752. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50753. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50754. map arrangement in Pixar's RenderMan package.
  50755. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50756. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50757. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50758. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50759. the major axis direction). The target column in the table below explains how the major axis direction
  50760. maps to the 2D image of a particular cube map target.
  50761. major axis
  50762. direction target sc tc ma
  50763. ---------- --------------------------------- --- --- ---
  50764. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50765. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50766. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50767. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50768. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50769. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50770. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50771. an updated (s,t) is calculated as follows
  50772. s = ( sc/|ma| + 1 ) / 2
  50773. t = ( tc/|ma| + 1 ) / 2
  50774. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50775. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50776. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50777. */
  50778. // Note this method return U and V in range from 0 to size-1
  50779. // SL END
  50780. // Store the information in vector3 for convenience (faceindex, u, v)
  50781. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50782. var maxCoord;
  50783. var faceIdx;
  50784. //absolute value 3
  50785. var absX = Math.abs(x);
  50786. var absY = Math.abs(y);
  50787. var absZ = Math.abs(z);
  50788. if (absX >= absY && absX >= absZ) {
  50789. maxCoord = absX;
  50790. if (x >= 0) {
  50791. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50792. }
  50793. else {
  50794. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50795. }
  50796. }
  50797. else if (absY >= absX && absY >= absZ) {
  50798. maxCoord = absY;
  50799. if (y >= 0) {
  50800. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50801. }
  50802. else {
  50803. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50804. }
  50805. }
  50806. else {
  50807. maxCoord = absZ;
  50808. if (z >= 0) {
  50809. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50810. }
  50811. else {
  50812. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50813. }
  50814. }
  50815. //divide through by max coord so face vector lies on cube face
  50816. var scale = 1 / maxCoord;
  50817. x *= scale;
  50818. y *= scale;
  50819. z *= scale;
  50820. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50821. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50822. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50823. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50824. // Modify original AMD code to return value from 0 to Size - 1
  50825. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50826. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50827. PMREMGenerator._vectorTemp.x = faceIdx;
  50828. PMREMGenerator._vectorTemp.y = u;
  50829. PMREMGenerator._vectorTemp.z = v;
  50830. return PMREMGenerator._vectorTemp;
  50831. };
  50832. //--------------------------------------------------------------------------------------
  50833. //Original code from Ignacio CastaÒo
  50834. // This formula is from Manne ÷hrstrˆm's thesis.
  50835. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50836. // cube face and return the area of the projection of that portion on the
  50837. // surface of the sphere.
  50838. //--------------------------------------------------------------------------------------
  50839. PMREMGenerator.prototype.areaElement = function (x, y) {
  50840. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50841. };
  50842. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50843. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50844. // (+ 0.5f is for texel center addressing)
  50845. u = (2.0 * (u + 0.5) / size) - 1.0;
  50846. v = (2.0 * (v + 0.5) / size) - 1.0;
  50847. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50848. var invResolution = 1.0 / size;
  50849. // U and V are the -1..1 texture coordinate on the current face.
  50850. // Get projected area for this texel
  50851. var x0 = u - invResolution;
  50852. var y0 = v - invResolution;
  50853. var x1 = u + invResolution;
  50854. var y1 = v + invResolution;
  50855. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50856. return solidAngle;
  50857. };
  50858. //--------------------------------------------------------------------------------------
  50859. //The key to the speed of these filtering routines is to quickly define a per-face
  50860. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50861. // Later these pixels are selectively processed based on their dot products to see if
  50862. // they reside within the filtering cone.
  50863. //
  50864. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50865. // of the number of texels needed to be covered in width and height order to filter the
  50866. // region. the bounding box for the center taps face is defined first, and if the
  50867. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50868. // defined next
  50869. //--------------------------------------------------------------------------------------
  50870. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50871. // note that pixels within these regions may be rejected
  50872. // based on the anlge
  50873. var iCubeFace;
  50874. var u;
  50875. var v;
  50876. // bounding box per face to specify region to process
  50877. var filterExtents = [];
  50878. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50879. filterExtents.push(new CMGBoundinBox());
  50880. }
  50881. // min angle a src texel can cover (in degrees)
  50882. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  50883. // angle about center tap to define filter cone
  50884. // filter angle is 1/2 the cone angle
  50885. var filterAngle = filterConeAngle / 2.0;
  50886. //ensure filter angle is larger than a texel
  50887. if (filterAngle < srcTexelAngle) {
  50888. filterAngle = srcTexelAngle;
  50889. }
  50890. //ensure filter cone is always smaller than the hemisphere
  50891. if (filterAngle > 90.0) {
  50892. filterAngle = 90.0;
  50893. }
  50894. // the maximum number of texels in 1D the filter cone angle will cover
  50895. // used to determine bounding box size for filter extents
  50896. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  50897. // ensure conservative region always covers at least one texel
  50898. if (filterSize < 1) {
  50899. filterSize = 1;
  50900. }
  50901. // dotProdThresh threshold based on cone angle to determine whether or not taps
  50902. // reside within the cone angle
  50903. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  50904. // process required faces
  50905. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50906. //iterate over dst cube map face texel
  50907. for (v = 0; v < dstSize; v++) {
  50908. for (u = 0; u < dstSize; u++) {
  50909. //get center tap direction
  50910. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  50911. //clear old per-face filter extents
  50912. this.clearFilterExtents(filterExtents);
  50913. //define per-face filter extents
  50914. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  50915. //perform filtering of src faces using filter extents
  50916. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  50917. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  50918. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  50919. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  50920. }
  50921. }
  50922. }
  50923. };
  50924. //--------------------------------------------------------------------------------------
  50925. //Clear filter extents for the 6 cube map faces
  50926. //--------------------------------------------------------------------------------------
  50927. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  50928. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  50929. filterExtents[iCubeFaces].clear();
  50930. }
  50931. };
  50932. //--------------------------------------------------------------------------------------
  50933. //Define per-face bounding box filter extents
  50934. //
  50935. // These define conservative texel regions in each of the faces the filter can possibly
  50936. // process. When the pixels in the regions are actually processed, the dot product
  50937. // between the tap vector and the center tap vector is used to determine the weight of
  50938. // the tap and whether or not the tap is within the cone.
  50939. //
  50940. //--------------------------------------------------------------------------------------
  50941. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  50942. //neighboring face and bleed over amount, and width of BBOX for
  50943. // left, right, top, and bottom edges of this face
  50944. var bleedOverAmount = [0, 0, 0, 0];
  50945. var bleedOverBBoxMin = [0, 0, 0, 0];
  50946. var bleedOverBBoxMax = [0, 0, 0, 0];
  50947. var neighborFace;
  50948. var neighborEdge;
  50949. var oppositeFaceIdx;
  50950. //get face idx, and u, v info from center tap dir
  50951. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  50952. var faceIdx = result.x;
  50953. var u = result.y;
  50954. var v = result.z;
  50955. //define bbox size within face
  50956. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  50957. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  50958. filterExtents[faceIdx].clampMin(0, 0, 0);
  50959. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  50960. //u and v extent in face corresponding to center tap
  50961. var minU = filterExtents[faceIdx].min.x;
  50962. var minV = filterExtents[faceIdx].min.y;
  50963. var maxU = filterExtents[faceIdx].max.x;
  50964. var maxV = filterExtents[faceIdx].max.y;
  50965. //bleed over amounts for face across u=0 edge (left)
  50966. bleedOverAmount[0] = (bboxSize - u);
  50967. bleedOverBBoxMin[0] = minV;
  50968. bleedOverBBoxMax[0] = maxV;
  50969. //bleed over amounts for face across u=1 edge (right)
  50970. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  50971. bleedOverBBoxMin[1] = minV;
  50972. bleedOverBBoxMax[1] = maxV;
  50973. //bleed over to face across v=0 edge (up)
  50974. bleedOverAmount[2] = (bboxSize - v);
  50975. bleedOverBBoxMin[2] = minU;
  50976. bleedOverBBoxMax[2] = maxU;
  50977. //bleed over to face across v=1 edge (down)
  50978. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  50979. bleedOverBBoxMin[3] = minU;
  50980. bleedOverBBoxMax[3] = maxU;
  50981. //compute bleed over regions in neighboring faces
  50982. for (var i = 0; i < 4; i++) {
  50983. if (bleedOverAmount[i] > 0) {
  50984. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  50985. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  50986. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  50987. // be flipped: the cases are
  50988. // if a left edge mates with a left or bottom edge on the neighbor
  50989. // if a top edge mates with a top or right edge on the neighbor
  50990. // if a right edge mates with a right or top edge on the neighbor
  50991. // if a bottom edge mates with a bottom or left edge on the neighbor
  50992. //Seeing as the edges are enumerated as follows
  50993. // left =0
  50994. // right =1
  50995. // top =2
  50996. // bottom =3
  50997. //
  50998. // so if the edge enums are the same, or the sum of the enums == 3,
  50999. // the bbox needs to be flipped
  51000. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51001. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51002. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51003. }
  51004. //The way the bounding box is extended onto the neighboring face
  51005. // depends on which edge of neighboring face abuts with this one
  51006. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51007. case PMREMGenerator.CP_EDGE_LEFT:
  51008. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51009. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51010. break;
  51011. case PMREMGenerator.CP_EDGE_RIGHT:
  51012. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51013. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51014. break;
  51015. case PMREMGenerator.CP_EDGE_TOP:
  51016. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51017. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51018. break;
  51019. case PMREMGenerator.CP_EDGE_BOTTOM:
  51020. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51021. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51022. break;
  51023. }
  51024. //clamp filter extents in non-center tap faces to remain within surface
  51025. filterExtents[neighborFace].clampMin(0, 0, 0);
  51026. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51027. }
  51028. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51029. // from the center tap face, then process the opposite face entirely for now.
  51030. //Note that the cases in which this happens, what usually happens is that
  51031. // more than one edge bleeds onto the opposite face, and the bounding box
  51032. // encompasses the entire cube map face.
  51033. if (bleedOverAmount[i] > srcSize) {
  51034. //determine opposite face
  51035. switch (faceIdx) {
  51036. case PMREMGenerator.CP_FACE_X_POS:
  51037. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51038. break;
  51039. case PMREMGenerator.CP_FACE_X_NEG:
  51040. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51041. break;
  51042. case PMREMGenerator.CP_FACE_Y_POS:
  51043. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51044. break;
  51045. case PMREMGenerator.CP_FACE_Y_NEG:
  51046. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51047. break;
  51048. case PMREMGenerator.CP_FACE_Z_POS:
  51049. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51050. break;
  51051. case PMREMGenerator.CP_FACE_Z_NEG:
  51052. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51053. break;
  51054. default:
  51055. break;
  51056. }
  51057. //just encompass entire face for now
  51058. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51059. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51060. }
  51061. }
  51062. };
  51063. //--------------------------------------------------------------------------------------
  51064. //ProcessFilterExtents
  51065. // Process bounding box in each cube face
  51066. //
  51067. //--------------------------------------------------------------------------------------
  51068. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51069. //accumulators are 64-bit floats in order to have the precision needed
  51070. // over a summation of a large number of pixels
  51071. var dstAccum = [0, 0, 0, 0];
  51072. var weightAccum = 0;
  51073. var k = 0;
  51074. var nSrcChannels = this.numChannels;
  51075. // norm cube map and srcCubeMap have same face width
  51076. var faceWidth = srcSize;
  51077. //amount to add to pointer to move to next scanline in images
  51078. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51079. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51080. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51081. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51082. // iterate over cubefaces
  51083. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51084. //if bbox is non empty
  51085. if (!filterExtents[iFaceIdx].empty()) {
  51086. var uStart = filterExtents[iFaceIdx].min.x;
  51087. var vStart = filterExtents[iFaceIdx].min.y;
  51088. var uEnd = filterExtents[iFaceIdx].max.x;
  51089. var vEnd = filterExtents[iFaceIdx].max.y;
  51090. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51091. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51092. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51093. for (var v = vStart; v <= vEnd; v++) {
  51094. var normCubeRowWalk = 0;
  51095. var srcCubeRowWalk = 0;
  51096. for (var u = uStart; u <= uEnd; u++) {
  51097. //pointer to direction in cube map associated with texel
  51098. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51099. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51100. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51101. //check dot product to see if texel is within cone
  51102. var tapDotProd = texelVectX * centerTapDir.x +
  51103. texelVectY * centerTapDir.y +
  51104. texelVectZ * centerTapDir.z;
  51105. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51106. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51107. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51108. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51109. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51110. // so just adding one to specularpower do the trick.
  51111. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51112. //iterate over channels
  51113. for (k = 0; k < nSrcChannels; k++) {
  51114. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51115. srcCubeRowWalk++;
  51116. }
  51117. weightAccum += weight; //accumulate weight
  51118. }
  51119. else {
  51120. //step across source pixel
  51121. srcCubeRowWalk += nSrcChannels;
  51122. }
  51123. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51124. }
  51125. startIndexNormCubeMap += normCubePitch;
  51126. startIndexSrcCubeMap += srcCubePitch;
  51127. }
  51128. }
  51129. }
  51130. //divide through by weights if weight is non zero
  51131. if (weightAccum != 0.0) {
  51132. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51133. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51134. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51135. if (this.numChannels > 3) {
  51136. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51137. }
  51138. }
  51139. else {
  51140. // otherwise sample nearest
  51141. // get face idx and u, v texel coordinate in face
  51142. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51143. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51144. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51145. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51146. if (this.numChannels > 3) {
  51147. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51148. }
  51149. }
  51150. return PMREMGenerator._vectorTemp;
  51151. };
  51152. //--------------------------------------------------------------------------------------
  51153. // Fixup cube edges
  51154. //
  51155. // average texels on cube map faces across the edges
  51156. // WARP/BENT Method Only.
  51157. //--------------------------------------------------------------------------------------
  51158. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51159. var k;
  51160. var j;
  51161. var i;
  51162. var iFace;
  51163. var iCorner = 0;
  51164. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51165. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51166. // note that if functionality to filter across the three texels for each corner, then
  51167. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51168. var cornerPtr = [
  51169. [[], [], []],
  51170. [[], [], []],
  51171. [[], [], []],
  51172. [[], [], []],
  51173. [[], [], []],
  51174. [[], [], []],
  51175. [[], [], []],
  51176. [[], [], []]
  51177. ];
  51178. //if there is no fixup, or fixup width = 0, do nothing
  51179. if (cubeMapSize < 1) {
  51180. return;
  51181. }
  51182. //special case 1x1 cubemap, average face colors
  51183. if (cubeMapSize == 1) {
  51184. //iterate over channels
  51185. for (k = 0; k < this.numChannels; k++) {
  51186. var accum = 0.0;
  51187. //iterate over faces to accumulate face colors
  51188. for (iFace = 0; iFace < 6; iFace++) {
  51189. accum += cubeMap[iFace][k];
  51190. }
  51191. //compute average over 6 face colors
  51192. accum /= 6.0;
  51193. //iterate over faces to distribute face colors
  51194. for (iFace = 0; iFace < 6; iFace++) {
  51195. cubeMap[iFace][k] = accum;
  51196. }
  51197. }
  51198. return;
  51199. }
  51200. //iterate over faces to collect list of corner texel pointers
  51201. for (iFace = 0; iFace < 6; iFace++) {
  51202. //the 4 corner pointers for this face
  51203. faceCornerStartIndicies[0] = [iFace, 0];
  51204. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51205. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51206. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51207. //iterate over face corners to collect cube corner pointers
  51208. for (iCorner = 0; iCorner < 4; iCorner++) {
  51209. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51210. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51211. cornerNumPtrs[corner]++;
  51212. }
  51213. }
  51214. //iterate over corners to average across corner tap values
  51215. for (iCorner = 0; iCorner < 8; iCorner++) {
  51216. for (k = 0; k < this.numChannels; k++) {
  51217. var cornerTapAccum = 0.0;
  51218. //iterate over corner texels and average results
  51219. for (i = 0; i < 3; i++) {
  51220. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51221. }
  51222. //divide by 3 to compute average of corner tap values
  51223. cornerTapAccum *= (1.0 / 3.0);
  51224. //iterate over corner texels and average results
  51225. for (i = 0; i < 3; i++) {
  51226. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51227. }
  51228. }
  51229. }
  51230. //iterate over the twelve edges of the cube to average across edges
  51231. for (i = 0; i < 12; i++) {
  51232. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51233. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51234. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51235. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51236. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51237. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51238. var edgeWalk = 0;
  51239. var neighborEdgeWalk = 0;
  51240. //Determine walking pointers based on edge type
  51241. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51242. switch (edge) {
  51243. case PMREMGenerator.CP_EDGE_LEFT:
  51244. // no change to faceEdgeStartPtr
  51245. edgeWalk = this.numChannels * cubeMapSize;
  51246. break;
  51247. case PMREMGenerator.CP_EDGE_RIGHT:
  51248. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51249. edgeWalk = this.numChannels * cubeMapSize;
  51250. break;
  51251. case PMREMGenerator.CP_EDGE_TOP:
  51252. // no change to faceEdgeStartPtr
  51253. edgeWalk = this.numChannels;
  51254. break;
  51255. case PMREMGenerator.CP_EDGE_BOTTOM:
  51256. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51257. edgeWalk = this.numChannels;
  51258. break;
  51259. }
  51260. //For certain types of edge abutments, the neighbor edge walk needs to
  51261. // be flipped: the cases are
  51262. // if a left edge mates with a left or bottom edge on the neighbor
  51263. // if a top edge mates with a top or right edge on the neighbor
  51264. // if a right edge mates with a right or top edge on the neighbor
  51265. // if a bottom edge mates with a bottom or left edge on the neighbor
  51266. //Seeing as the edges are enumerated as follows
  51267. // left =0
  51268. // right =1
  51269. // top =2
  51270. // bottom =3
  51271. //
  51272. //If the edge enums are the same, or the sum of the enums == 3,
  51273. // the neighbor edge walk needs to be flipped
  51274. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51275. switch (neighborEdge) {
  51276. case PMREMGenerator.CP_EDGE_LEFT:
  51277. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51278. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51279. break;
  51280. case PMREMGenerator.CP_EDGE_RIGHT:
  51281. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51282. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51283. break;
  51284. case PMREMGenerator.CP_EDGE_TOP:
  51285. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51286. neighborEdgeWalk = -this.numChannels;
  51287. break;
  51288. case PMREMGenerator.CP_EDGE_BOTTOM:
  51289. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51290. neighborEdgeWalk = -this.numChannels;
  51291. break;
  51292. }
  51293. }
  51294. else {
  51295. //swapped direction neighbor edge walk
  51296. switch (neighborEdge) {
  51297. case PMREMGenerator.CP_EDGE_LEFT:
  51298. //no change to neighborEdgeStartPtr for this case since it points
  51299. // to the upper left corner already
  51300. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51301. break;
  51302. case PMREMGenerator.CP_EDGE_RIGHT:
  51303. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51304. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51305. break;
  51306. case PMREMGenerator.CP_EDGE_TOP:
  51307. //no change to neighborEdgeStartPtr for this case since it points
  51308. // to the upper left corner already
  51309. neighborEdgeWalk = this.numChannels;
  51310. break;
  51311. case PMREMGenerator.CP_EDGE_BOTTOM:
  51312. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51313. neighborEdgeWalk = this.numChannels;
  51314. break;
  51315. }
  51316. }
  51317. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51318. //nearby neighborhood
  51319. //step ahead one texel on edge
  51320. edgeStartIndex += edgeWalk;
  51321. neighborEdgeStartIndex += neighborEdgeWalk;
  51322. // note that this loop does not process the corner texels, since they have already been
  51323. // averaged across faces across earlier
  51324. for (j = 1; j < (cubeMapSize - 1); j++) {
  51325. //for each set of taps along edge, average them
  51326. // and rewrite the results into the edges
  51327. for (k = 0; k < this.numChannels; k++) {
  51328. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51329. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51330. //compute average of tap intensity values
  51331. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51332. //propagate average of taps to edge taps
  51333. cubeMap[face][edgeStartIndex + k] = avgTap;
  51334. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51335. }
  51336. edgeStartIndex += edgeWalk;
  51337. neighborEdgeStartIndex += neighborEdgeWalk;
  51338. }
  51339. }
  51340. };
  51341. return PMREMGenerator;
  51342. }());
  51343. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51344. PMREMGenerator.CP_UDIR = 0;
  51345. PMREMGenerator.CP_VDIR = 1;
  51346. PMREMGenerator.CP_FACEAXIS = 2;
  51347. //used to index cube faces
  51348. PMREMGenerator.CP_FACE_X_POS = 0;
  51349. PMREMGenerator.CP_FACE_X_NEG = 1;
  51350. PMREMGenerator.CP_FACE_Y_POS = 2;
  51351. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51352. PMREMGenerator.CP_FACE_Z_POS = 4;
  51353. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51354. //used to index image edges
  51355. // NOTE.. the actual number corresponding to the edge is important
  51356. // do not change these, or the code will break
  51357. //
  51358. // CP_EDGE_LEFT is u = 0
  51359. // CP_EDGE_RIGHT is u = width-1
  51360. // CP_EDGE_TOP is v = 0
  51361. // CP_EDGE_BOTTOM is v = height-1
  51362. PMREMGenerator.CP_EDGE_LEFT = 0;
  51363. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51364. PMREMGenerator.CP_EDGE_TOP = 2;
  51365. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51366. //corners of CUBE map (P or N specifys if it corresponds to the
  51367. // positive or negative direction each of X, Y, and Z
  51368. PMREMGenerator.CP_CORNER_NNN = 0;
  51369. PMREMGenerator.CP_CORNER_NNP = 1;
  51370. PMREMGenerator.CP_CORNER_NPN = 2;
  51371. PMREMGenerator.CP_CORNER_NPP = 3;
  51372. PMREMGenerator.CP_CORNER_PNN = 4;
  51373. PMREMGenerator.CP_CORNER_PNP = 5;
  51374. PMREMGenerator.CP_CORNER_PPN = 6;
  51375. PMREMGenerator.CP_CORNER_PPP = 7;
  51376. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51377. //3x2 matrices that map cube map indexing vectors in 3d
  51378. // (after face selection and divide through by the
  51379. // _ABSOLUTE VALUE_ of the max coord)
  51380. // into NVC space
  51381. //Note this currently assumes the D3D cube face ordering and orientation
  51382. PMREMGenerator._sgFace2DMapping = [
  51383. //XPOS face
  51384. [[0, 0, -1],
  51385. [0, -1, 0],
  51386. [1, 0, 0]],
  51387. //XNEG face
  51388. [[0, 0, 1],
  51389. [0, -1, 0],
  51390. [-1, 0, 0]],
  51391. //YPOS face
  51392. [[1, 0, 0],
  51393. [0, 0, 1],
  51394. [0, 1, 0]],
  51395. //YNEG face
  51396. [[1, 0, 0],
  51397. [0, 0, -1],
  51398. [0, -1, 0]],
  51399. //ZPOS face
  51400. [[1, 0, 0],
  51401. [0, -1, 0],
  51402. [0, 0, 1]],
  51403. //ZNEG face
  51404. [[-1, 0, 0],
  51405. [0, -1, 0],
  51406. [0, 0, -1]],
  51407. ];
  51408. //------------------------------------------------------------------------------
  51409. // D3D cube map face specification
  51410. // mapping from 3D x,y,z cube map lookup coordinates
  51411. // to 2D within face u,v coordinates
  51412. //
  51413. // --------------------> U direction
  51414. // | (within-face texture space)
  51415. // | _____
  51416. // | | |
  51417. // | | +Y |
  51418. // | _____|_____|_____ _____
  51419. // | | | | | |
  51420. // | | -X | +Z | +X | -Z |
  51421. // | |_____|_____|_____|_____|
  51422. // | | |
  51423. // | | -Y |
  51424. // | |_____|
  51425. // |
  51426. // v V direction
  51427. // (within-face texture space)
  51428. //------------------------------------------------------------------------------
  51429. //Information about neighbors and how texture coorrdinates change across faces
  51430. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51431. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51432. //Note this currently assumes the D3D cube face ordering and orientation
  51433. PMREMGenerator._sgCubeNgh = [
  51434. //XPOS face
  51435. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51436. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51437. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51438. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51439. //XNEG face
  51440. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51441. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51442. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51443. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51444. //YPOS face
  51445. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51446. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51447. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51448. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51449. //YNEG face
  51450. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51451. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51452. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51453. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51454. //ZPOS face
  51455. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51456. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51457. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51458. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51459. //ZNEG face
  51460. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51461. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51462. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51463. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51464. ];
  51465. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51466. // this table is used to average over the edges.
  51467. PMREMGenerator._sgCubeEdgeList = [
  51468. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51469. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51470. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51471. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51472. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51473. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51474. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51475. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51476. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51477. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51478. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51479. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51480. ];
  51481. //Information about which of the 8 cube corners are correspond to the
  51482. // the 4 corners in each cube face
  51483. // the order is upper left, upper right, lower left, lower right
  51484. PMREMGenerator._sgCubeCornerList = [
  51485. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51486. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51487. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51488. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51489. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51490. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51491. ];
  51492. Internals.PMREMGenerator = PMREMGenerator;
  51493. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51494. })(BABYLON || (BABYLON = {}));
  51495. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  51496. var BABYLON;
  51497. (function (BABYLON) {
  51498. /**
  51499. * This represents a texture coming from an HDR input.
  51500. *
  51501. * The only supported format is currently panorama picture stored in RGBE format.
  51502. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51503. */
  51504. var HDRCubeTexture = (function (_super) {
  51505. __extends(HDRCubeTexture, _super);
  51506. /**
  51507. * Instantiates an HDRTexture from the following parameters.
  51508. *
  51509. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51510. * @param scene The scene the texture will be used in
  51511. * @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.
  51512. * @param noMipmap Forces to not generate the mipmap if true
  51513. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51514. * @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)
  51515. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51516. */
  51517. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  51518. if (noMipmap === void 0) { noMipmap = false; }
  51519. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51520. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51521. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51522. var _this = _super.call(this, scene) || this;
  51523. _this._useInGammaSpace = false;
  51524. _this._generateHarmonics = true;
  51525. _this._isBABYLONPreprocessed = false;
  51526. /**
  51527. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51528. */
  51529. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51530. /**
  51531. * The spherical polynomial data extracted from the texture.
  51532. */
  51533. _this.sphericalPolynomial = null;
  51534. /**
  51535. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51536. * This is usefull at run time to apply the good shader.
  51537. */
  51538. _this.isPMREM = false;
  51539. if (!url) {
  51540. return _this;
  51541. }
  51542. _this.name = url;
  51543. _this.url = url;
  51544. _this.hasAlpha = false;
  51545. _this.isCube = true;
  51546. _this._textureMatrix = BABYLON.Matrix.Identity();
  51547. if (size) {
  51548. _this._isBABYLONPreprocessed = false;
  51549. _this._noMipmap = noMipmap;
  51550. _this._size = size;
  51551. _this._useInGammaSpace = useInGammaSpace;
  51552. _this._usePMREMGenerator = usePMREMGenerator &&
  51553. scene.getEngine().getCaps().textureLOD &&
  51554. _this.getScene().getEngine().getCaps().textureFloat &&
  51555. !_this._useInGammaSpace;
  51556. }
  51557. else {
  51558. _this._isBABYLONPreprocessed = true;
  51559. _this._noMipmap = false;
  51560. _this._useInGammaSpace = false;
  51561. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51562. _this.getScene().getEngine().getCaps().textureFloat &&
  51563. !_this._useInGammaSpace;
  51564. }
  51565. _this.isPMREM = _this._usePMREMGenerator;
  51566. _this._texture = _this._getFromCache(url, _this._noMipmap);
  51567. if (!_this._texture) {
  51568. if (!scene.useDelayedTextureLoading) {
  51569. _this.loadTexture();
  51570. }
  51571. else {
  51572. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51573. }
  51574. }
  51575. return _this;
  51576. }
  51577. /**
  51578. * Occurs when the file is a preprocessed .babylon.hdr file.
  51579. */
  51580. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51581. var _this = this;
  51582. var mipLevels = 0;
  51583. var floatArrayView = null;
  51584. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51585. var mips = [];
  51586. var startIndex = 30;
  51587. for (var level = 0; level < mipLevels; level++) {
  51588. mips.push([]);
  51589. // Fill each pixel of the mip level.
  51590. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51591. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51592. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51593. mips[level].push(faceData);
  51594. startIndex += faceSize;
  51595. }
  51596. }
  51597. return mips;
  51598. } : null;
  51599. var callback = function (buffer) {
  51600. // Create Native Array Views
  51601. var intArrayView = new Int32Array(buffer);
  51602. floatArrayView = new Float32Array(buffer);
  51603. // Fill header.
  51604. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51605. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51606. // Update Texture Information.
  51607. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51608. // Fill polynomial information.
  51609. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51610. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51611. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51612. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51613. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51614. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51615. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51616. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51617. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51618. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51619. // Fill pixel data.
  51620. mipLevels = intArrayView[29]; // Number of mip levels.
  51621. var startIndex = 30;
  51622. var data = [];
  51623. var faceSize = Math.pow(_this._size, 2) * 3;
  51624. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51625. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51626. startIndex += faceSize;
  51627. }
  51628. var results = [];
  51629. var byteArray = null;
  51630. // Push each faces.
  51631. for (var k = 0; k < 6; k++) {
  51632. var dataFace = null;
  51633. // If special cases.
  51634. if (!mipmapGenerator) {
  51635. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51636. dataFace = data[j];
  51637. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51638. // 3 channels of 1 bytes per pixel in bytes.
  51639. var byteBuffer = new ArrayBuffer(faceSize);
  51640. byteArray = new Uint8Array(byteBuffer);
  51641. }
  51642. for (var i = 0; i < _this._size * _this._size; i++) {
  51643. // Put in gamma space if requested.
  51644. if (_this._useInGammaSpace) {
  51645. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51646. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51647. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51648. }
  51649. // Convert to int texture for fallback.
  51650. if (byteArray) {
  51651. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51652. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51653. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51654. // May use luminance instead if the result is not accurate.
  51655. var max = Math.max(Math.max(r, g), b);
  51656. if (max > 255) {
  51657. var scale = 255 / max;
  51658. r *= scale;
  51659. g *= scale;
  51660. b *= scale;
  51661. }
  51662. byteArray[(i * 3) + 0] = r;
  51663. byteArray[(i * 3) + 1] = g;
  51664. byteArray[(i * 3) + 2] = b;
  51665. }
  51666. }
  51667. }
  51668. else {
  51669. dataFace = data[k];
  51670. }
  51671. // Fill the array accordingly.
  51672. if (byteArray) {
  51673. results.push(byteArray);
  51674. }
  51675. else {
  51676. results.push(dataFace);
  51677. }
  51678. }
  51679. return results;
  51680. };
  51681. 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);
  51682. };
  51683. /**
  51684. * Occurs when the file is raw .hdr file.
  51685. */
  51686. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51687. var _this = this;
  51688. var callback = function (buffer) {
  51689. // Extract the raw linear data.
  51690. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51691. // Generate harmonics if needed.
  51692. if (_this._generateHarmonics) {
  51693. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51694. }
  51695. var results = [];
  51696. var byteArray = null;
  51697. // Push each faces.
  51698. for (var j = 0; j < 6; j++) {
  51699. // Create uintarray fallback.
  51700. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51701. // 3 channels of 1 bytes per pixel in bytes.
  51702. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51703. byteArray = new Uint8Array(byteBuffer);
  51704. }
  51705. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51706. // If special cases.
  51707. if (_this._useInGammaSpace || byteArray) {
  51708. for (var i = 0; i < _this._size * _this._size; i++) {
  51709. // Put in gamma space if requested.
  51710. if (_this._useInGammaSpace) {
  51711. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51712. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51713. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51714. }
  51715. // Convert to int texture for fallback.
  51716. if (byteArray) {
  51717. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51718. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51719. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51720. // May use luminance instead if the result is not accurate.
  51721. var max = Math.max(Math.max(r, g), b);
  51722. if (max > 255) {
  51723. var scale = 255 / max;
  51724. r *= scale;
  51725. g *= scale;
  51726. b *= scale;
  51727. }
  51728. byteArray[(i * 3) + 0] = r;
  51729. byteArray[(i * 3) + 1] = g;
  51730. byteArray[(i * 3) + 2] = b;
  51731. }
  51732. }
  51733. }
  51734. if (byteArray) {
  51735. results.push(byteArray);
  51736. }
  51737. else {
  51738. results.push(dataFace);
  51739. }
  51740. }
  51741. return results;
  51742. };
  51743. var mipmapGenerator = null;
  51744. if (!this._noMipmap &&
  51745. this._usePMREMGenerator) {
  51746. mipmapGenerator = function (data) {
  51747. // Custom setup of the generator matching with the PBR shader values.
  51748. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51749. return generator.filterCubeMap();
  51750. };
  51751. }
  51752. 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);
  51753. };
  51754. /**
  51755. * Starts the loading process of the texture.
  51756. */
  51757. HDRCubeTexture.prototype.loadTexture = function () {
  51758. if (this._isBABYLONPreprocessed) {
  51759. this.loadBabylonTexture();
  51760. }
  51761. else {
  51762. this.loadHDRTexture();
  51763. }
  51764. };
  51765. HDRCubeTexture.prototype.clone = function () {
  51766. var size = this._isBABYLONPreprocessed ? null : this._size;
  51767. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51768. // Base texture
  51769. newTexture.level = this.level;
  51770. newTexture.wrapU = this.wrapU;
  51771. newTexture.wrapV = this.wrapV;
  51772. newTexture.coordinatesIndex = this.coordinatesIndex;
  51773. newTexture.coordinatesMode = this.coordinatesMode;
  51774. return newTexture;
  51775. };
  51776. // Methods
  51777. HDRCubeTexture.prototype.delayLoad = function () {
  51778. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51779. return;
  51780. }
  51781. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51782. this._texture = this._getFromCache(this.url, this._noMipmap);
  51783. if (!this._texture) {
  51784. this.loadTexture();
  51785. }
  51786. };
  51787. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51788. return this._textureMatrix;
  51789. };
  51790. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51791. var texture = null;
  51792. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51793. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51794. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  51795. texture.name = parsedTexture.name;
  51796. texture.hasAlpha = parsedTexture.hasAlpha;
  51797. texture.level = parsedTexture.level;
  51798. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51799. }
  51800. return texture;
  51801. };
  51802. HDRCubeTexture.prototype.serialize = function () {
  51803. if (!this.name) {
  51804. return null;
  51805. }
  51806. var serializationObject = {};
  51807. serializationObject.name = this.name;
  51808. serializationObject.hasAlpha = this.hasAlpha;
  51809. serializationObject.isCube = true;
  51810. serializationObject.level = this.level;
  51811. serializationObject.size = this._size;
  51812. serializationObject.coordinatesMode = this.coordinatesMode;
  51813. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51814. serializationObject.generateHarmonics = this._generateHarmonics;
  51815. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51816. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51817. serializationObject.customType = "BABYLON.HDRCubeTexture";
  51818. return serializationObject;
  51819. };
  51820. /**
  51821. * Saves as a file the data contained in the texture in a binary format.
  51822. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51823. * as the spherical used in the lighting.
  51824. * @param url The HDR file url.
  51825. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51826. * @param onError Method called if any error happens during download.
  51827. * @return The packed binary data.
  51828. */
  51829. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51830. if (onError === void 0) { onError = null; }
  51831. var callback = function (buffer) {
  51832. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51833. // Returns a URL you can use as a href.
  51834. var objUrl = window.URL.createObjectURL(data);
  51835. // Simulates a link to it and click to dowload.
  51836. var a = document.createElement("a");
  51837. document.body.appendChild(a);
  51838. a.style.display = "none";
  51839. a.href = objUrl;
  51840. a.download = "envmap.babylon.hdr";
  51841. a.click();
  51842. };
  51843. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51844. };
  51845. /**
  51846. * Serializes the data contained in the texture in a binary format.
  51847. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51848. * as the spherical used in the lighting.
  51849. * @param url The HDR file url.
  51850. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51851. * @param onError Method called if any error happens during download.
  51852. * @return The packed binary data.
  51853. */
  51854. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51855. if (onError === void 0) { onError = null; }
  51856. // Needs the url tho create the texture.
  51857. if (!url) {
  51858. return null;
  51859. }
  51860. // Check Power of two size.
  51861. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51862. return null;
  51863. }
  51864. var getDataCallback = function (dataBuffer) {
  51865. // Extract the raw linear data.
  51866. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51867. // Generate harmonics if needed.
  51868. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51869. // Generate seamless faces
  51870. var mipGeneratorArray = [];
  51871. // Data are known to be in +X +Y +Z -X -Y -Z
  51872. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51873. mipGeneratorArray.push(cubeData.right); // +X
  51874. mipGeneratorArray.push(cubeData.left); // -X
  51875. mipGeneratorArray.push(cubeData.up); // +Y
  51876. mipGeneratorArray.push(cubeData.down); // -Y
  51877. mipGeneratorArray.push(cubeData.front); // +Z
  51878. mipGeneratorArray.push(cubeData.back); // -Z
  51879. // Custom setup of the generator matching with the PBR shader values.
  51880. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51881. var mippedData = generator.filterCubeMap();
  51882. // Compute required byte length.
  51883. var byteLength = 1 * 4; // Raw Data Version int32.
  51884. byteLength += 4; // CubeMap max mip face size int32.
  51885. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  51886. // Add data size.
  51887. byteLength += 4; // Number of mip levels int32.
  51888. for (var level = 0; level < mippedData.length; level++) {
  51889. var mipSize = size >> level;
  51890. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  51891. }
  51892. // Prepare binary structure.
  51893. var buffer = new ArrayBuffer(byteLength);
  51894. var intArrayView = new Int32Array(buffer);
  51895. var floatArrayView = new Float32Array(buffer);
  51896. // Fill header.
  51897. intArrayView[0] = 1; // Version 1.
  51898. intArrayView[1] = size; // CubeMap max mip face size.
  51899. // Fill polynomial information.
  51900. sphericalPolynomial.x.toArray(floatArrayView, 2);
  51901. sphericalPolynomial.y.toArray(floatArrayView, 5);
  51902. sphericalPolynomial.z.toArray(floatArrayView, 8);
  51903. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  51904. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  51905. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  51906. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  51907. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  51908. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  51909. // Fill pixel data.
  51910. intArrayView[29] = mippedData.length; // Number of mip levels.
  51911. var startIndex = 30;
  51912. for (var level = 0; level < mippedData.length; level++) {
  51913. // Fill each pixel of the mip level.
  51914. var faceSize = Math.pow(size >> level, 2) * 3;
  51915. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51916. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  51917. startIndex += faceSize;
  51918. }
  51919. }
  51920. // Callback.
  51921. callback(buffer);
  51922. };
  51923. // Download and process.
  51924. BABYLON.Tools.LoadFile(url, function (data) {
  51925. getDataCallback(data);
  51926. }, null, null, true, onError);
  51927. };
  51928. return HDRCubeTexture;
  51929. }(BABYLON.BaseTexture));
  51930. HDRCubeTexture._facesMapping = [
  51931. "right",
  51932. "up",
  51933. "front",
  51934. "left",
  51935. "down",
  51936. "back"
  51937. ];
  51938. BABYLON.HDRCubeTexture = HDRCubeTexture;
  51939. })(BABYLON || (BABYLON = {}));
  51940. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  51941. var BABYLON;
  51942. (function (BABYLON) {
  51943. var Debug;
  51944. (function (Debug) {
  51945. /**
  51946. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  51947. */
  51948. var SkeletonViewer = (function () {
  51949. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  51950. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  51951. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  51952. this.skeleton = skeleton;
  51953. this.mesh = mesh;
  51954. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  51955. this.renderingGroupId = renderingGroupId;
  51956. this.color = BABYLON.Color3.White();
  51957. this._debugLines = [];
  51958. this._isEnabled = false;
  51959. this._scene = scene;
  51960. this.update();
  51961. this._renderFunction = this.update.bind(this);
  51962. }
  51963. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  51964. get: function () {
  51965. return this._isEnabled;
  51966. },
  51967. set: function (value) {
  51968. if (this._isEnabled === value) {
  51969. return;
  51970. }
  51971. this._isEnabled = value;
  51972. if (value) {
  51973. this._scene.registerBeforeRender(this._renderFunction);
  51974. }
  51975. else {
  51976. this._scene.unregisterBeforeRender(this._renderFunction);
  51977. }
  51978. },
  51979. enumerable: true,
  51980. configurable: true
  51981. });
  51982. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  51983. if (x === void 0) { x = 0; }
  51984. if (y === void 0) { y = 0; }
  51985. if (z === void 0) { z = 0; }
  51986. var tmat = BABYLON.Tmp.Matrix[0];
  51987. var parentBone = bone.getParent();
  51988. tmat.copyFrom(bone.getLocalMatrix());
  51989. if (x !== 0 || y !== 0 || z !== 0) {
  51990. var tmat2 = BABYLON.Tmp.Matrix[1];
  51991. BABYLON.Matrix.IdentityToRef(tmat2);
  51992. tmat2.m[12] = x;
  51993. tmat2.m[13] = y;
  51994. tmat2.m[14] = z;
  51995. tmat2.multiplyToRef(tmat, tmat);
  51996. }
  51997. if (parentBone) {
  51998. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  51999. }
  52000. tmat.multiplyToRef(meshMat, tmat);
  52001. position.x = tmat.m[12];
  52002. position.y = tmat.m[13];
  52003. position.z = tmat.m[14];
  52004. };
  52005. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  52006. var len = bones.length;
  52007. for (var i = 0; i < len; i++) {
  52008. var bone = bones[i];
  52009. var points = this._debugLines[i];
  52010. if (!points) {
  52011. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52012. this._debugLines[i] = points;
  52013. }
  52014. this._getBonePosition(points[0], bone, meshMat);
  52015. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  52016. }
  52017. };
  52018. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  52019. var len = bones.length;
  52020. var boneNum = 0;
  52021. for (var i = len - 1; i >= 0; i--) {
  52022. var childBone = bones[i];
  52023. var parentBone = childBone.getParent();
  52024. if (!parentBone) {
  52025. continue;
  52026. }
  52027. var points = this._debugLines[boneNum];
  52028. if (!points) {
  52029. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52030. this._debugLines[boneNum] = points;
  52031. }
  52032. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  52033. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  52034. boneNum++;
  52035. }
  52036. };
  52037. SkeletonViewer.prototype.update = function () {
  52038. if (this.autoUpdateBonesMatrices) {
  52039. this.skeleton.computeAbsoluteTransforms();
  52040. }
  52041. if (this.skeleton.bones[0].length === undefined) {
  52042. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52043. }
  52044. else {
  52045. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52046. }
  52047. if (!this._debugMesh) {
  52048. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  52049. this._debugMesh.renderingGroupId = this.renderingGroupId;
  52050. }
  52051. else {
  52052. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  52053. }
  52054. this._debugMesh.color = this.color;
  52055. };
  52056. SkeletonViewer.prototype.dispose = function () {
  52057. if (this._debugMesh) {
  52058. this.isEnabled = false;
  52059. this._debugMesh.dispose();
  52060. this._debugMesh = null;
  52061. }
  52062. };
  52063. return SkeletonViewer;
  52064. }());
  52065. Debug.SkeletonViewer = SkeletonViewer;
  52066. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52067. })(BABYLON || (BABYLON = {}));
  52068. //# sourceMappingURL=babylon.skeletonViewer.js.map
  52069. var BABYLON;
  52070. (function (BABYLON) {
  52071. var Debug;
  52072. (function (Debug) {
  52073. var AxesViewer = (function () {
  52074. function AxesViewer(scene, scaleLines) {
  52075. if (scaleLines === void 0) { scaleLines = 1; }
  52076. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52077. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52078. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52079. this.scaleLines = 1;
  52080. this.scaleLines = scaleLines;
  52081. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  52082. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  52083. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  52084. this._xmesh.renderingGroupId = 2;
  52085. this._ymesh.renderingGroupId = 2;
  52086. this._zmesh.renderingGroupId = 2;
  52087. this._xmesh.material.checkReadyOnlyOnce = true;
  52088. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  52089. this._ymesh.material.checkReadyOnlyOnce = true;
  52090. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  52091. this._zmesh.material.checkReadyOnlyOnce = true;
  52092. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  52093. this.scene = scene;
  52094. }
  52095. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  52096. var scaleLines = this.scaleLines;
  52097. var point1 = this._xline[0];
  52098. var point2 = this._xline[1];
  52099. point1.x = position.x;
  52100. point1.y = position.y;
  52101. point1.z = position.z;
  52102. point2.x = point1.x + xaxis.x * scaleLines;
  52103. point2.y = point1.y + xaxis.y * scaleLines;
  52104. point2.z = point1.z + xaxis.z * scaleLines;
  52105. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  52106. point1 = this._yline[0];
  52107. point2 = this._yline[1];
  52108. point1.x = position.x;
  52109. point1.y = position.y;
  52110. point1.z = position.z;
  52111. point2.x = point1.x + yaxis.x * scaleLines;
  52112. point2.y = point1.y + yaxis.y * scaleLines;
  52113. point2.z = point1.z + yaxis.z * scaleLines;
  52114. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  52115. point1 = this._zline[0];
  52116. point2 = this._zline[1];
  52117. point1.x = position.x;
  52118. point1.y = position.y;
  52119. point1.z = position.z;
  52120. point2.x = point1.x + zaxis.x * scaleLines;
  52121. point2.y = point1.y + zaxis.y * scaleLines;
  52122. point2.z = point1.z + zaxis.z * scaleLines;
  52123. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  52124. };
  52125. AxesViewer.prototype.dispose = function () {
  52126. if (this._xmesh) {
  52127. this._xmesh.dispose();
  52128. this._ymesh.dispose();
  52129. this._zmesh.dispose();
  52130. this._xmesh = null;
  52131. this._ymesh = null;
  52132. this._zmesh = null;
  52133. this._xline = null;
  52134. this._yline = null;
  52135. this._zline = null;
  52136. this.scene = null;
  52137. }
  52138. };
  52139. return AxesViewer;
  52140. }());
  52141. Debug.AxesViewer = AxesViewer;
  52142. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52143. })(BABYLON || (BABYLON = {}));
  52144. //# sourceMappingURL=babylon.axesViewer.js.map
  52145. var BABYLON;
  52146. (function (BABYLON) {
  52147. var Debug;
  52148. (function (Debug) {
  52149. var BoneAxesViewer = (function (_super) {
  52150. __extends(BoneAxesViewer, _super);
  52151. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52152. if (scaleLines === void 0) { scaleLines = 1; }
  52153. var _this = _super.call(this, scene, scaleLines) || this;
  52154. _this.pos = BABYLON.Vector3.Zero();
  52155. _this.xaxis = BABYLON.Vector3.Zero();
  52156. _this.yaxis = BABYLON.Vector3.Zero();
  52157. _this.zaxis = BABYLON.Vector3.Zero();
  52158. _this.mesh = mesh;
  52159. _this.bone = bone;
  52160. return _this;
  52161. }
  52162. BoneAxesViewer.prototype.update = function () {
  52163. var bone = this.bone;
  52164. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52165. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52166. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52167. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52168. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52169. };
  52170. BoneAxesViewer.prototype.dispose = function () {
  52171. if (this.pos) {
  52172. this.pos = null;
  52173. this.xaxis = null;
  52174. this.yaxis = null;
  52175. this.zaxis = null;
  52176. this.mesh = null;
  52177. this.bone = null;
  52178. _super.prototype.dispose.call(this);
  52179. }
  52180. };
  52181. return BoneAxesViewer;
  52182. }(Debug.AxesViewer));
  52183. Debug.BoneAxesViewer = BoneAxesViewer;
  52184. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52185. })(BABYLON || (BABYLON = {}));
  52186. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52187. var BABYLON;
  52188. (function (BABYLON) {
  52189. /**
  52190. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52191. * It can help converting any input color in a desired output one. This can then be used to create effects
  52192. * from sepia, black and white to sixties or futuristic rendering...
  52193. *
  52194. * The only supported format is currently 3dl.
  52195. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52196. */
  52197. var ColorGradingTexture = (function (_super) {
  52198. __extends(ColorGradingTexture, _super);
  52199. /**
  52200. * Instantiates a ColorGradingTexture from the following parameters.
  52201. *
  52202. * @param url The location of the color gradind data (currently only supporting 3dl)
  52203. * @param scene The scene the texture will be used in
  52204. */
  52205. function ColorGradingTexture(url, scene) {
  52206. var _this = _super.call(this, scene) || this;
  52207. if (!url) {
  52208. return _this;
  52209. }
  52210. _this._textureMatrix = BABYLON.Matrix.Identity();
  52211. _this.name = url;
  52212. _this.url = url;
  52213. _this.hasAlpha = false;
  52214. _this.isCube = false;
  52215. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52216. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52217. _this.anisotropicFilteringLevel = 1;
  52218. _this._texture = _this._getFromCache(url, true);
  52219. if (!_this._texture) {
  52220. if (!scene.useDelayedTextureLoading) {
  52221. _this.loadTexture();
  52222. }
  52223. else {
  52224. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52225. }
  52226. }
  52227. return _this;
  52228. }
  52229. /**
  52230. * Returns the texture matrix used in most of the material.
  52231. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52232. */
  52233. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52234. return this._textureMatrix;
  52235. };
  52236. /**
  52237. * Occurs when the file being loaded is a .3dl LUT file.
  52238. */
  52239. ColorGradingTexture.prototype.load3dlTexture = function () {
  52240. var _this = this;
  52241. var mipLevels = 0;
  52242. var floatArrayView = null;
  52243. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52244. this._texture = texture;
  52245. var callback = function (text) {
  52246. var data;
  52247. var tempData;
  52248. var line;
  52249. var lines = text.split('\n');
  52250. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52251. var maxColor = 0;
  52252. for (var i = 0; i < lines.length; i++) {
  52253. line = lines[i];
  52254. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52255. continue;
  52256. if (line.indexOf('#') === 0)
  52257. continue;
  52258. var words = line.split(" ");
  52259. if (size === 0) {
  52260. // Number of space + one
  52261. size = words.length;
  52262. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52263. tempData = new Float32Array(size * size * size * 4);
  52264. continue;
  52265. }
  52266. if (size != 0) {
  52267. var r = Math.max(parseInt(words[0]), 0);
  52268. var g = Math.max(parseInt(words[1]), 0);
  52269. var b = Math.max(parseInt(words[2]), 0);
  52270. maxColor = Math.max(r, maxColor);
  52271. maxColor = Math.max(g, maxColor);
  52272. maxColor = Math.max(b, maxColor);
  52273. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52274. tempData[pixelStorageIndex + 0] = r;
  52275. tempData[pixelStorageIndex + 1] = g;
  52276. tempData[pixelStorageIndex + 2] = b;
  52277. tempData[pixelStorageIndex + 3] = 0;
  52278. pixelIndexSlice++;
  52279. if (pixelIndexSlice % size == 0) {
  52280. pixelIndexH++;
  52281. pixelIndexSlice = 0;
  52282. if (pixelIndexH % size == 0) {
  52283. pixelIndexW++;
  52284. pixelIndexH = 0;
  52285. }
  52286. }
  52287. }
  52288. }
  52289. for (var i = 0; i < tempData.length; i++) {
  52290. var value = tempData[i];
  52291. data[i] = (value / maxColor * 255);
  52292. }
  52293. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52294. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52295. };
  52296. BABYLON.Tools.LoadFile(this.url, callback);
  52297. return this._texture;
  52298. };
  52299. /**
  52300. * Starts the loading process of the texture.
  52301. */
  52302. ColorGradingTexture.prototype.loadTexture = function () {
  52303. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52304. this.load3dlTexture();
  52305. }
  52306. };
  52307. /**
  52308. * Clones the color gradind texture.
  52309. */
  52310. ColorGradingTexture.prototype.clone = function () {
  52311. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52312. // Base texture
  52313. newTexture.level = this.level;
  52314. return newTexture;
  52315. };
  52316. /**
  52317. * Called during delayed load for textures.
  52318. */
  52319. ColorGradingTexture.prototype.delayLoad = function () {
  52320. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52321. return;
  52322. }
  52323. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52324. this._texture = this._getFromCache(this.url, true);
  52325. if (!this._texture) {
  52326. this.loadTexture();
  52327. }
  52328. };
  52329. /**
  52330. * Binds the color grading to the shader.
  52331. * @param colorGrading The texture to bind
  52332. * @param effect The effect to bind to
  52333. */
  52334. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52335. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52336. var x = colorGrading.level; // Texture Level
  52337. var y = colorGrading.getSize().height; // Texture Size example with 8
  52338. var z = y - 1.0; // SizeMinusOne 8 - 1
  52339. var w = 1 / y; // Space of 1 slice 1 / 8
  52340. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  52341. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  52342. 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
  52343. 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
  52344. 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
  52345. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  52346. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  52347. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  52348. };
  52349. /**
  52350. * Prepare the list of uniforms associated with the ColorGrading effects.
  52351. * @param uniformsList The list of uniforms used in the effect
  52352. * @param samplersList The list of samplers used in the effect
  52353. */
  52354. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  52355. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  52356. samplersList.push("cameraColorGrading2DSampler");
  52357. };
  52358. /**
  52359. * Parses a color grading texture serialized by Babylon.
  52360. * @param parsedTexture The texture information being parsedTexture
  52361. * @param scene The scene to load the texture in
  52362. * @param rootUrl The root url of the data assets to load
  52363. * @return A color gradind texture
  52364. */
  52365. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52366. var texture = null;
  52367. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52368. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  52369. texture.name = parsedTexture.name;
  52370. texture.level = parsedTexture.level;
  52371. }
  52372. return texture;
  52373. };
  52374. /**
  52375. * Serializes the LUT texture to json format.
  52376. */
  52377. ColorGradingTexture.prototype.serialize = function () {
  52378. if (!this.name) {
  52379. return null;
  52380. }
  52381. var serializationObject = {};
  52382. serializationObject.name = this.name;
  52383. serializationObject.level = this.level;
  52384. serializationObject.customType = "BABYLON.ColorGradingTexture";
  52385. return serializationObject;
  52386. };
  52387. return ColorGradingTexture;
  52388. }(BABYLON.BaseTexture));
  52389. /**
  52390. * Empty line regex stored for GC.
  52391. */
  52392. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  52393. BABYLON.ColorGradingTexture = ColorGradingTexture;
  52394. })(BABYLON || (BABYLON = {}));
  52395. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  52396. var BABYLON;
  52397. (function (BABYLON) {
  52398. /**
  52399. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52400. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52401. * 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;
  52402. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52403. */
  52404. var ColorCurves = (function () {
  52405. function ColorCurves() {
  52406. this._dirty = true;
  52407. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  52408. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  52409. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52410. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  52411. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52412. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  52413. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  52414. this._globalHue = 30;
  52415. this._globalDensity = 0;
  52416. this._globalSaturation = 0;
  52417. this._globalExposure = 0;
  52418. this._highlightsHue = 30;
  52419. this._highlightsDensity = 0;
  52420. this._highlightsSaturation = 0;
  52421. this._highlightsExposure = 0;
  52422. this._midtonesHue = 30;
  52423. this._midtonesDensity = 0;
  52424. this._midtonesSaturation = 0;
  52425. this._midtonesExposure = 0;
  52426. this._shadowsHue = 30;
  52427. this._shadowsDensity = 0;
  52428. this._shadowsSaturation = 0;
  52429. this._shadowsExposure = 0;
  52430. }
  52431. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  52432. /**
  52433. * Gets the global Hue value.
  52434. * 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).
  52435. */
  52436. get: function () {
  52437. return this._globalHue;
  52438. },
  52439. /**
  52440. * Sets the global Hue value.
  52441. * 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).
  52442. */
  52443. set: function (value) {
  52444. this._globalHue = value;
  52445. this._dirty = true;
  52446. },
  52447. enumerable: true,
  52448. configurable: true
  52449. });
  52450. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  52451. /**
  52452. * Gets the global Density value.
  52453. * 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.
  52454. * Values less than zero provide a filter of opposite hue.
  52455. */
  52456. get: function () {
  52457. return this._globalDensity;
  52458. },
  52459. /**
  52460. * Sets the global Density value.
  52461. * 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.
  52462. * Values less than zero provide a filter of opposite hue.
  52463. */
  52464. set: function (value) {
  52465. this._globalDensity = value;
  52466. this._dirty = true;
  52467. },
  52468. enumerable: true,
  52469. configurable: true
  52470. });
  52471. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  52472. /**
  52473. * Gets the global Saturation value.
  52474. * 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.
  52475. */
  52476. get: function () {
  52477. return this._globalSaturation;
  52478. },
  52479. /**
  52480. * Sets the global Saturation value.
  52481. * 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.
  52482. */
  52483. set: function (value) {
  52484. this._globalSaturation = value;
  52485. this._dirty = true;
  52486. },
  52487. enumerable: true,
  52488. configurable: true
  52489. });
  52490. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  52491. /**
  52492. * Gets the highlights Hue value.
  52493. * 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).
  52494. */
  52495. get: function () {
  52496. return this._highlightsHue;
  52497. },
  52498. /**
  52499. * Sets the highlights Hue value.
  52500. * 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).
  52501. */
  52502. set: function (value) {
  52503. this._highlightsHue = value;
  52504. this._dirty = true;
  52505. },
  52506. enumerable: true,
  52507. configurable: true
  52508. });
  52509. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  52510. /**
  52511. * Gets the highlights Density value.
  52512. * 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.
  52513. * Values less than zero provide a filter of opposite hue.
  52514. */
  52515. get: function () {
  52516. return this._highlightsDensity;
  52517. },
  52518. /**
  52519. * Sets the highlights Density value.
  52520. * 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.
  52521. * Values less than zero provide a filter of opposite hue.
  52522. */
  52523. set: function (value) {
  52524. this._highlightsDensity = value;
  52525. this._dirty = true;
  52526. },
  52527. enumerable: true,
  52528. configurable: true
  52529. });
  52530. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  52531. /**
  52532. * Gets the highlights Saturation value.
  52533. * 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.
  52534. */
  52535. get: function () {
  52536. return this._highlightsSaturation;
  52537. },
  52538. /**
  52539. * Sets the highlights Saturation value.
  52540. * 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.
  52541. */
  52542. set: function (value) {
  52543. this._highlightsSaturation = value;
  52544. this._dirty = true;
  52545. },
  52546. enumerable: true,
  52547. configurable: true
  52548. });
  52549. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  52550. /**
  52551. * Gets the highlights Exposure value.
  52552. * 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.
  52553. */
  52554. get: function () {
  52555. return this._highlightsExposure;
  52556. },
  52557. /**
  52558. * Sets the highlights Exposure value.
  52559. * 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.
  52560. */
  52561. set: function (value) {
  52562. this._highlightsExposure = value;
  52563. this._dirty = true;
  52564. },
  52565. enumerable: true,
  52566. configurable: true
  52567. });
  52568. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  52569. /**
  52570. * Gets the midtones Hue value.
  52571. * 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).
  52572. */
  52573. get: function () {
  52574. return this._midtonesHue;
  52575. },
  52576. /**
  52577. * Sets the midtones Hue value.
  52578. * 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).
  52579. */
  52580. set: function (value) {
  52581. this._midtonesHue = value;
  52582. this._dirty = true;
  52583. },
  52584. enumerable: true,
  52585. configurable: true
  52586. });
  52587. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  52588. /**
  52589. * Gets the midtones Density value.
  52590. * 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.
  52591. * Values less than zero provide a filter of opposite hue.
  52592. */
  52593. get: function () {
  52594. return this._midtonesDensity;
  52595. },
  52596. /**
  52597. * Sets the midtones Density value.
  52598. * 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.
  52599. * Values less than zero provide a filter of opposite hue.
  52600. */
  52601. set: function (value) {
  52602. this._midtonesDensity = value;
  52603. this._dirty = true;
  52604. },
  52605. enumerable: true,
  52606. configurable: true
  52607. });
  52608. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  52609. /**
  52610. * Gets the midtones Saturation value.
  52611. * 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.
  52612. */
  52613. get: function () {
  52614. return this._midtonesSaturation;
  52615. },
  52616. /**
  52617. * Sets the midtones Saturation value.
  52618. * 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.
  52619. */
  52620. set: function (value) {
  52621. this._midtonesSaturation = value;
  52622. this._dirty = true;
  52623. },
  52624. enumerable: true,
  52625. configurable: true
  52626. });
  52627. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  52628. /**
  52629. * Gets the midtones Exposure value.
  52630. * 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.
  52631. */
  52632. get: function () {
  52633. return this._midtonesExposure;
  52634. },
  52635. /**
  52636. * Sets the midtones Exposure value.
  52637. * 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.
  52638. */
  52639. set: function (value) {
  52640. this._midtonesExposure = value;
  52641. this._dirty = true;
  52642. },
  52643. enumerable: true,
  52644. configurable: true
  52645. });
  52646. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  52647. /**
  52648. * Gets the shadows Hue value.
  52649. * 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).
  52650. */
  52651. get: function () {
  52652. return this._shadowsHue;
  52653. },
  52654. /**
  52655. * Sets the shadows Hue value.
  52656. * 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).
  52657. */
  52658. set: function (value) {
  52659. this._shadowsHue = value;
  52660. this._dirty = true;
  52661. },
  52662. enumerable: true,
  52663. configurable: true
  52664. });
  52665. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  52666. /**
  52667. * Gets the shadows Density value.
  52668. * 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.
  52669. * Values less than zero provide a filter of opposite hue.
  52670. */
  52671. get: function () {
  52672. return this._shadowsDensity;
  52673. },
  52674. /**
  52675. * Sets the shadows Density value.
  52676. * 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.
  52677. * Values less than zero provide a filter of opposite hue.
  52678. */
  52679. set: function (value) {
  52680. this._shadowsDensity = value;
  52681. this._dirty = true;
  52682. },
  52683. enumerable: true,
  52684. configurable: true
  52685. });
  52686. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  52687. /**
  52688. * Gets the shadows Saturation value.
  52689. * 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.
  52690. */
  52691. get: function () {
  52692. return this._shadowsSaturation;
  52693. },
  52694. /**
  52695. * Sets the shadows Saturation value.
  52696. * 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.
  52697. */
  52698. set: function (value) {
  52699. this._shadowsSaturation = value;
  52700. this._dirty = true;
  52701. },
  52702. enumerable: true,
  52703. configurable: true
  52704. });
  52705. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  52706. /**
  52707. * Gets the shadows Exposure value.
  52708. * 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.
  52709. */
  52710. get: function () {
  52711. return this._shadowsExposure;
  52712. },
  52713. /**
  52714. * Sets the shadows Exposure value.
  52715. * 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.
  52716. */
  52717. set: function (value) {
  52718. this._shadowsExposure = value;
  52719. this._dirty = true;
  52720. },
  52721. enumerable: true,
  52722. configurable: true
  52723. });
  52724. /**
  52725. * Binds the color curves to the shader.
  52726. * @param colorCurves The color curve to bind
  52727. * @param effect The effect to bind to
  52728. */
  52729. ColorCurves.Bind = function (colorCurves, effect) {
  52730. if (colorCurves._dirty) {
  52731. colorCurves._dirty = false;
  52732. // Fill in global info.
  52733. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  52734. // Compute highlights info.
  52735. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  52736. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  52737. // Compute midtones info.
  52738. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  52739. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  52740. // Compute shadows info.
  52741. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  52742. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  52743. // Compute deltas (neutral is midtones).
  52744. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  52745. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  52746. }
  52747. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  52748. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  52749. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  52750. };
  52751. /**
  52752. * Prepare the list of uniforms associated with the ColorCurves effects.
  52753. * @param uniformsList The list of uniforms used in the effect
  52754. */
  52755. ColorCurves.PrepareUniforms = function (uniformsList) {
  52756. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  52757. };
  52758. /**
  52759. * Returns color grading data based on a hue, density, saturation and exposure value.
  52760. * @param filterHue The hue of the color filter.
  52761. * @param filterDensity The density of the color filter.
  52762. * @param saturation The saturation.
  52763. * @param exposure The exposure.
  52764. * @param result The result data container.
  52765. */
  52766. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  52767. if (hue == null) {
  52768. return;
  52769. }
  52770. hue = ColorCurves.clamp(hue, 0, 360);
  52771. density = ColorCurves.clamp(density, -100, 100);
  52772. saturation = ColorCurves.clamp(saturation, -100, 100);
  52773. exposure = ColorCurves.clamp(exposure, -100, 100);
  52774. // Remap the slider/config filter density with non-linear mapping and also scale by half
  52775. // so that the maximum filter density is only 50% control. This provides fine control
  52776. // for small values and reasonable range.
  52777. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  52778. density *= 0.5;
  52779. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  52780. if (density < 0) {
  52781. density *= -1;
  52782. hue = (hue + 180) % 360;
  52783. }
  52784. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  52785. result.scaleToRef(2, result);
  52786. result.a = 1 + 0.01 * saturation;
  52787. };
  52788. /**
  52789. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  52790. * @param value The input slider value in range [-100,100].
  52791. * @returns Adjusted value.
  52792. */
  52793. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  52794. value /= 100;
  52795. var x = Math.abs(value);
  52796. x = Math.pow(x, 2);
  52797. if (value < 0) {
  52798. x *= -1;
  52799. }
  52800. x *= 100;
  52801. return x;
  52802. };
  52803. /**
  52804. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  52805. * @param hue The hue (H) input.
  52806. * @param saturation The saturation (S) input.
  52807. * @param brightness The brightness (B) input.
  52808. * @result An RGBA color represented as Vector4.
  52809. */
  52810. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  52811. var h = ColorCurves.clamp(hue, 0, 360);
  52812. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  52813. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  52814. if (s === 0) {
  52815. result.r = v;
  52816. result.g = v;
  52817. result.b = v;
  52818. }
  52819. else {
  52820. // sector 0 to 5
  52821. h /= 60;
  52822. var i = Math.floor(h);
  52823. // fractional part of h
  52824. var f = h - i;
  52825. var p = v * (1 - s);
  52826. var q = v * (1 - s * f);
  52827. var t = v * (1 - s * (1 - f));
  52828. switch (i) {
  52829. case 0:
  52830. result.r = v;
  52831. result.g = t;
  52832. result.b = p;
  52833. break;
  52834. case 1:
  52835. result.r = q;
  52836. result.g = v;
  52837. result.b = p;
  52838. break;
  52839. case 2:
  52840. result.r = p;
  52841. result.g = v;
  52842. result.b = t;
  52843. break;
  52844. case 3:
  52845. result.r = p;
  52846. result.g = q;
  52847. result.b = v;
  52848. break;
  52849. case 4:
  52850. result.r = t;
  52851. result.g = p;
  52852. result.b = v;
  52853. break;
  52854. default:
  52855. result.r = v;
  52856. result.g = p;
  52857. result.b = q;
  52858. break;
  52859. }
  52860. }
  52861. result.a = 1;
  52862. };
  52863. /**
  52864. * Returns a value clamped between min and max
  52865. * @param value The value to clamp
  52866. * @param min The minimum of value
  52867. * @param max The maximum of value
  52868. * @returns The clamped value.
  52869. */
  52870. ColorCurves.clamp = function (value, min, max) {
  52871. return Math.min(Math.max(value, min), max);
  52872. };
  52873. /**
  52874. * Clones the current color curve instance.
  52875. * @return The cloned curves
  52876. */
  52877. ColorCurves.prototype.clone = function () {
  52878. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  52879. };
  52880. /**
  52881. * Serializes the current color curve instance to a json representation.
  52882. * @return a JSON representation
  52883. */
  52884. ColorCurves.prototype.serialize = function () {
  52885. return BABYLON.SerializationHelper.Serialize(this);
  52886. };
  52887. /**
  52888. * Parses the color curve from a json representation.
  52889. * @param source the JSON source to parse
  52890. * @return The parsed curves
  52891. */
  52892. ColorCurves.Parse = function (source) {
  52893. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  52894. };
  52895. return ColorCurves;
  52896. }());
  52897. __decorate([
  52898. BABYLON.serialize()
  52899. ], ColorCurves.prototype, "_globalHue", void 0);
  52900. __decorate([
  52901. BABYLON.serialize()
  52902. ], ColorCurves.prototype, "_globalDensity", void 0);
  52903. __decorate([
  52904. BABYLON.serialize()
  52905. ], ColorCurves.prototype, "_globalSaturation", void 0);
  52906. __decorate([
  52907. BABYLON.serialize()
  52908. ], ColorCurves.prototype, "_globalExposure", void 0);
  52909. __decorate([
  52910. BABYLON.serialize()
  52911. ], ColorCurves.prototype, "_highlightsHue", void 0);
  52912. __decorate([
  52913. BABYLON.serialize()
  52914. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  52915. __decorate([
  52916. BABYLON.serialize()
  52917. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  52918. __decorate([
  52919. BABYLON.serialize()
  52920. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  52921. __decorate([
  52922. BABYLON.serialize()
  52923. ], ColorCurves.prototype, "_midtonesHue", void 0);
  52924. __decorate([
  52925. BABYLON.serialize()
  52926. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  52927. __decorate([
  52928. BABYLON.serialize()
  52929. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  52930. __decorate([
  52931. BABYLON.serialize()
  52932. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  52933. BABYLON.ColorCurves = ColorCurves;
  52934. })(BABYLON || (BABYLON = {}));
  52935. //# sourceMappingURL=babylon.colorCurves.js.map
  52936. var BABYLON;
  52937. (function (BABYLON) {
  52938. var PBRMaterialDefines = (function (_super) {
  52939. __extends(PBRMaterialDefines, _super);
  52940. function PBRMaterialDefines() {
  52941. var _this = _super.call(this) || this;
  52942. _this.ALBEDO = false;
  52943. _this.AMBIENT = false;
  52944. _this.OPACITY = false;
  52945. _this.OPACITYRGB = false;
  52946. _this.REFLECTION = false;
  52947. _this.EMISSIVE = false;
  52948. _this.REFLECTIVITY = false;
  52949. _this.BUMP = false;
  52950. _this.PARALLAX = false;
  52951. _this.PARALLAXOCCLUSION = false;
  52952. _this.SPECULAROVERALPHA = false;
  52953. _this.CLIPPLANE = false;
  52954. _this.ALPHATEST = false;
  52955. _this.ALPHAFROMALBEDO = false;
  52956. _this.POINTSIZE = false;
  52957. _this.FOG = false;
  52958. _this.SPECULARTERM = false;
  52959. _this.OPACITYFRESNEL = false;
  52960. _this.EMISSIVEFRESNEL = false;
  52961. _this.FRESNEL = false;
  52962. _this.NORMAL = false;
  52963. _this.UV1 = false;
  52964. _this.UV2 = false;
  52965. _this.VERTEXCOLOR = false;
  52966. _this.VERTEXALPHA = false;
  52967. _this.NUM_BONE_INFLUENCERS = 0;
  52968. _this.BonesPerMesh = 0;
  52969. _this.INSTANCES = false;
  52970. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  52971. _this.MICROSURFACEAUTOMATIC = false;
  52972. _this.EMISSIVEASILLUMINATION = false;
  52973. _this.LINKEMISSIVEWITHALBEDO = false;
  52974. _this.LIGHTMAP = false;
  52975. _this.USELIGHTMAPASSHADOWMAP = false;
  52976. _this.REFLECTIONMAP_3D = false;
  52977. _this.REFLECTIONMAP_SPHERICAL = false;
  52978. _this.REFLECTIONMAP_PLANAR = false;
  52979. _this.REFLECTIONMAP_CUBIC = false;
  52980. _this.REFLECTIONMAP_PROJECTION = false;
  52981. _this.REFLECTIONMAP_SKYBOX = false;
  52982. _this.REFLECTIONMAP_EXPLICIT = false;
  52983. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  52984. _this.INVERTCUBICMAP = false;
  52985. _this.LOGARITHMICDEPTH = false;
  52986. _this.CAMERATONEMAP = false;
  52987. _this.CAMERACONTRAST = false;
  52988. _this.CAMERACOLORGRADING = false;
  52989. _this.CAMERACOLORCURVES = false;
  52990. _this.OVERLOADEDVALUES = false;
  52991. _this.OVERLOADEDSHADOWVALUES = false;
  52992. _this.USESPHERICALFROMREFLECTIONMAP = false;
  52993. _this.REFRACTION = false;
  52994. _this.REFRACTIONMAP_3D = false;
  52995. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  52996. _this.REFRACTIONMAPINLINEARSPACE = false;
  52997. _this.LODBASEDMICROSFURACE = false;
  52998. _this.USEPHYSICALLIGHTFALLOFF = false;
  52999. _this.RADIANCEOVERALPHA = false;
  53000. _this.USEPMREMREFLECTION = false;
  53001. _this.USEPMREMREFRACTION = false;
  53002. _this.OPENGLNORMALMAP = false;
  53003. _this.INVERTNORMALMAPX = false;
  53004. _this.INVERTNORMALMAPY = false;
  53005. _this.SHADOWFULLFLOAT = false;
  53006. _this.METALLICWORKFLOW = false;
  53007. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  53008. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  53009. _this.rebuild();
  53010. return _this;
  53011. }
  53012. return PBRMaterialDefines;
  53013. }(BABYLON.MaterialDefines));
  53014. /**
  53015. * The Physically based material of BJS.
  53016. *
  53017. * This offers the main features of a standard PBR material.
  53018. * For more information, please refer to the documentation :
  53019. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  53020. */
  53021. var PBRMaterial = (function (_super) {
  53022. __extends(PBRMaterial, _super);
  53023. /**
  53024. * Instantiates a new PBRMaterial instance.
  53025. *
  53026. * @param name The material name
  53027. * @param scene The scene the material will be use in.
  53028. */
  53029. function PBRMaterial(name, scene) {
  53030. var _this = _super.call(this, name, scene) || this;
  53031. /**
  53032. * Intensity of the direct lights e.g. the four lights available in your scene.
  53033. * This impacts both the direct diffuse and specular highlights.
  53034. */
  53035. _this.directIntensity = 1.0;
  53036. /**
  53037. * Intensity of the emissive part of the material.
  53038. * This helps controlling the emissive effect without modifying the emissive color.
  53039. */
  53040. _this.emissiveIntensity = 1.0;
  53041. /**
  53042. * Intensity of the environment e.g. how much the environment will light the object
  53043. * either through harmonics for rough material or through the refelction for shiny ones.
  53044. */
  53045. _this.environmentIntensity = 1.0;
  53046. /**
  53047. * This is a special control allowing the reduction of the specular highlights coming from the
  53048. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  53049. */
  53050. _this.specularIntensity = 1.0;
  53051. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  53052. /**
  53053. * Debug Control allowing disabling the bump map on this material.
  53054. */
  53055. _this.disableBumpMap = false;
  53056. /**
  53057. * Debug Control helping enforcing or dropping the darkness of shadows.
  53058. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  53059. */
  53060. _this.overloadedShadowIntensity = 1.0;
  53061. /**
  53062. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  53063. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  53064. */
  53065. _this.overloadedShadeIntensity = 1.0;
  53066. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  53067. /**
  53068. * The camera exposure used on this material.
  53069. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  53070. * This corresponds to a photographic exposure.
  53071. */
  53072. _this.cameraExposure = 1.0;
  53073. /**
  53074. * The camera contrast used on this material.
  53075. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  53076. */
  53077. _this.cameraContrast = 1.0;
  53078. /**
  53079. * Color Grading 2D Lookup Texture.
  53080. * This allows special effects like sepia, black and white to sixties rendering style.
  53081. */
  53082. _this.cameraColorGradingTexture = null;
  53083. /**
  53084. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53085. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53086. * 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;
  53087. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53088. */
  53089. _this.cameraColorCurves = null;
  53090. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  53091. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  53092. /**
  53093. * Debug Control allowing to overload the ambient color.
  53094. * This as to be use with the overloadedAmbientIntensity parameter.
  53095. */
  53096. _this.overloadedAmbient = BABYLON.Color3.White();
  53097. /**
  53098. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  53099. */
  53100. _this.overloadedAmbientIntensity = 0.0;
  53101. /**
  53102. * Debug Control allowing to overload the albedo color.
  53103. * This as to be use with the overloadedAlbedoIntensity parameter.
  53104. */
  53105. _this.overloadedAlbedo = BABYLON.Color3.White();
  53106. /**
  53107. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  53108. */
  53109. _this.overloadedAlbedoIntensity = 0.0;
  53110. /**
  53111. * Debug Control allowing to overload the reflectivity color.
  53112. * This as to be use with the overloadedReflectivityIntensity parameter.
  53113. */
  53114. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  53115. /**
  53116. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  53117. */
  53118. _this.overloadedReflectivityIntensity = 0.0;
  53119. /**
  53120. * Debug Control allowing to overload the emissive color.
  53121. * This as to be use with the overloadedEmissiveIntensity parameter.
  53122. */
  53123. _this.overloadedEmissive = BABYLON.Color3.White();
  53124. /**
  53125. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  53126. */
  53127. _this.overloadedEmissiveIntensity = 0.0;
  53128. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  53129. /**
  53130. * Debug Control allowing to overload the reflection color.
  53131. * This as to be use with the overloadedReflectionIntensity parameter.
  53132. */
  53133. _this.overloadedReflection = BABYLON.Color3.White();
  53134. /**
  53135. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  53136. */
  53137. _this.overloadedReflectionIntensity = 0.0;
  53138. /**
  53139. * Debug Control allowing to overload the microsurface.
  53140. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53141. */
  53142. _this.overloadedMicroSurface = 0.0;
  53143. /**
  53144. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53145. */
  53146. _this.overloadedMicroSurfaceIntensity = 0.0;
  53147. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  53148. /**
  53149. * AKA Occlusion Texture Intensity in other nomenclature.
  53150. */
  53151. _this.ambientTextureStrength = 1.0;
  53152. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53153. /**
  53154. * AKA Diffuse Color in other nomenclature.
  53155. */
  53156. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53157. /**
  53158. * AKA Specular Color in other nomenclature.
  53159. */
  53160. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53161. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53162. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53163. /**
  53164. * AKA Glossiness in other nomenclature.
  53165. */
  53166. _this.microSurface = 0.9;
  53167. /**
  53168. * source material index of refraction (IOR)' / 'destination material IOR.
  53169. */
  53170. _this.indexOfRefraction = 0.66;
  53171. /**
  53172. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53173. */
  53174. _this.invertRefractionY = false;
  53175. /**
  53176. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53177. * Materials half opaque for instance using refraction could benefit from this control.
  53178. */
  53179. _this.linkRefractionWithTransparency = false;
  53180. /**
  53181. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53182. */
  53183. _this.linkEmissiveWithAlbedo = false;
  53184. _this.useLightmapAsShadowmap = false;
  53185. /**
  53186. * In this mode, the emissive informtaion will always be added to the lighting once.
  53187. * A light for instance can be thought as emissive.
  53188. */
  53189. _this.useEmissiveAsIllumination = false;
  53190. /**
  53191. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53192. */
  53193. _this.useAlphaFromAlbedoTexture = false;
  53194. /**
  53195. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53196. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53197. */
  53198. _this.useSpecularOverAlpha = true;
  53199. /**
  53200. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53201. */
  53202. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53203. /**
  53204. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  53205. */
  53206. _this.useRoughnessFromMetallicTextureAlpha = true;
  53207. /**
  53208. * Specifies if the metallic texture contains the roughness information in its green channel.
  53209. */
  53210. _this.useRoughnessFromMetallicTextureGreen = false;
  53211. /**
  53212. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53213. * The material will try to infer what glossiness each pixel should be.
  53214. */
  53215. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  53216. /**
  53217. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53218. * the creation of the material.
  53219. */
  53220. _this.useScalarInLinearSpace = false;
  53221. /**
  53222. * BJS is using an harcoded light falloff based on a manually sets up range.
  53223. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53224. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53225. */
  53226. _this.usePhysicalLightFalloff = true;
  53227. /**
  53228. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53229. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53230. */
  53231. _this.useRadianceOverAlpha = true;
  53232. /**
  53233. * Allows using the bump map in parallax mode.
  53234. */
  53235. _this.useParallax = false;
  53236. /**
  53237. * Allows using the bump map in parallax occlusion mode.
  53238. */
  53239. _this.useParallaxOcclusion = false;
  53240. /**
  53241. * Controls the scale bias of the parallax mode.
  53242. */
  53243. _this.parallaxScaleBias = 0.05;
  53244. /**
  53245. * If sets to true, disables all the lights affecting the material.
  53246. */
  53247. _this.disableLighting = false;
  53248. /**
  53249. * Number of Simultaneous lights allowed on the material.
  53250. */
  53251. _this.maxSimultaneousLights = 4;
  53252. /**
  53253. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53254. */
  53255. _this.invertNormalMapX = false;
  53256. /**
  53257. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53258. */
  53259. _this.invertNormalMapY = false;
  53260. _this._renderTargets = new BABYLON.SmartArray(16);
  53261. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53262. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53263. _this._tempColor = new BABYLON.Color3();
  53264. _this._defines = new PBRMaterialDefines();
  53265. _this._cachedDefines = new PBRMaterialDefines();
  53266. _this._myScene = null;
  53267. _this._myShadowGenerator = null;
  53268. _this._cachedDefines.BonesPerMesh = -1;
  53269. _this.getRenderTargetTextures = function () {
  53270. _this._renderTargets.reset();
  53271. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53272. _this._renderTargets.push(_this.reflectionTexture);
  53273. }
  53274. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53275. _this._renderTargets.push(_this.refractionTexture);
  53276. }
  53277. return _this._renderTargets;
  53278. };
  53279. return _this;
  53280. }
  53281. PBRMaterial.prototype.getClassName = function () {
  53282. return "PBRMaterial";
  53283. };
  53284. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53285. get: function () {
  53286. return this._useLogarithmicDepth;
  53287. },
  53288. set: function (value) {
  53289. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53290. },
  53291. enumerable: true,
  53292. configurable: true
  53293. });
  53294. PBRMaterial.prototype.needAlphaBlending = function () {
  53295. if (this.linkRefractionWithTransparency) {
  53296. return false;
  53297. }
  53298. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53299. };
  53300. PBRMaterial.prototype.needAlphaTesting = function () {
  53301. if (this.linkRefractionWithTransparency) {
  53302. return false;
  53303. }
  53304. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53305. };
  53306. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53307. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53308. };
  53309. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53310. return this.albedoTexture;
  53311. };
  53312. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53313. if (!mesh) {
  53314. return true;
  53315. }
  53316. if (this._defines.INSTANCES !== useInstances) {
  53317. return false;
  53318. }
  53319. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53320. return true;
  53321. }
  53322. return false;
  53323. };
  53324. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53325. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53326. };
  53327. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53328. if (!useScalarInLinear) {
  53329. color.toLinearSpaceToRef(ref);
  53330. }
  53331. else {
  53332. ref.r = color.r;
  53333. ref.g = color.g;
  53334. ref.b = color.b;
  53335. }
  53336. };
  53337. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53338. var lightIndex = 0;
  53339. var depthValuesAlreadySet = false;
  53340. for (var index = 0; index < scene.lights.length; index++) {
  53341. var light = scene.lights[index];
  53342. if (!light.isEnabled()) {
  53343. continue;
  53344. }
  53345. if (!light.canAffectMesh(mesh)) {
  53346. continue;
  53347. }
  53348. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  53349. // GAMMA CORRECTION.
  53350. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  53351. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  53352. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  53353. if (defines["SPECULARTERM"]) {
  53354. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  53355. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  53356. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  53357. }
  53358. // Shadows
  53359. if (scene.shadowsEnabled) {
  53360. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  53361. }
  53362. lightIndex++;
  53363. if (lightIndex === maxSimultaneousLights)
  53364. break;
  53365. }
  53366. };
  53367. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  53368. if (this.isFrozen) {
  53369. if (this._wasPreviouslyReady) {
  53370. return true;
  53371. }
  53372. }
  53373. var scene = this.getScene();
  53374. var engine = scene.getEngine();
  53375. var needNormals = false;
  53376. var needUVs = false;
  53377. this._defines.reset();
  53378. if (scene.lightsEnabled && !this.disableLighting) {
  53379. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  53380. }
  53381. if (!this.checkReadyOnEveryCall) {
  53382. if (this._renderId === scene.getRenderId()) {
  53383. if (this._checkCache(scene, mesh, useInstances)) {
  53384. return true;
  53385. }
  53386. }
  53387. }
  53388. if (scene.texturesEnabled) {
  53389. if (scene.getEngine().getCaps().textureLOD) {
  53390. this._defines.LODBASEDMICROSFURACE = true;
  53391. }
  53392. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53393. if (!this.albedoTexture.isReady()) {
  53394. return false;
  53395. }
  53396. else {
  53397. needUVs = true;
  53398. this._defines.ALBEDO = true;
  53399. }
  53400. }
  53401. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53402. if (!this.ambientTexture.isReady()) {
  53403. return false;
  53404. }
  53405. else {
  53406. needUVs = true;
  53407. this._defines.AMBIENT = true;
  53408. }
  53409. }
  53410. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53411. if (!this.opacityTexture.isReady()) {
  53412. return false;
  53413. }
  53414. else {
  53415. needUVs = true;
  53416. this._defines.OPACITY = true;
  53417. if (this.opacityTexture.getAlphaFromRGB) {
  53418. this._defines.OPACITYRGB = true;
  53419. }
  53420. }
  53421. }
  53422. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53423. if (!this.reflectionTexture.isReady()) {
  53424. return false;
  53425. }
  53426. else {
  53427. needNormals = true;
  53428. this._defines.REFLECTION = true;
  53429. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  53430. this._defines.INVERTCUBICMAP = true;
  53431. }
  53432. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  53433. switch (this.reflectionTexture.coordinatesMode) {
  53434. case BABYLON.Texture.CUBIC_MODE:
  53435. case BABYLON.Texture.INVCUBIC_MODE:
  53436. this._defines.REFLECTIONMAP_CUBIC = true;
  53437. break;
  53438. case BABYLON.Texture.EXPLICIT_MODE:
  53439. this._defines.REFLECTIONMAP_EXPLICIT = true;
  53440. break;
  53441. case BABYLON.Texture.PLANAR_MODE:
  53442. this._defines.REFLECTIONMAP_PLANAR = true;
  53443. break;
  53444. case BABYLON.Texture.PROJECTION_MODE:
  53445. this._defines.REFLECTIONMAP_PROJECTION = true;
  53446. break;
  53447. case BABYLON.Texture.SKYBOX_MODE:
  53448. this._defines.REFLECTIONMAP_SKYBOX = true;
  53449. break;
  53450. case BABYLON.Texture.SPHERICAL_MODE:
  53451. this._defines.REFLECTIONMAP_SPHERICAL = true;
  53452. break;
  53453. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  53454. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  53455. break;
  53456. }
  53457. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  53458. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  53459. needNormals = true;
  53460. if (this.reflectionTexture.isPMREM) {
  53461. this._defines.USEPMREMREFLECTION = true;
  53462. }
  53463. }
  53464. }
  53465. }
  53466. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53467. if (!this.lightmapTexture.isReady()) {
  53468. return false;
  53469. }
  53470. else {
  53471. needUVs = true;
  53472. this._defines.LIGHTMAP = true;
  53473. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  53474. }
  53475. }
  53476. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53477. if (!this.emissiveTexture.isReady()) {
  53478. return false;
  53479. }
  53480. else {
  53481. needUVs = true;
  53482. this._defines.EMISSIVE = true;
  53483. }
  53484. }
  53485. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53486. if (this.metallicTexture) {
  53487. if (!this.metallicTexture.isReady()) {
  53488. return false;
  53489. }
  53490. else {
  53491. needUVs = true;
  53492. this._defines.METALLICWORKFLOW = true;
  53493. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  53494. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  53495. }
  53496. }
  53497. else if (this.reflectivityTexture) {
  53498. if (!this.reflectivityTexture.isReady()) {
  53499. return false;
  53500. }
  53501. else {
  53502. needUVs = true;
  53503. this._defines.REFLECTIVITY = true;
  53504. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  53505. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  53506. }
  53507. }
  53508. }
  53509. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53510. if (!this.bumpTexture.isReady()) {
  53511. return false;
  53512. }
  53513. else {
  53514. needUVs = true;
  53515. this._defines.BUMP = true;
  53516. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53517. this._defines.PARALLAX = true;
  53518. if (this.useParallaxOcclusion) {
  53519. this._defines.PARALLAXOCCLUSION = true;
  53520. }
  53521. }
  53522. if (this.invertNormalMapX) {
  53523. this._defines.INVERTNORMALMAPX = true;
  53524. }
  53525. if (this.invertNormalMapY) {
  53526. this._defines.INVERTNORMALMAPY = true;
  53527. }
  53528. }
  53529. }
  53530. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53531. if (!this.refractionTexture.isReady()) {
  53532. return false;
  53533. }
  53534. else {
  53535. needUVs = true;
  53536. this._defines.REFRACTION = true;
  53537. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  53538. if (this.linkRefractionWithTransparency) {
  53539. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  53540. }
  53541. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  53542. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  53543. if (this.refractionTexture.isPMREM) {
  53544. this._defines.USEPMREMREFRACTION = true;
  53545. }
  53546. }
  53547. }
  53548. }
  53549. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53550. if (!this.cameraColorGradingTexture.isReady()) {
  53551. return false;
  53552. }
  53553. else {
  53554. this._defines.CAMERACOLORGRADING = true;
  53555. }
  53556. }
  53557. }
  53558. // Effect
  53559. if (scene.clipPlane) {
  53560. this._defines.CLIPPLANE = true;
  53561. }
  53562. if (engine.getAlphaTesting()) {
  53563. this._defines.ALPHATEST = true;
  53564. }
  53565. if (this._shouldUseAlphaFromAlbedoTexture()) {
  53566. this._defines.ALPHAFROMALBEDO = true;
  53567. }
  53568. if (this.useEmissiveAsIllumination) {
  53569. this._defines.EMISSIVEASILLUMINATION = true;
  53570. }
  53571. if (this.linkEmissiveWithAlbedo) {
  53572. this._defines.LINKEMISSIVEWITHALBEDO = true;
  53573. }
  53574. if (this.useLogarithmicDepth) {
  53575. this._defines.LOGARITHMICDEPTH = true;
  53576. }
  53577. if (this.cameraContrast != 1) {
  53578. this._defines.CAMERACONTRAST = true;
  53579. }
  53580. if (this.cameraExposure != 1) {
  53581. this._defines.CAMERATONEMAP = true;
  53582. }
  53583. if (this.cameraColorCurves) {
  53584. this._defines.CAMERACOLORCURVES = true;
  53585. }
  53586. if (this.overloadedShadeIntensity != 1 ||
  53587. this.overloadedShadowIntensity != 1) {
  53588. this._defines.OVERLOADEDSHADOWVALUES = true;
  53589. }
  53590. if (this.overloadedMicroSurfaceIntensity > 0 ||
  53591. this.overloadedEmissiveIntensity > 0 ||
  53592. this.overloadedReflectivityIntensity > 0 ||
  53593. this.overloadedAlbedoIntensity > 0 ||
  53594. this.overloadedAmbientIntensity > 0 ||
  53595. this.overloadedReflectionIntensity > 0) {
  53596. this._defines.OVERLOADEDVALUES = true;
  53597. }
  53598. // Point size
  53599. if (this.pointsCloud || scene.forcePointsCloud) {
  53600. this._defines.POINTSIZE = true;
  53601. }
  53602. // Fog
  53603. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53604. this._defines.FOG = true;
  53605. }
  53606. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53607. // Fresnel
  53608. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  53609. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53610. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53611. this._defines.OPACITYFRESNEL = true;
  53612. }
  53613. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53614. this._defines.EMISSIVEFRESNEL = true;
  53615. }
  53616. needNormals = true;
  53617. this._defines.FRESNEL = true;
  53618. }
  53619. }
  53620. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  53621. this._defines.SPECULAROVERALPHA = true;
  53622. }
  53623. if (this.usePhysicalLightFalloff) {
  53624. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  53625. }
  53626. if (this.useRadianceOverAlpha) {
  53627. this._defines.RADIANCEOVERALPHA = true;
  53628. }
  53629. // Attribs
  53630. if (mesh) {
  53631. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53632. this._defines.NORMAL = true;
  53633. }
  53634. if (needUVs) {
  53635. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53636. this._defines.UV1 = true;
  53637. }
  53638. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53639. this._defines.UV2 = true;
  53640. }
  53641. }
  53642. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53643. this._defines.VERTEXCOLOR = true;
  53644. if (mesh.hasVertexAlpha) {
  53645. this._defines.VERTEXALPHA = true;
  53646. }
  53647. }
  53648. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53649. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  53650. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  53651. }
  53652. // Instances
  53653. if (useInstances) {
  53654. this._defines.INSTANCES = true;
  53655. }
  53656. }
  53657. // Get correct effect
  53658. if (!this._defines.isEqual(this._cachedDefines)) {
  53659. this._defines.cloneTo(this._cachedDefines);
  53660. scene.resetCachedMaterial();
  53661. // Fallbacks
  53662. var fallbacks = new BABYLON.EffectFallbacks();
  53663. if (this._defines.REFLECTION) {
  53664. fallbacks.addFallback(0, "REFLECTION");
  53665. }
  53666. if (this._defines.REFRACTION) {
  53667. fallbacks.addFallback(0, "REFRACTION");
  53668. }
  53669. if (this._defines.REFLECTIVITY) {
  53670. fallbacks.addFallback(0, "REFLECTIVITY");
  53671. }
  53672. if (this._defines.BUMP) {
  53673. fallbacks.addFallback(0, "BUMP");
  53674. }
  53675. if (this._defines.PARALLAX) {
  53676. fallbacks.addFallback(1, "PARALLAX");
  53677. }
  53678. if (this._defines.PARALLAXOCCLUSION) {
  53679. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  53680. }
  53681. if (this._defines.SPECULAROVERALPHA) {
  53682. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  53683. }
  53684. if (this._defines.FOG) {
  53685. fallbacks.addFallback(1, "FOG");
  53686. }
  53687. if (this._defines.POINTSIZE) {
  53688. fallbacks.addFallback(0, "POINTSIZE");
  53689. }
  53690. if (this._defines.LOGARITHMICDEPTH) {
  53691. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  53692. }
  53693. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  53694. if (this._defines.SPECULARTERM) {
  53695. fallbacks.addFallback(0, "SPECULARTERM");
  53696. }
  53697. if (this._defines.OPACITYFRESNEL) {
  53698. fallbacks.addFallback(1, "OPACITYFRESNEL");
  53699. }
  53700. if (this._defines.EMISSIVEFRESNEL) {
  53701. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  53702. }
  53703. if (this._defines.FRESNEL) {
  53704. fallbacks.addFallback(3, "FRESNEL");
  53705. }
  53706. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  53707. fallbacks.addCPUSkinningFallback(0, mesh);
  53708. }
  53709. //Attributes
  53710. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53711. if (this._defines.NORMAL) {
  53712. attribs.push(BABYLON.VertexBuffer.NormalKind);
  53713. }
  53714. if (this._defines.UV1) {
  53715. attribs.push(BABYLON.VertexBuffer.UVKind);
  53716. }
  53717. if (this._defines.UV2) {
  53718. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53719. }
  53720. if (this._defines.VERTEXCOLOR) {
  53721. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53722. }
  53723. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  53724. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  53725. // Legacy browser patch
  53726. var join = this._defines.toString();
  53727. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  53728. "vFogInfos", "vFogColor", "pointSize",
  53729. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  53730. "mBones",
  53731. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  53732. "depthValues",
  53733. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  53734. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  53735. "logarithmicDepthConstant",
  53736. "vSphericalX", "vSphericalY", "vSphericalZ",
  53737. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  53738. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  53739. "vMicrosurfaceTextureLods",
  53740. "vCameraInfos"
  53741. ];
  53742. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  53743. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  53744. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  53745. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  53746. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  53747. }
  53748. if (!this._effect.isReady()) {
  53749. return false;
  53750. }
  53751. this._renderId = scene.getRenderId();
  53752. this._wasPreviouslyReady = true;
  53753. if (mesh) {
  53754. if (!mesh._materialDefines) {
  53755. mesh._materialDefines = new PBRMaterialDefines();
  53756. }
  53757. this._defines.cloneTo(mesh._materialDefines);
  53758. }
  53759. return true;
  53760. };
  53761. PBRMaterial.prototype.unbind = function () {
  53762. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  53763. this._effect.setTexture("reflection2DSampler", null);
  53764. }
  53765. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  53766. this._effect.setTexture("refraction2DSampler", null);
  53767. }
  53768. _super.prototype.unbind.call(this);
  53769. };
  53770. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53771. this._effect.setMatrix("world", world);
  53772. };
  53773. PBRMaterial.prototype.bind = function (world, mesh) {
  53774. this._myScene = this.getScene();
  53775. // Matrices
  53776. this.bindOnlyWorldMatrix(world);
  53777. // Bones
  53778. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53779. if (this._myScene.getCachedMaterial() !== this) {
  53780. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  53781. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53782. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53783. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  53784. }
  53785. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53786. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  53787. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  53788. }
  53789. }
  53790. // Textures
  53791. if (this._myScene.texturesEnabled) {
  53792. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53793. this._effect.setTexture("albedoSampler", this.albedoTexture);
  53794. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  53795. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  53796. }
  53797. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53798. this._effect.setTexture("ambientSampler", this.ambientTexture);
  53799. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  53800. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  53801. }
  53802. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53803. this._effect.setTexture("opacitySampler", this.opacityTexture);
  53804. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  53805. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  53806. }
  53807. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53808. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  53809. if (this.reflectionTexture.isCube) {
  53810. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  53811. }
  53812. else {
  53813. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  53814. }
  53815. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  53816. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  53817. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  53818. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  53819. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  53820. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  53821. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  53822. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  53823. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  53824. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  53825. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  53826. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  53827. }
  53828. }
  53829. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53830. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  53831. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  53832. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  53833. }
  53834. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53835. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  53836. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  53837. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  53838. }
  53839. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53840. if (this.metallicTexture) {
  53841. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  53842. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  53843. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  53844. }
  53845. else if (this.reflectivityTexture) {
  53846. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  53847. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  53848. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  53849. }
  53850. }
  53851. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53852. this._effect.setTexture("bumpSampler", this.bumpTexture);
  53853. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  53854. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  53855. }
  53856. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53857. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  53858. var depth = 1.0;
  53859. if (this.refractionTexture.isCube) {
  53860. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  53861. }
  53862. else {
  53863. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  53864. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  53865. if (this.refractionTexture.depth) {
  53866. depth = this.refractionTexture.depth;
  53867. }
  53868. }
  53869. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  53870. }
  53871. if ((this.reflectionTexture || this.refractionTexture)) {
  53872. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  53873. }
  53874. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53875. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  53876. }
  53877. }
  53878. // Clip plane
  53879. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  53880. // Point size
  53881. if (this.pointsCloud) {
  53882. this._effect.setFloat("pointSize", this.pointSize);
  53883. }
  53884. // Colors
  53885. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  53886. // GAMMA CORRECTION.
  53887. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  53888. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  53889. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  53890. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  53891. // GAMMA CORRECTION.
  53892. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  53893. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  53894. // GAMMA CORRECTION.
  53895. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  53896. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  53897. }
  53898. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  53899. // GAMMA CORRECTION.
  53900. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  53901. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  53902. // Lights
  53903. if (this._myScene.lightsEnabled && !this.disableLighting) {
  53904. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  53905. }
  53906. // View
  53907. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  53908. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  53909. }
  53910. // Fog
  53911. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  53912. this._lightingInfos.x = this.directIntensity;
  53913. this._lightingInfos.y = this.emissiveIntensity;
  53914. this._lightingInfos.z = this.environmentIntensity;
  53915. this._lightingInfos.w = this.specularIntensity;
  53916. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  53917. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  53918. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  53919. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  53920. this._cameraInfos.x = this.cameraExposure;
  53921. this._cameraInfos.y = this.cameraContrast;
  53922. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  53923. if (this.cameraColorCurves) {
  53924. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  53925. }
  53926. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  53927. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  53928. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  53929. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  53930. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  53931. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  53932. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  53933. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  53934. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  53935. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  53936. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  53937. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  53938. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  53939. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  53940. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  53941. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  53942. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  53943. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  53944. // Log. depth
  53945. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  53946. }
  53947. _super.prototype.bind.call(this, world, mesh);
  53948. this._myScene = null;
  53949. };
  53950. PBRMaterial.prototype.getAnimatables = function () {
  53951. var results = [];
  53952. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  53953. results.push(this.albedoTexture);
  53954. }
  53955. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  53956. results.push(this.ambientTexture);
  53957. }
  53958. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  53959. results.push(this.opacityTexture);
  53960. }
  53961. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  53962. results.push(this.reflectionTexture);
  53963. }
  53964. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  53965. results.push(this.emissiveTexture);
  53966. }
  53967. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  53968. results.push(this.metallicTexture);
  53969. }
  53970. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  53971. results.push(this.reflectivityTexture);
  53972. }
  53973. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  53974. results.push(this.bumpTexture);
  53975. }
  53976. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  53977. results.push(this.lightmapTexture);
  53978. }
  53979. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  53980. results.push(this.refractionTexture);
  53981. }
  53982. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  53983. results.push(this.cameraColorGradingTexture);
  53984. }
  53985. return results;
  53986. };
  53987. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53988. if (forceDisposeTextures) {
  53989. if (this.albedoTexture) {
  53990. this.albedoTexture.dispose();
  53991. }
  53992. if (this.ambientTexture) {
  53993. this.ambientTexture.dispose();
  53994. }
  53995. if (this.opacityTexture) {
  53996. this.opacityTexture.dispose();
  53997. }
  53998. if (this.reflectionTexture) {
  53999. this.reflectionTexture.dispose();
  54000. }
  54001. if (this.emissiveTexture) {
  54002. this.emissiveTexture.dispose();
  54003. }
  54004. if (this.metallicTexture) {
  54005. this.metallicTexture.dispose();
  54006. }
  54007. if (this.reflectivityTexture) {
  54008. this.reflectivityTexture.dispose();
  54009. }
  54010. if (this.bumpTexture) {
  54011. this.bumpTexture.dispose();
  54012. }
  54013. if (this.lightmapTexture) {
  54014. this.lightmapTexture.dispose();
  54015. }
  54016. if (this.refractionTexture) {
  54017. this.refractionTexture.dispose();
  54018. }
  54019. if (this.cameraColorGradingTexture) {
  54020. this.cameraColorGradingTexture.dispose();
  54021. }
  54022. }
  54023. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54024. };
  54025. PBRMaterial.prototype.clone = function (name) {
  54026. var _this = this;
  54027. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  54028. };
  54029. PBRMaterial.prototype.serialize = function () {
  54030. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54031. serializationObject.customType = "BABYLON.PBRMaterial";
  54032. return serializationObject;
  54033. };
  54034. // Statics
  54035. PBRMaterial.Parse = function (source, scene, rootUrl) {
  54036. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  54037. };
  54038. return PBRMaterial;
  54039. }(BABYLON.Material));
  54040. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  54041. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  54042. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  54043. PBRMaterial._scaledReflection = new BABYLON.Color3();
  54044. __decorate([
  54045. BABYLON.serialize()
  54046. ], PBRMaterial.prototype, "directIntensity", void 0);
  54047. __decorate([
  54048. BABYLON.serialize()
  54049. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  54050. __decorate([
  54051. BABYLON.serialize()
  54052. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  54053. __decorate([
  54054. BABYLON.serialize()
  54055. ], PBRMaterial.prototype, "specularIntensity", void 0);
  54056. __decorate([
  54057. BABYLON.serialize()
  54058. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  54059. __decorate([
  54060. BABYLON.serialize()
  54061. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  54062. __decorate([
  54063. BABYLON.serialize()
  54064. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  54065. __decorate([
  54066. BABYLON.serialize()
  54067. ], PBRMaterial.prototype, "cameraExposure", void 0);
  54068. __decorate([
  54069. BABYLON.serialize()
  54070. ], PBRMaterial.prototype, "cameraContrast", void 0);
  54071. __decorate([
  54072. BABYLON.serializeAsTexture()
  54073. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  54074. __decorate([
  54075. BABYLON.serializeAsColorCurves()
  54076. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  54077. __decorate([
  54078. BABYLON.serializeAsColor3()
  54079. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  54080. __decorate([
  54081. BABYLON.serialize()
  54082. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  54083. __decorate([
  54084. BABYLON.serializeAsColor3()
  54085. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  54086. __decorate([
  54087. BABYLON.serialize()
  54088. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  54089. __decorate([
  54090. BABYLON.serializeAsColor3()
  54091. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  54092. __decorate([
  54093. BABYLON.serialize()
  54094. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  54095. __decorate([
  54096. BABYLON.serializeAsColor3()
  54097. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  54098. __decorate([
  54099. BABYLON.serialize()
  54100. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  54101. __decorate([
  54102. BABYLON.serializeAsColor3()
  54103. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  54104. __decorate([
  54105. BABYLON.serialize()
  54106. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  54107. __decorate([
  54108. BABYLON.serialize()
  54109. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  54110. __decorate([
  54111. BABYLON.serialize()
  54112. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  54113. __decorate([
  54114. BABYLON.serializeAsTexture()
  54115. ], PBRMaterial.prototype, "albedoTexture", void 0);
  54116. __decorate([
  54117. BABYLON.serializeAsTexture()
  54118. ], PBRMaterial.prototype, "ambientTexture", void 0);
  54119. __decorate([
  54120. BABYLON.serialize()
  54121. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  54122. __decorate([
  54123. BABYLON.serializeAsTexture()
  54124. ], PBRMaterial.prototype, "opacityTexture", void 0);
  54125. __decorate([
  54126. BABYLON.serializeAsTexture()
  54127. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  54128. __decorate([
  54129. BABYLON.serializeAsTexture()
  54130. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  54131. __decorate([
  54132. BABYLON.serializeAsTexture()
  54133. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  54134. __decorate([
  54135. BABYLON.serializeAsTexture()
  54136. ], PBRMaterial.prototype, "metallicTexture", void 0);
  54137. __decorate([
  54138. BABYLON.serializeAsTexture()
  54139. ], PBRMaterial.prototype, "bumpTexture", void 0);
  54140. __decorate([
  54141. BABYLON.serializeAsTexture()
  54142. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  54143. __decorate([
  54144. BABYLON.serializeAsTexture()
  54145. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54146. __decorate([
  54147. BABYLON.serializeAsColor3("ambient")
  54148. ], PBRMaterial.prototype, "ambientColor", void 0);
  54149. __decorate([
  54150. BABYLON.serializeAsColor3("albedo")
  54151. ], PBRMaterial.prototype, "albedoColor", void 0);
  54152. __decorate([
  54153. BABYLON.serializeAsColor3("reflectivity")
  54154. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54155. __decorate([
  54156. BABYLON.serializeAsColor3("reflection")
  54157. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54158. __decorate([
  54159. BABYLON.serializeAsColor3("emissive")
  54160. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54161. __decorate([
  54162. BABYLON.serialize()
  54163. ], PBRMaterial.prototype, "microSurface", void 0);
  54164. __decorate([
  54165. BABYLON.serialize()
  54166. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54167. __decorate([
  54168. BABYLON.serialize()
  54169. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54170. __decorate([
  54171. BABYLON.serializeAsFresnelParameters()
  54172. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54173. __decorate([
  54174. BABYLON.serializeAsFresnelParameters()
  54175. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54176. __decorate([
  54177. BABYLON.serialize()
  54178. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54179. __decorate([
  54180. BABYLON.serialize()
  54181. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54182. __decorate([
  54183. BABYLON.serialize()
  54184. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54185. __decorate([
  54186. BABYLON.serialize()
  54187. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54188. __decorate([
  54189. BABYLON.serialize()
  54190. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54191. __decorate([
  54192. BABYLON.serialize()
  54193. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54194. __decorate([
  54195. BABYLON.serialize()
  54196. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54197. __decorate([
  54198. BABYLON.serialize()
  54199. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  54200. __decorate([
  54201. BABYLON.serialize()
  54202. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  54203. __decorate([
  54204. BABYLON.serialize()
  54205. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54206. __decorate([
  54207. BABYLON.serialize()
  54208. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54209. __decorate([
  54210. BABYLON.serialize()
  54211. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54212. __decorate([
  54213. BABYLON.serialize()
  54214. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54215. __decorate([
  54216. BABYLON.serialize()
  54217. ], PBRMaterial.prototype, "useParallax", void 0);
  54218. __decorate([
  54219. BABYLON.serialize()
  54220. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54221. __decorate([
  54222. BABYLON.serialize()
  54223. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54224. __decorate([
  54225. BABYLON.serialize()
  54226. ], PBRMaterial.prototype, "disableLighting", void 0);
  54227. __decorate([
  54228. BABYLON.serialize()
  54229. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54230. __decorate([
  54231. BABYLON.serialize()
  54232. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54233. __decorate([
  54234. BABYLON.serialize()
  54235. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54236. __decorate([
  54237. BABYLON.serialize()
  54238. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54239. BABYLON.PBRMaterial = PBRMaterial;
  54240. })(BABYLON || (BABYLON = {}));
  54241. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54242. var BABYLON;
  54243. (function (BABYLON) {
  54244. var DebugLayer = (function () {
  54245. function DebugLayer(scene) {
  54246. this._scene = scene;
  54247. }
  54248. /** Creates the inspector window. */
  54249. DebugLayer.prototype._createInspector = function (popup) {
  54250. if (!this._inspector) {
  54251. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  54252. } // else nothing to do,; instance is already existing
  54253. };
  54254. DebugLayer.prototype.isVisible = function () {
  54255. return false;
  54256. };
  54257. DebugLayer.prototype.hide = function () {
  54258. if (this._inspector) {
  54259. this._inspector.dispose();
  54260. this._inspector = null;
  54261. }
  54262. };
  54263. DebugLayer.prototype.show = function (popup) {
  54264. if (typeof INSPECTOR == 'undefined') {
  54265. // Load inspector and add it to the DOM
  54266. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  54267. }
  54268. else {
  54269. // Otherwise creates the inspector
  54270. this._createInspector(popup);
  54271. }
  54272. };
  54273. return DebugLayer;
  54274. }());
  54275. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54276. BABYLON.DebugLayer = DebugLayer;
  54277. })(BABYLON || (BABYLON = {}));
  54278. //# sourceMappingURL=babylon.debugLayer.js.map
  54279. var BABYLON;
  54280. (function (BABYLON) {
  54281. var StandardRenderingPipeline = (function (_super) {
  54282. __extends(StandardRenderingPipeline, _super);
  54283. /**
  54284. * @constructor
  54285. * @param {string} name - The rendering pipeline name
  54286. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54287. * @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)
  54288. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54289. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54290. */
  54291. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54292. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54293. var _this = _super.call(this, scene.getEngine(), name) || this;
  54294. _this.downSampleX4PostProcess = null;
  54295. _this.brightPassPostProcess = null;
  54296. _this.gaussianBlurHPostProcesses = [];
  54297. _this.gaussianBlurVPostProcesses = [];
  54298. _this.textureAdderPostProcess = null;
  54299. _this.textureAdderFinalPostProcess = null;
  54300. _this.lensFlarePostProcess = null;
  54301. _this.lensFlareComposePostProcess = null;
  54302. _this.depthOfFieldPostProcess = null;
  54303. // Values
  54304. _this.brightThreshold = 1.0;
  54305. _this.blurWidth = 2.0;
  54306. _this.gaussianCoefficient = 0.25;
  54307. _this.gaussianMean = 1.0;
  54308. _this.gaussianStandardDeviation = 1.0;
  54309. _this.exposure = 1.0;
  54310. _this.lensTexture = null;
  54311. _this.lensColorTexture = null;
  54312. _this.lensFlareStrength = 20.0;
  54313. _this.lensFlareGhostDispersal = 1.4;
  54314. _this.lensFlareHaloWidth = 0.7;
  54315. _this.lensFlareDistortionStrength = 16.0;
  54316. _this.lensStarTexture = null;
  54317. _this.lensFlareDirtTexture = null;
  54318. _this.depthOfFieldDistance = 10.0;
  54319. // IAnimatable
  54320. _this.animations = [];
  54321. _this._depthRenderer = null;
  54322. // Getters and setters
  54323. _this._depthOfFieldEnabled = true;
  54324. _this._lensFlareEnabled = true;
  54325. // Initialize
  54326. _this._scene = scene;
  54327. // Create pass post-processe
  54328. if (!originalPostProcess) {
  54329. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  54330. }
  54331. else {
  54332. _this.originalPostProcess = originalPostProcess;
  54333. }
  54334. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54335. // Create down sample X4 post-process
  54336. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  54337. // Create bright pass post-process
  54338. _this._createBrightPassPostProcess(scene, ratio / 2);
  54339. // Create gaussian blur post-processes (down sampling blurs)
  54340. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  54341. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  54342. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  54343. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  54344. // Create texture adder post-process
  54345. _this._createTextureAdderPostProcess(scene, ratio);
  54346. // Create depth-of-field source post-process
  54347. _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);
  54348. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54349. // Create lens flare post-process
  54350. _this._createLensFlarePostProcess(scene, ratio);
  54351. // Create gaussian blur used by depth-of-field
  54352. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  54353. // Create depth-of-field post-process
  54354. _this._createDepthOfFieldPostProcess(scene, ratio);
  54355. // Finish
  54356. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54357. if (cameras !== null) {
  54358. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54359. }
  54360. // Deactivate
  54361. _this.LensFlareEnabled = false;
  54362. _this.DepthOfFieldEnabled = false;
  54363. return _this;
  54364. }
  54365. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54366. get: function () {
  54367. return this._depthOfFieldEnabled;
  54368. },
  54369. set: function (enabled) {
  54370. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  54371. if (enabled && !this._depthOfFieldEnabled) {
  54372. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54373. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54374. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54375. this._depthRenderer = this._scene.enableDepthRenderer();
  54376. }
  54377. else if (!enabled && this._depthOfFieldEnabled) {
  54378. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54379. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54380. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54381. }
  54382. this._depthOfFieldEnabled = enabled;
  54383. },
  54384. enumerable: true,
  54385. configurable: true
  54386. });
  54387. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54388. get: function () {
  54389. return this._lensFlareEnabled;
  54390. },
  54391. set: function (enabled) {
  54392. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  54393. if (enabled && !this._lensFlareEnabled) {
  54394. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54395. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54396. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54397. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54398. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54399. }
  54400. else if (!enabled && this._lensFlareEnabled) {
  54401. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54402. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54403. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54404. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54405. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54406. }
  54407. this._lensFlareEnabled = enabled;
  54408. },
  54409. enumerable: true,
  54410. configurable: true
  54411. });
  54412. // Down Sample X4 Post-Processs
  54413. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54414. var _this = this;
  54415. var downSampleX4Offsets = new Array(32);
  54416. 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);
  54417. this.downSampleX4PostProcess.onApply = function (effect) {
  54418. var id = 0;
  54419. for (var i = -2; i < 2; i++) {
  54420. for (var j = -2; j < 2; j++) {
  54421. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54422. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54423. id += 2;
  54424. }
  54425. }
  54426. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54427. };
  54428. // Add to pipeline
  54429. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54430. };
  54431. // Brightpass Post-Process
  54432. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54433. var _this = this;
  54434. var brightOffsets = new Array(8);
  54435. 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);
  54436. this.brightPassPostProcess.onApply = function (effect) {
  54437. var sU = (1.0 / _this.brightPassPostProcess.width);
  54438. var sV = (1.0 / _this.brightPassPostProcess.height);
  54439. brightOffsets[0] = -0.5 * sU;
  54440. brightOffsets[1] = 0.5 * sV;
  54441. brightOffsets[2] = 0.5 * sU;
  54442. brightOffsets[3] = 0.5 * sV;
  54443. brightOffsets[4] = -0.5 * sU;
  54444. brightOffsets[5] = -0.5 * sV;
  54445. brightOffsets[6] = 0.5 * sU;
  54446. brightOffsets[7] = -0.5 * sV;
  54447. effect.setArray2("dsOffsets", brightOffsets);
  54448. effect.setFloat("brightThreshold", _this.brightThreshold);
  54449. };
  54450. // Add to pipeline
  54451. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54452. };
  54453. // Create gaussian blur H&V post-processes
  54454. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  54455. var _this = this;
  54456. var blurOffsets = new Array(9);
  54457. var blurWeights = new Array(9);
  54458. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  54459. var callback = function (height) {
  54460. return function (effect) {
  54461. // Weights
  54462. var x = 0.0;
  54463. for (var i = 0; i < 9; i++) {
  54464. x = (i - 4.0) / 4.0;
  54465. blurWeights[i] =
  54466. _this.gaussianCoefficient
  54467. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  54468. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  54469. }
  54470. var lastOutputDimensions = {
  54471. width: scene.getEngine().getRenderWidth(),
  54472. height: scene.getEngine().getRenderHeight()
  54473. };
  54474. for (var i = 0; i < 9; i++) {
  54475. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54476. blurOffsets[i] = value;
  54477. }
  54478. effect.setArray("blurOffsets", blurOffsets);
  54479. effect.setArray("blurWeights", blurWeights);
  54480. effect.setFloat("blurWidth", _this.blurWidth);
  54481. };
  54482. };
  54483. // Create horizontal gaussian blur post-processes
  54484. 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);
  54485. gaussianBlurHPostProcess.onApply = callback(false);
  54486. // Create vertical gaussian blur post-process
  54487. 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);
  54488. gaussianBlurVPostProcess.onApply = callback(true);
  54489. // Add to pipeline
  54490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  54491. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  54492. // Finish
  54493. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  54494. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  54495. };
  54496. // Create texture adder post-process
  54497. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54498. var _this = this;
  54499. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  54500. 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);
  54501. this.textureAdderPostProcess.onApply = function (effect) {
  54502. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  54503. effect.setTexture("lensSampler", _this.lensTexture);
  54504. effect.setFloat("exposure", _this.exposure);
  54505. };
  54506. // Add to pipeline
  54507. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54508. };
  54509. // Create lens flare post-process
  54510. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54511. var _this = this;
  54512. 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);
  54513. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  54514. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  54515. 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);
  54516. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  54517. var resolution = new BABYLON.Vector2(0, 0);
  54518. // Lens flare
  54519. this.lensFlarePostProcess.onApply = function (effect) {
  54520. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  54521. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54522. effect.setFloat("strength", _this.lensFlareStrength);
  54523. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54524. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54525. // Shift
  54526. resolution.x = _this.lensFlarePostProcess.width;
  54527. resolution.y = _this.lensFlarePostProcess.height;
  54528. effect.setVector2("resolution", resolution);
  54529. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54530. };
  54531. // Compose
  54532. 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);
  54533. 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);
  54534. this.lensFlareComposePostProcess.onApply = function (effect) {
  54535. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54536. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54537. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54538. // Lens start rotation matrix
  54539. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54540. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54541. 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));
  54542. camRot *= 4.0;
  54543. 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);
  54544. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54545. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54546. };
  54547. };
  54548. // Create depth-of-field post-process
  54549. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54550. var _this = this;
  54551. 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);
  54552. this.depthOfFieldPostProcess.onApply = function (effect) {
  54553. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54554. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  54555. effect.setFloat("distance", _this.depthOfFieldDistance);
  54556. };
  54557. // Add to pipeline
  54558. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54559. };
  54560. // Dispose
  54561. StandardRenderingPipeline.prototype.dispose = function () {
  54562. for (var i = 0; i < this._scene.cameras.length; i++) {
  54563. var camera = this._scene.cameras[i];
  54564. this.originalPostProcess.dispose(camera);
  54565. this.downSampleX4PostProcess.dispose(camera);
  54566. this.brightPassPostProcess.dispose(camera);
  54567. this.textureAdderPostProcess.dispose(camera);
  54568. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  54569. this.gaussianBlurHPostProcesses[j].dispose(camera);
  54570. }
  54571. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  54572. this.gaussianBlurVPostProcesses[j].dispose(camera);
  54573. }
  54574. this.textureAdderFinalPostProcess.dispose(camera);
  54575. this.lensFlarePostProcess.dispose(camera);
  54576. this.lensFlareComposePostProcess.dispose(camera);
  54577. this.depthOfFieldPostProcess.dispose(camera);
  54578. }
  54579. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54580. _super.prototype.dispose.call(this);
  54581. };
  54582. return StandardRenderingPipeline;
  54583. }(BABYLON.PostProcessRenderPipeline));
  54584. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54585. })(BABYLON || (BABYLON = {}));
  54586. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54587. 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}"};
  54588. 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"};
  54589. 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=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t}();t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);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,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r((-1),0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,(-(t.y/o*2-1)),t.z),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=f.X,m=f.Y,y=0,c=0,p=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=A.Vector3[0],R=0,T=A.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(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),p=Math.acos(R)*v,r.Dot(T,u)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),d++);var _=A.Vector3[2],M=A.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(),r.CrossToRef(_,T,M),M.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(M,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.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=p},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z),(-this.w))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.substract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return 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,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,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 r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},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 r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},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,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o=t.Identity();return t.SlerpToRef(i,r,n,o),o},t.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},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],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},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 r=new t;return this.addToRef(i,r),r},t.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];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],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+r*_+n*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]=-(r*z-n*w+o*v)*b,t.m[5]=(i*z-n*d+o*g)*b,t.m[9]=-(i*w-r*d+o*R)*b,t.m[13]=(i*v-r*g+n*R)*b,t.m[2]=(r*F-n*L+o*C)*b,t.m[6]=-(i*F-n*P+o*Z)*b,t.m[10]=(i*L-r*P+o*S)*b,t.m[14]=-(i*C-r*Z+n*S)*b,t.m[3]=-(r*I-n*H+o*q)*b,t.m[7]=(i*I-n*D+o*V)*b,t.m[11]=-(i*H-r*D+o*N)*b,t.m[15]=(i*q-r*V+n*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 r=new t;return this.multiplyToRef(i,r),r},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 r=0;r<16;r++)t[i+r]=this.m[r];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],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[r]=n*v+o*T+e*b+s*P,i[r+1]=n*d+o*_+e*F+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*b+m*P,i[r+5]=h*d+a*_+u*F+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*b+f*P,i[r+9]=y*d+c*_+p*F+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*b+w*P,i[r+13]=x*d+l*_+z*F+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},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(r,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return r.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),r.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),r.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===r.x||0===r.y||0===r.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(t.FromValuesToRef(this.m[0]/r.x,this.m[1]/r.x,this.m[2]/r.x,0,this.m[4]/r.y,this.m[5]/r.y,this.m[6]/r.y,0,this.m[8]/r.z,this.m[9]/r.z,this.m[10]/r.z,0,0,0,0,1,A.Matrix[0]),a.FromRotationMatrixToRef(A.Matrix[0],n),!0)},t.prototype.getRotationMatrix=function(){var i=t.Identity();return this.getRotationMatrixToRef(i),i},t.prototype.getRotationMatrixToRef=function(i){var r=this.m,n=r[0]*r[1]*r[2]*r[3]<0?-1:1,o=r[4]*r[5]*r[6]*r[7]<0?-1:1,e=r[8]*r[9]*r[10]*r[11]<0?-1:1,s=n*Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]),h=o*Math.sqrt(r[4]*r[4]+r[5]*r[5]+r[6]*r[6]),a=e*Math.sqrt(r[8]*r[8]+r[9]*r[9]+r[10]*r[10]);t.FromValuesToRef(r[0]/s,r[1]/s,r[2]/s,0,r[4]/h,r[5]/h,r[6]/h,0,r[8]/a,r[9]/a,r[10]/a,0,0,0,0,1,i)},t.FromArray=function(i,r){var n=new t;return r||(r=0),t.FromArrayToRef(i,r,n),n},t.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},t.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},t.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},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 r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},t.FromValues=function(i,r,n,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]=r,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},t.Compose=function(i,r,n){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 r.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),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 r=new t;return t.RotationXToRef(i,r),r},t.Invert=function(i){var r=new t;return i.invertToRef(r),r},t.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var r=new t;return t.RotationYToRef(i,r),r},t.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var r=new t;return t.RotationZToRef(i,r),r},t.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,r){var n=t.Zero();return t.RotationAxisToRef(i,r,n),n},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},t.Scaling=function(i,r,n){var o=t.Zero();return t.ScalingToRef(i,r,n,o),o},t.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},t.Translation=function(i,r,n){var o=t.Identity();return t.TranslationToRef(i,r,n,o),o},t.TranslationToRef=function(i,r,n,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,r,n,1,o)},t.Lerp=function(i,r,n){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-n)+r.m[e]*n;return o},t.DecomposeLerp=function(i,r,n){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);r.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return t.Compose(c,p,f)},t.LookAtLH=function(i,r,n){var o=t.Zero();return t.LookAtLHToRef(i,r,n,o),o},t.LookAtLHToRef=function(i,r,n,o){r.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,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,r,n){var o=t.Zero();return t.LookAtRHToRef(i,r,n,o),o},t.LookAtRHToRef=function(i,r,n,o){i.subtractToRef(r,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,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,r,n,o){var e=t.Zero();return t.OrthoLHToRef(i,r,n,o,e),e},t.OrthoLHToRef=function(i,r,n,o,e){var s=2/i,h=2/r,a=1/(o-n),u=n/(n-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,r,n,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(n-r),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]=(n+r)/(r-n),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,r,n,o,e,s,h){t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,r,n,o){var e=t.Zero();return e.m[0]=2*n/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*n/r,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(n-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]=n*o/(n-o),e},t.PerspectiveFovLH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,r,n,o,e),e},t.PerspectiveFovLHToRef=function(t,i,r,n,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]=n/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(r*n)/(n-r)},t.PerspectiveFovRH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,r,n,o,e),e},t.PerspectiveFovRHToRef=function(t,i,r,n,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]=n/(r-n),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n)},t.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-r/(i-r),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=i*r/(i-r)},t.GetFinalMatrix=function(i,r,n,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 r.multiply(n).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 r=new t;return r.m[0]=i.m[0],r.m[1]=i.m[4],r.m[2]=i.m[8],r.m[3]=i.m[12],r.m[4]=i.m[1],r.m[5]=i.m[5],r.m[6]=i.m[9],r.m[7]=i.m[13],r.m[8]=i.m[2],r.m[9]=i.m[6],r.m[10]=i.m[10],r.m[11]=i.m[14],r.m[12]=i.m[3],r.m[13]=i.m[7],r.m[14]=i.m[11],r.m[15]=i.m[15],r},t.Reflection=function(i){var r=new t;return t.ReflectionToRef(i,r),r},t.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},t.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},t}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var M=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=M;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[new a(0,0,0,0)],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A}(BABYLON||(BABYLON={}));";
  54590. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54591. module.exports = BABYLON;
  54592. };