babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. }());
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. }());
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. }());
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.Forward = function () {
  834. return new Vector3(0, 0, 1.0);
  835. };
  836. Vector3.Right = function () {
  837. return new Vector3(1.0, 0, 0);
  838. };
  839. Vector3.Left = function () {
  840. return new Vector3(-1.0, 0, 0);
  841. };
  842. Vector3.TransformCoordinates = function (vector, transformation) {
  843. var result = Vector3.Zero();
  844. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  845. return result;
  846. };
  847. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  848. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  849. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  850. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  851. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  852. result.x = x / w;
  853. result.y = y / w;
  854. result.z = z / w;
  855. };
  856. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  857. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  858. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  859. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  860. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  861. result.x = rx / rw;
  862. result.y = ry / rw;
  863. result.z = rz / rw;
  864. };
  865. Vector3.TransformNormal = function (vector, transformation) {
  866. var result = Vector3.Zero();
  867. Vector3.TransformNormalToRef(vector, transformation, result);
  868. return result;
  869. };
  870. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  871. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  872. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  873. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  874. result.x = x;
  875. result.y = y;
  876. result.z = z;
  877. };
  878. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  879. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  880. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  881. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  882. };
  883. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  884. var squared = amount * amount;
  885. var cubed = amount * squared;
  886. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  887. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  888. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  889. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  890. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  891. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  892. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  893. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  894. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Clamp = function (value, min, max) {
  898. var x = value.x;
  899. x = (x > max.x) ? max.x : x;
  900. x = (x < min.x) ? min.x : x;
  901. var y = value.y;
  902. y = (y > max.y) ? max.y : y;
  903. y = (y < min.y) ? min.y : y;
  904. var z = value.z;
  905. z = (z > max.z) ? max.z : z;
  906. z = (z < min.z) ? min.z : z;
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  910. var squared = amount * amount;
  911. var cubed = amount * squared;
  912. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  913. var part2 = (-2.0 * cubed) + (3.0 * squared);
  914. var part3 = (cubed - (2.0 * squared)) + amount;
  915. var part4 = cubed - squared;
  916. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  917. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  918. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  919. return new Vector3(x, y, z);
  920. };
  921. Vector3.Lerp = function (start, end, amount) {
  922. var x = start.x + ((end.x - start.x) * amount);
  923. var y = start.y + ((end.y - start.y) * amount);
  924. var z = start.z + ((end.z - start.z) * amount);
  925. return new Vector3(x, y, z);
  926. };
  927. Vector3.Dot = function (left, right) {
  928. return (left.x * right.x + left.y * right.y + left.z * right.z);
  929. };
  930. Vector3.Cross = function (left, right) {
  931. var result = Vector3.Zero();
  932. Vector3.CrossToRef(left, right, result);
  933. return result;
  934. };
  935. Vector3.CrossToRef = function (left, right, result) {
  936. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  937. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  938. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  939. result.copyFrom(Tmp.Vector3[0]);
  940. };
  941. Vector3.Normalize = function (vector) {
  942. var result = Vector3.Zero();
  943. Vector3.NormalizeToRef(vector, result);
  944. return result;
  945. };
  946. Vector3.NormalizeToRef = function (vector, result) {
  947. result.copyFrom(vector);
  948. result.normalize();
  949. };
  950. Vector3.Project = function (vector, world, transform, viewport) {
  951. var cw = viewport.width;
  952. var ch = viewport.height;
  953. var cx = viewport.x;
  954. var cy = viewport.y;
  955. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  956. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  957. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  958. world.multiplyToRef(transform, matrix);
  959. matrix.multiplyToRef(viewportMatrix, matrix);
  960. return Vector3.TransformCoordinates(vector, matrix);
  961. };
  962. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  963. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  964. world.multiplyToRef(transform, matrix);
  965. matrix.invert();
  966. source.x = source.x / viewportWidth * 2 - 1;
  967. source.y = -(source.y / viewportHeight * 2 - 1);
  968. var vector = Vector3.TransformCoordinates(source, matrix);
  969. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  970. if (MathTools.WithinEpsilon(num, 1.0)) {
  971. vector = vector.scale(1.0 / num);
  972. }
  973. return vector;
  974. };
  975. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  976. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  977. world.multiplyToRef(view, matrix);
  978. matrix.multiplyToRef(projection, matrix);
  979. matrix.invert();
  980. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  981. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  982. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  983. if (MathTools.WithinEpsilon(num, 1.0)) {
  984. vector = vector.scale(1.0 / num);
  985. }
  986. return vector;
  987. };
  988. Vector3.Minimize = function (left, right) {
  989. var min = left.clone();
  990. min.MinimizeInPlace(right);
  991. return min;
  992. };
  993. Vector3.Maximize = function (left, right) {
  994. var max = left.clone();
  995. max.MaximizeInPlace(right);
  996. return max;
  997. };
  998. Vector3.Distance = function (value1, value2) {
  999. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1000. };
  1001. Vector3.DistanceSquared = function (value1, value2) {
  1002. var x = value1.x - value2.x;
  1003. var y = value1.y - value2.y;
  1004. var z = value1.z - value2.z;
  1005. return (x * x) + (y * y) + (z * z);
  1006. };
  1007. Vector3.Center = function (value1, value2) {
  1008. var center = value1.add(value2);
  1009. center.scaleInPlace(0.5);
  1010. return center;
  1011. };
  1012. /**
  1013. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1014. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1015. * to something in order to rotate it from its local system to the given target system.
  1016. */
  1017. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1018. var rotation = Vector3.Zero();
  1019. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1020. return rotation;
  1021. };
  1022. /**
  1023. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1024. */
  1025. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1026. var u = axis1.normalize();
  1027. var w = axis3.normalize();
  1028. // world axis
  1029. var X = Axis.X;
  1030. var Y = Axis.Y;
  1031. // equation unknowns and vars
  1032. var yaw = 0.0;
  1033. var pitch = 0.0;
  1034. var roll = 0.0;
  1035. var x = 0.0;
  1036. var y = 0.0;
  1037. var z = 0.0;
  1038. var t = 0.0;
  1039. var sign = -1.0;
  1040. var nbRevert = 0;
  1041. var cross = Tmp.Vector3[0];
  1042. var dot = 0.0;
  1043. // step 1 : rotation around w
  1044. // Rv3(u) = u1, and u1 belongs to plane xOz
  1045. // Rv3(w) = w1 = w invariant
  1046. var u1 = Tmp.Vector3[1];
  1047. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1048. z = 1.0;
  1049. }
  1050. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1051. x = 1.0;
  1052. }
  1053. else {
  1054. t = w.z / w.x;
  1055. x = -t * Math.sqrt(1 / (1 + t * t));
  1056. z = Math.sqrt(1 / (1 + t * t));
  1057. }
  1058. u1.x = x;
  1059. u1.y = y;
  1060. u1.z = z;
  1061. u1.normalize();
  1062. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1063. cross.normalize();
  1064. if (Vector3.Dot(w, cross) < 0) {
  1065. sign = 1.0;
  1066. }
  1067. dot = Vector3.Dot(u, u1);
  1068. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1069. roll = Math.acos(dot) * sign;
  1070. if (Vector3.Dot(u1, X) < 0) {
  1071. roll = Math.PI + roll;
  1072. u1 = u1.scaleInPlace(-1);
  1073. nbRevert++;
  1074. }
  1075. // step 2 : rotate around u1
  1076. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1077. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1078. var w2 = Tmp.Vector3[2];
  1079. var v2 = Tmp.Vector3[3];
  1080. x = 0.0;
  1081. y = 0.0;
  1082. z = 0.0;
  1083. sign = -1.0;
  1084. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1085. x = 1.0;
  1086. }
  1087. else {
  1088. t = u1.z / u1.x;
  1089. x = -t * Math.sqrt(1 / (1 + t * t));
  1090. z = Math.sqrt(1 / (1 + t * t));
  1091. }
  1092. w2.x = x;
  1093. w2.y = y;
  1094. w2.z = z;
  1095. w2.normalize();
  1096. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1097. v2.normalize();
  1098. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1099. cross.normalize();
  1100. if (Vector3.Dot(u1, cross) < 0) {
  1101. sign = 1.0;
  1102. }
  1103. dot = Vector3.Dot(w, w2);
  1104. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1105. pitch = Math.acos(dot) * sign;
  1106. if (Vector3.Dot(v2, Y) < 0) {
  1107. pitch = Math.PI + pitch;
  1108. nbRevert++;
  1109. }
  1110. // step 3 : rotate around v2
  1111. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1112. sign = -1.0;
  1113. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1114. cross.normalize();
  1115. if (Vector3.Dot(cross, Y) < 0) {
  1116. sign = 1.0;
  1117. }
  1118. dot = Vector3.Dot(u1, X);
  1119. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1120. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1121. if (dot < 0 && nbRevert < 2) {
  1122. yaw = Math.PI + yaw;
  1123. }
  1124. ref.x = pitch;
  1125. ref.y = yaw;
  1126. ref.z = roll;
  1127. };
  1128. return Vector3;
  1129. }());
  1130. BABYLON.Vector3 = Vector3;
  1131. //Vector4 class created for EulerAngle class conversion to Quaternion
  1132. var Vector4 = (function () {
  1133. function Vector4(x, y, z, w) {
  1134. this.x = x;
  1135. this.y = y;
  1136. this.z = z;
  1137. this.w = w;
  1138. }
  1139. Vector4.prototype.toString = function () {
  1140. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1141. };
  1142. Vector4.prototype.getClassName = function () {
  1143. return "Vector4";
  1144. };
  1145. Vector4.prototype.getHashCode = function () {
  1146. var hash = this.x || 0;
  1147. hash = (hash * 397) ^ (this.y || 0);
  1148. hash = (hash * 397) ^ (this.z || 0);
  1149. hash = (hash * 397) ^ (this.w || 0);
  1150. return hash;
  1151. };
  1152. // Operators
  1153. Vector4.prototype.asArray = function () {
  1154. var result = [];
  1155. this.toArray(result, 0);
  1156. return result;
  1157. };
  1158. Vector4.prototype.toArray = function (array, index) {
  1159. if (index === undefined) {
  1160. index = 0;
  1161. }
  1162. array[index] = this.x;
  1163. array[index + 1] = this.y;
  1164. array[index + 2] = this.z;
  1165. array[index + 3] = this.w;
  1166. return this;
  1167. };
  1168. Vector4.prototype.addInPlace = function (otherVector) {
  1169. this.x += otherVector.x;
  1170. this.y += otherVector.y;
  1171. this.z += otherVector.z;
  1172. this.w += otherVector.w;
  1173. return this;
  1174. };
  1175. Vector4.prototype.add = function (otherVector) {
  1176. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1177. };
  1178. Vector4.prototype.addToRef = function (otherVector, result) {
  1179. result.x = this.x + otherVector.x;
  1180. result.y = this.y + otherVector.y;
  1181. result.z = this.z + otherVector.z;
  1182. result.w = this.w + otherVector.w;
  1183. return this;
  1184. };
  1185. Vector4.prototype.subtractInPlace = function (otherVector) {
  1186. this.x -= otherVector.x;
  1187. this.y -= otherVector.y;
  1188. this.z -= otherVector.z;
  1189. this.w -= otherVector.w;
  1190. return this;
  1191. };
  1192. Vector4.prototype.subtract = function (otherVector) {
  1193. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1194. };
  1195. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1196. result.x = this.x - otherVector.x;
  1197. result.y = this.y - otherVector.y;
  1198. result.z = this.z - otherVector.z;
  1199. result.w = this.w - otherVector.w;
  1200. return this;
  1201. };
  1202. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1203. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1204. };
  1205. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1206. result.x = this.x - x;
  1207. result.y = this.y - y;
  1208. result.z = this.z - z;
  1209. result.w = this.w - w;
  1210. return this;
  1211. };
  1212. Vector4.prototype.negate = function () {
  1213. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1214. };
  1215. Vector4.prototype.scaleInPlace = function (scale) {
  1216. this.x *= scale;
  1217. this.y *= scale;
  1218. this.z *= scale;
  1219. this.w *= scale;
  1220. return this;
  1221. };
  1222. Vector4.prototype.scale = function (scale) {
  1223. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1224. };
  1225. Vector4.prototype.scaleToRef = function (scale, result) {
  1226. result.x = this.x * scale;
  1227. result.y = this.y * scale;
  1228. result.z = this.z * scale;
  1229. result.w = this.w * scale;
  1230. };
  1231. Vector4.prototype.equals = function (otherVector) {
  1232. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1233. };
  1234. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1235. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1236. return otherVector
  1237. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1238. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1239. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1240. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1241. };
  1242. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1243. return this.x === x && this.y === y && this.z === z && this.w === w;
  1244. };
  1245. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1246. this.x *= otherVector.x;
  1247. this.y *= otherVector.y;
  1248. this.z *= otherVector.z;
  1249. this.w *= otherVector.w;
  1250. return this;
  1251. };
  1252. Vector4.prototype.multiply = function (otherVector) {
  1253. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1254. };
  1255. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1256. result.x = this.x * otherVector.x;
  1257. result.y = this.y * otherVector.y;
  1258. result.z = this.z * otherVector.z;
  1259. result.w = this.w * otherVector.w;
  1260. return this;
  1261. };
  1262. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1263. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1264. };
  1265. Vector4.prototype.divide = function (otherVector) {
  1266. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1267. };
  1268. Vector4.prototype.divideToRef = function (otherVector, result) {
  1269. result.x = this.x / otherVector.x;
  1270. result.y = this.y / otherVector.y;
  1271. result.z = this.z / otherVector.z;
  1272. result.w = this.w / otherVector.w;
  1273. return this;
  1274. };
  1275. Vector4.prototype.MinimizeInPlace = function (other) {
  1276. if (other.x < this.x)
  1277. this.x = other.x;
  1278. if (other.y < this.y)
  1279. this.y = other.y;
  1280. if (other.z < this.z)
  1281. this.z = other.z;
  1282. if (other.w < this.w)
  1283. this.w = other.w;
  1284. return this;
  1285. };
  1286. Vector4.prototype.MaximizeInPlace = function (other) {
  1287. if (other.x > this.x)
  1288. this.x = other.x;
  1289. if (other.y > this.y)
  1290. this.y = other.y;
  1291. if (other.z > this.z)
  1292. this.z = other.z;
  1293. if (other.w > this.w)
  1294. this.w = other.w;
  1295. return this;
  1296. };
  1297. // Properties
  1298. Vector4.prototype.length = function () {
  1299. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1300. };
  1301. Vector4.prototype.lengthSquared = function () {
  1302. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1303. };
  1304. // Methods
  1305. Vector4.prototype.normalize = function () {
  1306. var len = this.length();
  1307. if (len === 0)
  1308. return this;
  1309. var num = 1.0 / len;
  1310. this.x *= num;
  1311. this.y *= num;
  1312. this.z *= num;
  1313. this.w *= num;
  1314. return this;
  1315. };
  1316. Vector4.prototype.toVector3 = function () {
  1317. return new Vector3(this.x, this.y, this.z);
  1318. };
  1319. Vector4.prototype.clone = function () {
  1320. return new Vector4(this.x, this.y, this.z, this.w);
  1321. };
  1322. Vector4.prototype.copyFrom = function (source) {
  1323. this.x = source.x;
  1324. this.y = source.y;
  1325. this.z = source.z;
  1326. this.w = source.w;
  1327. return this;
  1328. };
  1329. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1330. this.x = x;
  1331. this.y = y;
  1332. this.z = z;
  1333. this.w = w;
  1334. return this;
  1335. };
  1336. // Statics
  1337. Vector4.FromArray = function (array, offset) {
  1338. if (!offset) {
  1339. offset = 0;
  1340. }
  1341. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1342. };
  1343. Vector4.FromArrayToRef = function (array, offset, result) {
  1344. result.x = array[offset];
  1345. result.y = array[offset + 1];
  1346. result.z = array[offset + 2];
  1347. result.w = array[offset + 3];
  1348. };
  1349. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1350. result.x = array[offset];
  1351. result.y = array[offset + 1];
  1352. result.z = array[offset + 2];
  1353. result.w = array[offset + 3];
  1354. };
  1355. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1356. result.x = x;
  1357. result.y = y;
  1358. result.z = z;
  1359. result.w = w;
  1360. };
  1361. Vector4.Zero = function () {
  1362. return new Vector4(0, 0, 0, 0);
  1363. };
  1364. Vector4.Normalize = function (vector) {
  1365. var result = Vector4.Zero();
  1366. Vector4.NormalizeToRef(vector, result);
  1367. return result;
  1368. };
  1369. Vector4.NormalizeToRef = function (vector, result) {
  1370. result.copyFrom(vector);
  1371. result.normalize();
  1372. };
  1373. Vector4.Minimize = function (left, right) {
  1374. var min = left.clone();
  1375. min.MinimizeInPlace(right);
  1376. return min;
  1377. };
  1378. Vector4.Maximize = function (left, right) {
  1379. var max = left.clone();
  1380. max.MaximizeInPlace(right);
  1381. return max;
  1382. };
  1383. Vector4.Distance = function (value1, value2) {
  1384. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1385. };
  1386. Vector4.DistanceSquared = function (value1, value2) {
  1387. var x = value1.x - value2.x;
  1388. var y = value1.y - value2.y;
  1389. var z = value1.z - value2.z;
  1390. var w = value1.w - value2.w;
  1391. return (x * x) + (y * y) + (z * z) + (w * w);
  1392. };
  1393. Vector4.Center = function (value1, value2) {
  1394. var center = value1.add(value2);
  1395. center.scaleInPlace(0.5);
  1396. return center;
  1397. };
  1398. return Vector4;
  1399. }());
  1400. BABYLON.Vector4 = Vector4;
  1401. var Size = (function () {
  1402. function Size(width, height) {
  1403. this.width = width;
  1404. this.height = height;
  1405. }
  1406. Size.prototype.toString = function () {
  1407. return "{W: " + this.width + ", H: " + this.height + "}";
  1408. };
  1409. Size.prototype.getClassName = function () {
  1410. return "Size";
  1411. };
  1412. Size.prototype.getHashCode = function () {
  1413. var hash = this.width || 0;
  1414. hash = (hash * 397) ^ (this.height || 0);
  1415. return hash;
  1416. };
  1417. Size.prototype.copyFrom = function (src) {
  1418. this.width = src.width;
  1419. this.height = src.height;
  1420. };
  1421. Size.prototype.copyFromFloats = function (width, height) {
  1422. this.width = width;
  1423. this.height = height;
  1424. };
  1425. Size.prototype.multiplyByFloats = function (w, h) {
  1426. return new Size(this.width * w, this.height * h);
  1427. };
  1428. Size.prototype.clone = function () {
  1429. return new Size(this.width, this.height);
  1430. };
  1431. Size.prototype.equals = function (other) {
  1432. if (!other) {
  1433. return false;
  1434. }
  1435. return (this.width === other.width) && (this.height === other.height);
  1436. };
  1437. Object.defineProperty(Size.prototype, "surface", {
  1438. get: function () {
  1439. return this.width * this.height;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. Size.Zero = function () {
  1445. return new Size(0, 0);
  1446. };
  1447. Size.prototype.add = function (otherSize) {
  1448. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1449. return r;
  1450. };
  1451. Size.prototype.substract = function (otherSize) {
  1452. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1453. return r;
  1454. };
  1455. Size.Lerp = function (start, end, amount) {
  1456. var w = start.width + ((end.width - start.width) * amount);
  1457. var h = start.height + ((end.height - start.height) * amount);
  1458. return new Size(w, h);
  1459. };
  1460. return Size;
  1461. }());
  1462. BABYLON.Size = Size;
  1463. var Quaternion = (function () {
  1464. function Quaternion(x, y, z, w) {
  1465. if (x === void 0) { x = 0; }
  1466. if (y === void 0) { y = 0; }
  1467. if (z === void 0) { z = 0; }
  1468. if (w === void 0) { w = 1; }
  1469. this.x = x;
  1470. this.y = y;
  1471. this.z = z;
  1472. this.w = w;
  1473. }
  1474. Quaternion.prototype.toString = function () {
  1475. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1476. };
  1477. Quaternion.prototype.getClassName = function () {
  1478. return "Quaternion";
  1479. };
  1480. Quaternion.prototype.getHashCode = function () {
  1481. var hash = this.x || 0;
  1482. hash = (hash * 397) ^ (this.y || 0);
  1483. hash = (hash * 397) ^ (this.z || 0);
  1484. hash = (hash * 397) ^ (this.w || 0);
  1485. return hash;
  1486. };
  1487. Quaternion.prototype.asArray = function () {
  1488. return [this.x, this.y, this.z, this.w];
  1489. };
  1490. Quaternion.prototype.equals = function (otherQuaternion) {
  1491. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1492. };
  1493. Quaternion.prototype.clone = function () {
  1494. return new Quaternion(this.x, this.y, this.z, this.w);
  1495. };
  1496. Quaternion.prototype.copyFrom = function (other) {
  1497. this.x = other.x;
  1498. this.y = other.y;
  1499. this.z = other.z;
  1500. this.w = other.w;
  1501. return this;
  1502. };
  1503. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.z = z;
  1507. this.w = w;
  1508. return this;
  1509. };
  1510. Quaternion.prototype.add = function (other) {
  1511. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1512. };
  1513. Quaternion.prototype.subtract = function (other) {
  1514. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1515. };
  1516. Quaternion.prototype.scale = function (value) {
  1517. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1518. };
  1519. Quaternion.prototype.multiply = function (q1) {
  1520. var result = new Quaternion(0, 0, 0, 1.0);
  1521. this.multiplyToRef(q1, result);
  1522. return result;
  1523. };
  1524. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1525. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1526. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1527. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1528. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1529. result.copyFromFloats(x, y, z, w);
  1530. return this;
  1531. };
  1532. Quaternion.prototype.multiplyInPlace = function (q1) {
  1533. this.multiplyToRef(q1, this);
  1534. return this;
  1535. };
  1536. Quaternion.prototype.conjugateToRef = function (ref) {
  1537. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1538. return this;
  1539. };
  1540. Quaternion.prototype.conjugateInPlace = function () {
  1541. this.x *= -1;
  1542. this.y *= -1;
  1543. this.z *= -1;
  1544. return this;
  1545. };
  1546. Quaternion.prototype.conjugate = function () {
  1547. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1548. return result;
  1549. };
  1550. Quaternion.prototype.length = function () {
  1551. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1552. };
  1553. Quaternion.prototype.normalize = function () {
  1554. var length = 1.0 / this.length();
  1555. this.x *= length;
  1556. this.y *= length;
  1557. this.z *= length;
  1558. this.w *= length;
  1559. return this;
  1560. };
  1561. Quaternion.prototype.toEulerAngles = function (order) {
  1562. if (order === void 0) { order = "YZX"; }
  1563. var result = Vector3.Zero();
  1564. this.toEulerAnglesToRef(result, order);
  1565. return result;
  1566. };
  1567. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1568. if (order === void 0) { order = "YZX"; }
  1569. var qz = this.z;
  1570. var qx = this.x;
  1571. var qy = this.y;
  1572. var qw = this.w;
  1573. var sqw = qw * qw;
  1574. var sqz = qz * qz;
  1575. var sqx = qx * qx;
  1576. var sqy = qy * qy;
  1577. var zAxisY = qy * qz - qx * qw;
  1578. var limit = .4999999;
  1579. if (zAxisY < -limit) {
  1580. result.y = 2 * Math.atan2(qy, qw);
  1581. result.x = Math.PI / 2;
  1582. result.z = 0;
  1583. }
  1584. else if (zAxisY > limit) {
  1585. result.y = 2 * Math.atan2(qy, qw);
  1586. result.x = -Math.PI / 2;
  1587. result.z = 0;
  1588. }
  1589. else {
  1590. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  1591. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  1592. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  1593. }
  1594. return this;
  1595. };
  1596. Quaternion.prototype.toRotationMatrix = function (result) {
  1597. var xx = this.x * this.x;
  1598. var yy = this.y * this.y;
  1599. var zz = this.z * this.z;
  1600. var xy = this.x * this.y;
  1601. var zw = this.z * this.w;
  1602. var zx = this.z * this.x;
  1603. var yw = this.y * this.w;
  1604. var yz = this.y * this.z;
  1605. var xw = this.x * this.w;
  1606. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1607. result.m[1] = 2.0 * (xy + zw);
  1608. result.m[2] = 2.0 * (zx - yw);
  1609. result.m[3] = 0;
  1610. result.m[4] = 2.0 * (xy - zw);
  1611. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1612. result.m[6] = 2.0 * (yz + xw);
  1613. result.m[7] = 0;
  1614. result.m[8] = 2.0 * (zx + yw);
  1615. result.m[9] = 2.0 * (yz - xw);
  1616. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1617. result.m[11] = 0;
  1618. result.m[12] = 0;
  1619. result.m[13] = 0;
  1620. result.m[14] = 0;
  1621. result.m[15] = 1.0;
  1622. return this;
  1623. };
  1624. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1625. Quaternion.FromRotationMatrixToRef(matrix, this);
  1626. return this;
  1627. };
  1628. // Statics
  1629. Quaternion.FromRotationMatrix = function (matrix) {
  1630. var result = new Quaternion();
  1631. Quaternion.FromRotationMatrixToRef(matrix, result);
  1632. return result;
  1633. };
  1634. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1635. var data = matrix.m;
  1636. var m11 = data[0], m12 = data[4], m13 = data[8];
  1637. var m21 = data[1], m22 = data[5], m23 = data[9];
  1638. var m31 = data[2], m32 = data[6], m33 = data[10];
  1639. var trace = m11 + m22 + m33;
  1640. var s;
  1641. if (trace > 0) {
  1642. s = 0.5 / Math.sqrt(trace + 1.0);
  1643. result.w = 0.25 / s;
  1644. result.x = (m32 - m23) * s;
  1645. result.y = (m13 - m31) * s;
  1646. result.z = (m21 - m12) * s;
  1647. }
  1648. else if (m11 > m22 && m11 > m33) {
  1649. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1650. result.w = (m32 - m23) / s;
  1651. result.x = 0.25 * s;
  1652. result.y = (m12 + m21) / s;
  1653. result.z = (m13 + m31) / s;
  1654. }
  1655. else if (m22 > m33) {
  1656. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1657. result.w = (m13 - m31) / s;
  1658. result.x = (m12 + m21) / s;
  1659. result.y = 0.25 * s;
  1660. result.z = (m23 + m32) / s;
  1661. }
  1662. else {
  1663. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1664. result.w = (m21 - m12) / s;
  1665. result.x = (m13 + m31) / s;
  1666. result.y = (m23 + m32) / s;
  1667. result.z = 0.25 * s;
  1668. }
  1669. };
  1670. Quaternion.Inverse = function (q) {
  1671. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1672. };
  1673. Quaternion.Identity = function () {
  1674. return new Quaternion(0, 0, 0, 1);
  1675. };
  1676. Quaternion.RotationAxis = function (axis, angle) {
  1677. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1678. };
  1679. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1680. var sin = Math.sin(angle / 2);
  1681. axis.normalize();
  1682. result.w = Math.cos(angle / 2);
  1683. result.x = axis.x * sin;
  1684. result.y = axis.y * sin;
  1685. result.z = axis.z * sin;
  1686. return result;
  1687. };
  1688. Quaternion.FromArray = function (array, offset) {
  1689. if (!offset) {
  1690. offset = 0;
  1691. }
  1692. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1693. };
  1694. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1695. var q = new Quaternion();
  1696. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1697. return q;
  1698. };
  1699. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1700. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1701. var halfRoll = roll * 0.5;
  1702. var halfPitch = pitch * 0.5;
  1703. var halfYaw = yaw * 0.5;
  1704. var sinRoll = Math.sin(halfRoll);
  1705. var cosRoll = Math.cos(halfRoll);
  1706. var sinPitch = Math.sin(halfPitch);
  1707. var cosPitch = Math.cos(halfPitch);
  1708. var sinYaw = Math.sin(halfYaw);
  1709. var cosYaw = Math.cos(halfYaw);
  1710. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1711. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1712. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1713. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1714. };
  1715. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1716. var result = new Quaternion();
  1717. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1718. return result;
  1719. };
  1720. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1721. // Produces a quaternion from Euler angles in the z-x-z orientation
  1722. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1723. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1724. var halfBeta = beta * 0.5;
  1725. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1726. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1727. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1728. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1729. };
  1730. Quaternion.Slerp = function (left, right, amount) {
  1731. var result = Quaternion.Identity();
  1732. Quaternion.SlerpToRef(left, right, amount, result);
  1733. return result;
  1734. };
  1735. Quaternion.SlerpToRef = function (left, right, amount, result) {
  1736. var num2;
  1737. var num3;
  1738. var num = amount;
  1739. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1740. var flag = false;
  1741. if (num4 < 0) {
  1742. flag = true;
  1743. num4 = -num4;
  1744. }
  1745. if (num4 > 0.999999) {
  1746. num3 = 1 - num;
  1747. num2 = flag ? -num : num;
  1748. }
  1749. else {
  1750. var num5 = Math.acos(num4);
  1751. var num6 = (1.0 / Math.sin(num5));
  1752. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1753. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1754. }
  1755. result.x = (num3 * left.x) + (num2 * right.x);
  1756. result.y = (num3 * left.y) + (num2 * right.y);
  1757. result.z = (num3 * left.z) + (num2 * right.z);
  1758. result.w = (num3 * left.w) + (num2 * right.w);
  1759. };
  1760. return Quaternion;
  1761. }());
  1762. BABYLON.Quaternion = Quaternion;
  1763. var Matrix = (function () {
  1764. function Matrix() {
  1765. this.m = new Float32Array(16);
  1766. }
  1767. // Properties
  1768. Matrix.prototype.isIdentity = function () {
  1769. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1770. return false;
  1771. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1772. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1773. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1774. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1775. return false;
  1776. return true;
  1777. };
  1778. Matrix.prototype.determinant = function () {
  1779. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1780. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1781. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1782. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1783. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1784. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1785. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1786. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1787. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1788. };
  1789. // Methods
  1790. Matrix.prototype.toArray = function () {
  1791. return this.m;
  1792. };
  1793. Matrix.prototype.asArray = function () {
  1794. return this.toArray();
  1795. };
  1796. Matrix.prototype.invert = function () {
  1797. this.invertToRef(this);
  1798. return this;
  1799. };
  1800. Matrix.prototype.reset = function () {
  1801. for (var index = 0; index < 16; index++) {
  1802. this.m[index] = 0;
  1803. }
  1804. return this;
  1805. };
  1806. Matrix.prototype.add = function (other) {
  1807. var result = new Matrix();
  1808. this.addToRef(other, result);
  1809. return result;
  1810. };
  1811. Matrix.prototype.addToRef = function (other, result) {
  1812. for (var index = 0; index < 16; index++) {
  1813. result.m[index] = this.m[index] + other.m[index];
  1814. }
  1815. return this;
  1816. };
  1817. Matrix.prototype.addToSelf = function (other) {
  1818. for (var index = 0; index < 16; index++) {
  1819. this.m[index] += other.m[index];
  1820. }
  1821. return this;
  1822. };
  1823. Matrix.prototype.invertToRef = function (other) {
  1824. var l1 = this.m[0];
  1825. var l2 = this.m[1];
  1826. var l3 = this.m[2];
  1827. var l4 = this.m[3];
  1828. var l5 = this.m[4];
  1829. var l6 = this.m[5];
  1830. var l7 = this.m[6];
  1831. var l8 = this.m[7];
  1832. var l9 = this.m[8];
  1833. var l10 = this.m[9];
  1834. var l11 = this.m[10];
  1835. var l12 = this.m[11];
  1836. var l13 = this.m[12];
  1837. var l14 = this.m[13];
  1838. var l15 = this.m[14];
  1839. var l16 = this.m[15];
  1840. var l17 = (l11 * l16) - (l12 * l15);
  1841. var l18 = (l10 * l16) - (l12 * l14);
  1842. var l19 = (l10 * l15) - (l11 * l14);
  1843. var l20 = (l9 * l16) - (l12 * l13);
  1844. var l21 = (l9 * l15) - (l11 * l13);
  1845. var l22 = (l9 * l14) - (l10 * l13);
  1846. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1847. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1848. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1849. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1850. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1851. var l28 = (l7 * l16) - (l8 * l15);
  1852. var l29 = (l6 * l16) - (l8 * l14);
  1853. var l30 = (l6 * l15) - (l7 * l14);
  1854. var l31 = (l5 * l16) - (l8 * l13);
  1855. var l32 = (l5 * l15) - (l7 * l13);
  1856. var l33 = (l5 * l14) - (l6 * l13);
  1857. var l34 = (l7 * l12) - (l8 * l11);
  1858. var l35 = (l6 * l12) - (l8 * l10);
  1859. var l36 = (l6 * l11) - (l7 * l10);
  1860. var l37 = (l5 * l12) - (l8 * l9);
  1861. var l38 = (l5 * l11) - (l7 * l9);
  1862. var l39 = (l5 * l10) - (l6 * l9);
  1863. other.m[0] = l23 * l27;
  1864. other.m[4] = l24 * l27;
  1865. other.m[8] = l25 * l27;
  1866. other.m[12] = l26 * l27;
  1867. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1868. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1869. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1870. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1871. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1872. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1873. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1874. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1875. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1876. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1877. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1878. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1879. return this;
  1880. };
  1881. Matrix.prototype.setTranslation = function (vector3) {
  1882. this.m[12] = vector3.x;
  1883. this.m[13] = vector3.y;
  1884. this.m[14] = vector3.z;
  1885. return this;
  1886. };
  1887. Matrix.prototype.getTranslation = function () {
  1888. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1889. };
  1890. Matrix.prototype.multiply = function (other) {
  1891. var result = new Matrix();
  1892. this.multiplyToRef(other, result);
  1893. return result;
  1894. };
  1895. Matrix.prototype.copyFrom = function (other) {
  1896. for (var index = 0; index < 16; index++) {
  1897. this.m[index] = other.m[index];
  1898. }
  1899. return this;
  1900. };
  1901. Matrix.prototype.copyToArray = function (array, offset) {
  1902. if (offset === void 0) { offset = 0; }
  1903. for (var index = 0; index < 16; index++) {
  1904. array[offset + index] = this.m[index];
  1905. }
  1906. return this;
  1907. };
  1908. Matrix.prototype.multiplyToRef = function (other, result) {
  1909. this.multiplyToArray(other, result.m, 0);
  1910. return this;
  1911. };
  1912. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1913. var tm0 = this.m[0];
  1914. var tm1 = this.m[1];
  1915. var tm2 = this.m[2];
  1916. var tm3 = this.m[3];
  1917. var tm4 = this.m[4];
  1918. var tm5 = this.m[5];
  1919. var tm6 = this.m[6];
  1920. var tm7 = this.m[7];
  1921. var tm8 = this.m[8];
  1922. var tm9 = this.m[9];
  1923. var tm10 = this.m[10];
  1924. var tm11 = this.m[11];
  1925. var tm12 = this.m[12];
  1926. var tm13 = this.m[13];
  1927. var tm14 = this.m[14];
  1928. var tm15 = this.m[15];
  1929. var om0 = other.m[0];
  1930. var om1 = other.m[1];
  1931. var om2 = other.m[2];
  1932. var om3 = other.m[3];
  1933. var om4 = other.m[4];
  1934. var om5 = other.m[5];
  1935. var om6 = other.m[6];
  1936. var om7 = other.m[7];
  1937. var om8 = other.m[8];
  1938. var om9 = other.m[9];
  1939. var om10 = other.m[10];
  1940. var om11 = other.m[11];
  1941. var om12 = other.m[12];
  1942. var om13 = other.m[13];
  1943. var om14 = other.m[14];
  1944. var om15 = other.m[15];
  1945. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1946. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1947. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1948. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1949. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1950. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1951. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1952. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1953. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1954. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1955. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1956. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1957. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1958. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1959. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1960. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1961. return this;
  1962. };
  1963. Matrix.prototype.equals = function (value) {
  1964. return value &&
  1965. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1966. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1967. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1968. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1969. };
  1970. Matrix.prototype.clone = function () {
  1971. 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]);
  1972. };
  1973. Matrix.prototype.getClassName = function () {
  1974. return "Matrix";
  1975. };
  1976. Matrix.prototype.getHashCode = function () {
  1977. var hash = this.m[0] || 0;
  1978. for (var i = 1; i < 16; i++) {
  1979. hash = (hash * 397) ^ (this.m[i] || 0);
  1980. }
  1981. return hash;
  1982. };
  1983. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1984. translation.x = this.m[12];
  1985. translation.y = this.m[13];
  1986. translation.z = this.m[14];
  1987. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1988. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1989. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1990. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1991. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1992. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1993. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1994. rotation.x = 0;
  1995. rotation.y = 0;
  1996. rotation.z = 0;
  1997. rotation.w = 1;
  1998. return false;
  1999. }
  2000. 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]);
  2001. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  2002. return true;
  2003. };
  2004. Matrix.prototype.getRotationMatrix = function () {
  2005. var result = Matrix.Identity();
  2006. this.getRotationMatrixToRef(result);
  2007. return result;
  2008. };
  2009. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2010. var m = this.m;
  2011. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2012. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2013. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2014. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2015. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2016. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2017. 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);
  2018. };
  2019. // Statics
  2020. Matrix.FromArray = function (array, offset) {
  2021. var result = new Matrix();
  2022. if (!offset) {
  2023. offset = 0;
  2024. }
  2025. Matrix.FromArrayToRef(array, offset, result);
  2026. return result;
  2027. };
  2028. Matrix.FromArrayToRef = function (array, offset, result) {
  2029. for (var index = 0; index < 16; index++) {
  2030. result.m[index] = array[index + offset];
  2031. }
  2032. };
  2033. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2034. for (var index = 0; index < 16; index++) {
  2035. result.m[index] = array[index + offset] * scale;
  2036. }
  2037. };
  2038. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2039. result.m[0] = initialM11;
  2040. result.m[1] = initialM12;
  2041. result.m[2] = initialM13;
  2042. result.m[3] = initialM14;
  2043. result.m[4] = initialM21;
  2044. result.m[5] = initialM22;
  2045. result.m[6] = initialM23;
  2046. result.m[7] = initialM24;
  2047. result.m[8] = initialM31;
  2048. result.m[9] = initialM32;
  2049. result.m[10] = initialM33;
  2050. result.m[11] = initialM34;
  2051. result.m[12] = initialM41;
  2052. result.m[13] = initialM42;
  2053. result.m[14] = initialM43;
  2054. result.m[15] = initialM44;
  2055. };
  2056. Matrix.prototype.getRow = function (index) {
  2057. if (index < 0 || index > 3) {
  2058. return null;
  2059. }
  2060. var i = index * 4;
  2061. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2062. };
  2063. Matrix.prototype.setRow = function (index, row) {
  2064. if (index < 0 || index > 3) {
  2065. return this;
  2066. }
  2067. var i = index * 4;
  2068. this.m[i + 0] = row.x;
  2069. this.m[i + 1] = row.y;
  2070. this.m[i + 2] = row.z;
  2071. this.m[i + 3] = row.w;
  2072. return this;
  2073. };
  2074. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2075. var result = new Matrix();
  2076. result.m[0] = initialM11;
  2077. result.m[1] = initialM12;
  2078. result.m[2] = initialM13;
  2079. result.m[3] = initialM14;
  2080. result.m[4] = initialM21;
  2081. result.m[5] = initialM22;
  2082. result.m[6] = initialM23;
  2083. result.m[7] = initialM24;
  2084. result.m[8] = initialM31;
  2085. result.m[9] = initialM32;
  2086. result.m[10] = initialM33;
  2087. result.m[11] = initialM34;
  2088. result.m[12] = initialM41;
  2089. result.m[13] = initialM42;
  2090. result.m[14] = initialM43;
  2091. result.m[15] = initialM44;
  2092. return result;
  2093. };
  2094. Matrix.Compose = function (scale, rotation, translation) {
  2095. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2096. var rotationMatrix = Matrix.Identity();
  2097. rotation.toRotationMatrix(rotationMatrix);
  2098. result = result.multiply(rotationMatrix);
  2099. result.setTranslation(translation);
  2100. return result;
  2101. };
  2102. Matrix.Identity = function () {
  2103. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2104. };
  2105. Matrix.IdentityToRef = function (result) {
  2106. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2107. };
  2108. Matrix.Zero = function () {
  2109. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2110. };
  2111. Matrix.RotationX = function (angle) {
  2112. var result = new Matrix();
  2113. Matrix.RotationXToRef(angle, result);
  2114. return result;
  2115. };
  2116. Matrix.Invert = function (source) {
  2117. var result = new Matrix();
  2118. source.invertToRef(result);
  2119. return result;
  2120. };
  2121. Matrix.RotationXToRef = function (angle, result) {
  2122. var s = Math.sin(angle);
  2123. var c = Math.cos(angle);
  2124. result.m[0] = 1.0;
  2125. result.m[15] = 1.0;
  2126. result.m[5] = c;
  2127. result.m[10] = c;
  2128. result.m[9] = -s;
  2129. result.m[6] = s;
  2130. result.m[1] = 0;
  2131. result.m[2] = 0;
  2132. result.m[3] = 0;
  2133. result.m[4] = 0;
  2134. result.m[7] = 0;
  2135. result.m[8] = 0;
  2136. result.m[11] = 0;
  2137. result.m[12] = 0;
  2138. result.m[13] = 0;
  2139. result.m[14] = 0;
  2140. };
  2141. Matrix.RotationY = function (angle) {
  2142. var result = new Matrix();
  2143. Matrix.RotationYToRef(angle, result);
  2144. return result;
  2145. };
  2146. Matrix.RotationYToRef = function (angle, result) {
  2147. var s = Math.sin(angle);
  2148. var c = Math.cos(angle);
  2149. result.m[5] = 1.0;
  2150. result.m[15] = 1.0;
  2151. result.m[0] = c;
  2152. result.m[2] = -s;
  2153. result.m[8] = s;
  2154. result.m[10] = c;
  2155. result.m[1] = 0;
  2156. result.m[3] = 0;
  2157. result.m[4] = 0;
  2158. result.m[6] = 0;
  2159. result.m[7] = 0;
  2160. result.m[9] = 0;
  2161. result.m[11] = 0;
  2162. result.m[12] = 0;
  2163. result.m[13] = 0;
  2164. result.m[14] = 0;
  2165. };
  2166. Matrix.RotationZ = function (angle) {
  2167. var result = new Matrix();
  2168. Matrix.RotationZToRef(angle, result);
  2169. return result;
  2170. };
  2171. Matrix.RotationZToRef = function (angle, result) {
  2172. var s = Math.sin(angle);
  2173. var c = Math.cos(angle);
  2174. result.m[10] = 1.0;
  2175. result.m[15] = 1.0;
  2176. result.m[0] = c;
  2177. result.m[1] = s;
  2178. result.m[4] = -s;
  2179. result.m[5] = c;
  2180. result.m[2] = 0;
  2181. result.m[3] = 0;
  2182. result.m[6] = 0;
  2183. result.m[7] = 0;
  2184. result.m[8] = 0;
  2185. result.m[9] = 0;
  2186. result.m[11] = 0;
  2187. result.m[12] = 0;
  2188. result.m[13] = 0;
  2189. result.m[14] = 0;
  2190. };
  2191. Matrix.RotationAxis = function (axis, angle) {
  2192. var result = Matrix.Zero();
  2193. Matrix.RotationAxisToRef(axis, angle, result);
  2194. return result;
  2195. };
  2196. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2197. var s = Math.sin(-angle);
  2198. var c = Math.cos(-angle);
  2199. var c1 = 1 - c;
  2200. axis.normalize();
  2201. result.m[0] = (axis.x * axis.x) * c1 + c;
  2202. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2203. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2204. result.m[3] = 0.0;
  2205. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2206. result.m[5] = (axis.y * axis.y) * c1 + c;
  2207. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2208. result.m[7] = 0.0;
  2209. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2210. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2211. result.m[10] = (axis.z * axis.z) * c1 + c;
  2212. result.m[11] = 0.0;
  2213. result.m[15] = 1.0;
  2214. };
  2215. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2216. var result = new Matrix();
  2217. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2218. return result;
  2219. };
  2220. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2221. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2222. this._tempQuaternion.toRotationMatrix(result);
  2223. };
  2224. Matrix.Scaling = function (x, y, z) {
  2225. var result = Matrix.Zero();
  2226. Matrix.ScalingToRef(x, y, z, result);
  2227. return result;
  2228. };
  2229. Matrix.ScalingToRef = function (x, y, z, result) {
  2230. result.m[0] = x;
  2231. result.m[1] = 0;
  2232. result.m[2] = 0;
  2233. result.m[3] = 0;
  2234. result.m[4] = 0;
  2235. result.m[5] = y;
  2236. result.m[6] = 0;
  2237. result.m[7] = 0;
  2238. result.m[8] = 0;
  2239. result.m[9] = 0;
  2240. result.m[10] = z;
  2241. result.m[11] = 0;
  2242. result.m[12] = 0;
  2243. result.m[13] = 0;
  2244. result.m[14] = 0;
  2245. result.m[15] = 1.0;
  2246. };
  2247. Matrix.Translation = function (x, y, z) {
  2248. var result = Matrix.Identity();
  2249. Matrix.TranslationToRef(x, y, z, result);
  2250. return result;
  2251. };
  2252. Matrix.TranslationToRef = function (x, y, z, result) {
  2253. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2254. };
  2255. Matrix.Lerp = function (startValue, endValue, gradient) {
  2256. var result = Matrix.Zero();
  2257. for (var index = 0; index < 16; index++) {
  2258. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2259. }
  2260. return result;
  2261. };
  2262. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2263. var startScale = new Vector3(0, 0, 0);
  2264. var startRotation = new Quaternion();
  2265. var startTranslation = new Vector3(0, 0, 0);
  2266. startValue.decompose(startScale, startRotation, startTranslation);
  2267. var endScale = new Vector3(0, 0, 0);
  2268. var endRotation = new Quaternion();
  2269. var endTranslation = new Vector3(0, 0, 0);
  2270. endValue.decompose(endScale, endRotation, endTranslation);
  2271. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2272. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2273. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2274. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2275. };
  2276. Matrix.LookAtLH = function (eye, target, up) {
  2277. var result = Matrix.Zero();
  2278. Matrix.LookAtLHToRef(eye, target, up, result);
  2279. return result;
  2280. };
  2281. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2282. // Z axis
  2283. target.subtractToRef(eye, this._zAxis);
  2284. this._zAxis.normalize();
  2285. // X axis
  2286. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2287. if (this._xAxis.lengthSquared() === 0) {
  2288. this._xAxis.x = 1.0;
  2289. }
  2290. else {
  2291. this._xAxis.normalize();
  2292. }
  2293. // Y axis
  2294. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2295. this._yAxis.normalize();
  2296. // Eye angles
  2297. var ex = -Vector3.Dot(this._xAxis, eye);
  2298. var ey = -Vector3.Dot(this._yAxis, eye);
  2299. var ez = -Vector3.Dot(this._zAxis, eye);
  2300. 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);
  2301. };
  2302. Matrix.LookAtRH = function (eye, target, up) {
  2303. var result = Matrix.Zero();
  2304. Matrix.LookAtRHToRef(eye, target, up, result);
  2305. return result;
  2306. };
  2307. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2308. // Z axis
  2309. eye.subtractToRef(target, this._zAxis);
  2310. this._zAxis.normalize();
  2311. // X axis
  2312. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2313. if (this._xAxis.lengthSquared() === 0) {
  2314. this._xAxis.x = 1.0;
  2315. }
  2316. else {
  2317. this._xAxis.normalize();
  2318. }
  2319. // Y axis
  2320. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2321. this._yAxis.normalize();
  2322. // Eye angles
  2323. var ex = -Vector3.Dot(this._xAxis, eye);
  2324. var ey = -Vector3.Dot(this._yAxis, eye);
  2325. var ez = -Vector3.Dot(this._zAxis, eye);
  2326. 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);
  2327. };
  2328. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2329. var matrix = Matrix.Zero();
  2330. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2331. return matrix;
  2332. };
  2333. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2334. var hw = 2.0 / width;
  2335. var hh = 2.0 / height;
  2336. var id = 1.0 / (zfar - znear);
  2337. var nid = znear / (znear - zfar);
  2338. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2339. };
  2340. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2341. var matrix = Matrix.Zero();
  2342. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2343. return matrix;
  2344. };
  2345. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2346. result.m[0] = 2.0 / (right - left);
  2347. result.m[1] = result.m[2] = result.m[3] = 0;
  2348. result.m[5] = 2.0 / (top - bottom);
  2349. result.m[4] = result.m[6] = result.m[7] = 0;
  2350. result.m[10] = 1.0 / (zfar - znear);
  2351. result.m[8] = result.m[9] = result.m[11] = 0;
  2352. result.m[12] = (left + right) / (left - right);
  2353. result.m[13] = (top + bottom) / (bottom - top);
  2354. result.m[14] = -znear / (zfar - znear);
  2355. result.m[15] = 1.0;
  2356. };
  2357. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2358. var matrix = Matrix.Zero();
  2359. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2360. return matrix;
  2361. };
  2362. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2363. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2364. result.m[10] *= -1.0;
  2365. };
  2366. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2367. var matrix = Matrix.Zero();
  2368. matrix.m[0] = (2.0 * znear) / width;
  2369. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2370. matrix.m[5] = (2.0 * znear) / height;
  2371. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2372. matrix.m[10] = -zfar / (znear - zfar);
  2373. matrix.m[8] = matrix.m[9] = 0.0;
  2374. matrix.m[11] = 1.0;
  2375. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2376. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2377. return matrix;
  2378. };
  2379. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2380. var matrix = Matrix.Zero();
  2381. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2382. return matrix;
  2383. };
  2384. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2385. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2386. var tan = 1.0 / (Math.tan(fov * 0.5));
  2387. if (isVerticalFovFixed) {
  2388. result.m[0] = tan / aspect;
  2389. }
  2390. else {
  2391. result.m[0] = tan;
  2392. }
  2393. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2394. if (isVerticalFovFixed) {
  2395. result.m[5] = tan;
  2396. }
  2397. else {
  2398. result.m[5] = tan * aspect;
  2399. }
  2400. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2401. result.m[8] = result.m[9] = 0.0;
  2402. result.m[10] = zfar / (zfar - znear);
  2403. result.m[11] = 1.0;
  2404. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2405. result.m[14] = -(znear * zfar) / (zfar - znear);
  2406. };
  2407. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2408. var matrix = Matrix.Zero();
  2409. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2410. return matrix;
  2411. };
  2412. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2413. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2414. var tan = 1.0 / (Math.tan(fov * 0.5));
  2415. if (isVerticalFovFixed) {
  2416. result.m[0] = tan / aspect;
  2417. }
  2418. else {
  2419. result.m[0] = tan;
  2420. }
  2421. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2422. if (isVerticalFovFixed) {
  2423. result.m[5] = tan;
  2424. }
  2425. else {
  2426. result.m[5] = tan * aspect;
  2427. }
  2428. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2429. result.m[8] = result.m[9] = 0.0;
  2430. result.m[10] = zfar / (znear - zfar);
  2431. result.m[11] = -1.0;
  2432. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2433. result.m[14] = (znear * zfar) / (znear - zfar);
  2434. };
  2435. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2436. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2437. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2438. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2439. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2440. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2441. var xScale = 2.0 / (leftTan + rightTan);
  2442. var yScale = 2.0 / (upTan + downTan);
  2443. result.m[0] = xScale;
  2444. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2445. result.m[5] = yScale;
  2446. result.m[6] = result.m[7] = 0.0;
  2447. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2448. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2449. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2450. result.m[10] = -zfar / (znear - zfar);
  2451. result.m[11] = 1.0;
  2452. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2453. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2454. result.m[14] = (znear * zfar) / (znear - zfar);
  2455. };
  2456. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2457. var cw = viewport.width;
  2458. var ch = viewport.height;
  2459. var cx = viewport.x;
  2460. var cy = viewport.y;
  2461. 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);
  2462. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2463. };
  2464. Matrix.GetAsMatrix2x2 = function (matrix) {
  2465. return new Float32Array([
  2466. matrix.m[0], matrix.m[1],
  2467. matrix.m[4], matrix.m[5]
  2468. ]);
  2469. };
  2470. Matrix.GetAsMatrix3x3 = function (matrix) {
  2471. return new Float32Array([
  2472. matrix.m[0], matrix.m[1], matrix.m[2],
  2473. matrix.m[4], matrix.m[5], matrix.m[6],
  2474. matrix.m[8], matrix.m[9], matrix.m[10]
  2475. ]);
  2476. };
  2477. Matrix.Transpose = function (matrix) {
  2478. var result = new Matrix();
  2479. result.m[0] = matrix.m[0];
  2480. result.m[1] = matrix.m[4];
  2481. result.m[2] = matrix.m[8];
  2482. result.m[3] = matrix.m[12];
  2483. result.m[4] = matrix.m[1];
  2484. result.m[5] = matrix.m[5];
  2485. result.m[6] = matrix.m[9];
  2486. result.m[7] = matrix.m[13];
  2487. result.m[8] = matrix.m[2];
  2488. result.m[9] = matrix.m[6];
  2489. result.m[10] = matrix.m[10];
  2490. result.m[11] = matrix.m[14];
  2491. result.m[12] = matrix.m[3];
  2492. result.m[13] = matrix.m[7];
  2493. result.m[14] = matrix.m[11];
  2494. result.m[15] = matrix.m[15];
  2495. return result;
  2496. };
  2497. Matrix.Reflection = function (plane) {
  2498. var matrix = new Matrix();
  2499. Matrix.ReflectionToRef(plane, matrix);
  2500. return matrix;
  2501. };
  2502. Matrix.ReflectionToRef = function (plane, result) {
  2503. plane.normalize();
  2504. var x = plane.normal.x;
  2505. var y = plane.normal.y;
  2506. var z = plane.normal.z;
  2507. var temp = -2 * x;
  2508. var temp2 = -2 * y;
  2509. var temp3 = -2 * z;
  2510. result.m[0] = (temp * x) + 1;
  2511. result.m[1] = temp2 * x;
  2512. result.m[2] = temp3 * x;
  2513. result.m[3] = 0.0;
  2514. result.m[4] = temp * y;
  2515. result.m[5] = (temp2 * y) + 1;
  2516. result.m[6] = temp3 * y;
  2517. result.m[7] = 0.0;
  2518. result.m[8] = temp * z;
  2519. result.m[9] = temp2 * z;
  2520. result.m[10] = (temp3 * z) + 1;
  2521. result.m[11] = 0.0;
  2522. result.m[12] = temp * plane.d;
  2523. result.m[13] = temp2 * plane.d;
  2524. result.m[14] = temp3 * plane.d;
  2525. result.m[15] = 1.0;
  2526. };
  2527. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2528. mat.m[0] = xaxis.x;
  2529. mat.m[1] = xaxis.y;
  2530. mat.m[2] = xaxis.z;
  2531. mat.m[3] = 0;
  2532. mat.m[4] = yaxis.x;
  2533. mat.m[5] = yaxis.y;
  2534. mat.m[6] = yaxis.z;
  2535. mat.m[7] = 0;
  2536. mat.m[8] = zaxis.x;
  2537. mat.m[9] = zaxis.y;
  2538. mat.m[10] = zaxis.z;
  2539. mat.m[11] = 0;
  2540. mat.m[12] = 0;
  2541. mat.m[13] = 0;
  2542. mat.m[14] = 0;
  2543. mat.m[15] = 1;
  2544. };
  2545. Matrix.FromQuaternionToRef = function (quat, result) {
  2546. var xx = quat.x * quat.x;
  2547. var yy = quat.y * quat.y;
  2548. var zz = quat.z * quat.z;
  2549. var xy = quat.x * quat.y;
  2550. var zw = quat.z * quat.w;
  2551. var zx = quat.z * quat.x;
  2552. var yw = quat.y * quat.w;
  2553. var yz = quat.y * quat.z;
  2554. var xw = quat.x * quat.w;
  2555. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2556. result.m[1] = 2.0 * (xy + zw);
  2557. result.m[2] = 2.0 * (zx - yw);
  2558. result.m[3] = 0;
  2559. result.m[4] = 2.0 * (xy - zw);
  2560. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2561. result.m[6] = 2.0 * (yz + xw);
  2562. result.m[7] = 0;
  2563. result.m[8] = 2.0 * (zx + yw);
  2564. result.m[9] = 2.0 * (yz - xw);
  2565. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2566. result.m[11] = 0;
  2567. result.m[12] = 0;
  2568. result.m[13] = 0;
  2569. result.m[14] = 0;
  2570. result.m[15] = 1.0;
  2571. };
  2572. Matrix._tempQuaternion = new Quaternion();
  2573. Matrix._xAxis = Vector3.Zero();
  2574. Matrix._yAxis = Vector3.Zero();
  2575. Matrix._zAxis = Vector3.Zero();
  2576. return Matrix;
  2577. }());
  2578. BABYLON.Matrix = Matrix;
  2579. var Plane = (function () {
  2580. function Plane(a, b, c, d) {
  2581. this.normal = new Vector3(a, b, c);
  2582. this.d = d;
  2583. }
  2584. Plane.prototype.asArray = function () {
  2585. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2586. };
  2587. // Methods
  2588. Plane.prototype.clone = function () {
  2589. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2590. };
  2591. Plane.prototype.getClassName = function () {
  2592. return "Plane";
  2593. };
  2594. Plane.prototype.getHashCode = function () {
  2595. var hash = this.normal.getHashCode();
  2596. hash = (hash * 397) ^ (this.d || 0);
  2597. return hash;
  2598. };
  2599. Plane.prototype.normalize = function () {
  2600. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2601. var magnitude = 0;
  2602. if (norm !== 0) {
  2603. magnitude = 1.0 / norm;
  2604. }
  2605. this.normal.x *= magnitude;
  2606. this.normal.y *= magnitude;
  2607. this.normal.z *= magnitude;
  2608. this.d *= magnitude;
  2609. return this;
  2610. };
  2611. Plane.prototype.transform = function (transformation) {
  2612. var transposedMatrix = Matrix.Transpose(transformation);
  2613. var x = this.normal.x;
  2614. var y = this.normal.y;
  2615. var z = this.normal.z;
  2616. var d = this.d;
  2617. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2618. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2619. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2620. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2621. return new Plane(normalX, normalY, normalZ, finalD);
  2622. };
  2623. Plane.prototype.dotCoordinate = function (point) {
  2624. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2625. };
  2626. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2627. var x1 = point2.x - point1.x;
  2628. var y1 = point2.y - point1.y;
  2629. var z1 = point2.z - point1.z;
  2630. var x2 = point3.x - point1.x;
  2631. var y2 = point3.y - point1.y;
  2632. var z2 = point3.z - point1.z;
  2633. var yz = (y1 * z2) - (z1 * y2);
  2634. var xz = (z1 * x2) - (x1 * z2);
  2635. var xy = (x1 * y2) - (y1 * x2);
  2636. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2637. var invPyth;
  2638. if (pyth !== 0) {
  2639. invPyth = 1.0 / pyth;
  2640. }
  2641. else {
  2642. invPyth = 0;
  2643. }
  2644. this.normal.x = yz * invPyth;
  2645. this.normal.y = xz * invPyth;
  2646. this.normal.z = xy * invPyth;
  2647. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2648. return this;
  2649. };
  2650. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2651. var dot = Vector3.Dot(this.normal, direction);
  2652. return (dot <= epsilon);
  2653. };
  2654. Plane.prototype.signedDistanceTo = function (point) {
  2655. return Vector3.Dot(point, this.normal) + this.d;
  2656. };
  2657. // Statics
  2658. Plane.FromArray = function (array) {
  2659. return new Plane(array[0], array[1], array[2], array[3]);
  2660. };
  2661. Plane.FromPoints = function (point1, point2, point3) {
  2662. var result = new Plane(0, 0, 0, 0);
  2663. result.copyFromPoints(point1, point2, point3);
  2664. return result;
  2665. };
  2666. Plane.FromPositionAndNormal = function (origin, normal) {
  2667. var result = new Plane(0, 0, 0, 0);
  2668. normal.normalize();
  2669. result.normal = normal;
  2670. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2671. return result;
  2672. };
  2673. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2674. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2675. return Vector3.Dot(point, normal) + d;
  2676. };
  2677. return Plane;
  2678. }());
  2679. BABYLON.Plane = Plane;
  2680. var Viewport = (function () {
  2681. function Viewport(x, y, width, height) {
  2682. this.x = x;
  2683. this.y = y;
  2684. this.width = width;
  2685. this.height = height;
  2686. }
  2687. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2688. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2689. };
  2690. return Viewport;
  2691. }());
  2692. BABYLON.Viewport = Viewport;
  2693. var Frustum = (function () {
  2694. function Frustum() {
  2695. }
  2696. Frustum.GetPlanes = function (transform) {
  2697. var frustumPlanes = [];
  2698. for (var index = 0; index < 6; index++) {
  2699. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2700. }
  2701. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2702. return frustumPlanes;
  2703. };
  2704. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2705. // Near
  2706. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2707. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2708. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2709. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2710. frustumPlanes[0].normalize();
  2711. // Far
  2712. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2713. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2714. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2715. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2716. frustumPlanes[1].normalize();
  2717. // Left
  2718. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2719. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2720. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2721. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2722. frustumPlanes[2].normalize();
  2723. // Right
  2724. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2725. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2726. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2727. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2728. frustumPlanes[3].normalize();
  2729. // Top
  2730. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2731. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2732. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2733. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2734. frustumPlanes[4].normalize();
  2735. // Bottom
  2736. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2737. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2738. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2739. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2740. frustumPlanes[5].normalize();
  2741. };
  2742. return Frustum;
  2743. }());
  2744. BABYLON.Frustum = Frustum;
  2745. (function (Space) {
  2746. Space[Space["LOCAL"] = 0] = "LOCAL";
  2747. Space[Space["WORLD"] = 1] = "WORLD";
  2748. })(BABYLON.Space || (BABYLON.Space = {}));
  2749. var Space = BABYLON.Space;
  2750. var Axis = (function () {
  2751. function Axis() {
  2752. }
  2753. Axis.X = new Vector3(1, 0, 0);
  2754. Axis.Y = new Vector3(0, 1, 0);
  2755. Axis.Z = new Vector3(0, 0, 1);
  2756. return Axis;
  2757. }());
  2758. BABYLON.Axis = Axis;
  2759. ;
  2760. var BezierCurve = (function () {
  2761. function BezierCurve() {
  2762. }
  2763. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2764. // Extract X (which is equal to time here)
  2765. var f0 = 1 - 3 * x2 + 3 * x1;
  2766. var f1 = 3 * x2 - 6 * x1;
  2767. var f2 = 3 * x1;
  2768. var refinedT = t;
  2769. for (var i = 0; i < 5; i++) {
  2770. var refinedT2 = refinedT * refinedT;
  2771. var refinedT3 = refinedT2 * refinedT;
  2772. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2773. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2774. refinedT -= (x - t) * slope;
  2775. refinedT = Math.min(1, Math.max(0, refinedT));
  2776. }
  2777. // Resolve cubic bezier for the given x
  2778. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2779. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2780. Math.pow(refinedT, 3);
  2781. };
  2782. return BezierCurve;
  2783. }());
  2784. BABYLON.BezierCurve = BezierCurve;
  2785. (function (Orientation) {
  2786. Orientation[Orientation["CW"] = 0] = "CW";
  2787. Orientation[Orientation["CCW"] = 1] = "CCW";
  2788. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2789. var Orientation = BABYLON.Orientation;
  2790. var Angle = (function () {
  2791. function Angle(radians) {
  2792. var _this = this;
  2793. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2794. this.radians = function () { return _this._radians; };
  2795. this._radians = radians;
  2796. if (this._radians < 0)
  2797. this._radians += (2 * Math.PI);
  2798. }
  2799. Angle.BetweenTwoPoints = function (a, b) {
  2800. var delta = b.subtract(a);
  2801. var theta = Math.atan2(delta.y, delta.x);
  2802. return new Angle(theta);
  2803. };
  2804. Angle.FromRadians = function (radians) {
  2805. return new Angle(radians);
  2806. };
  2807. Angle.FromDegrees = function (degrees) {
  2808. return new Angle(degrees * Math.PI / 180);
  2809. };
  2810. return Angle;
  2811. }());
  2812. BABYLON.Angle = Angle;
  2813. var Arc2 = (function () {
  2814. function Arc2(startPoint, midPoint, endPoint) {
  2815. this.startPoint = startPoint;
  2816. this.midPoint = midPoint;
  2817. this.endPoint = endPoint;
  2818. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2819. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2820. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2821. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2822. 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);
  2823. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2824. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2825. var a1 = this.startAngle.degrees();
  2826. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2827. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2828. // angles correction
  2829. if (a2 - a1 > +180.0)
  2830. a2 -= 360.0;
  2831. if (a2 - a1 < -180.0)
  2832. a2 += 360.0;
  2833. if (a3 - a2 > +180.0)
  2834. a3 -= 360.0;
  2835. if (a3 - a2 < -180.0)
  2836. a3 += 360.0;
  2837. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2838. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2839. }
  2840. return Arc2;
  2841. }());
  2842. BABYLON.Arc2 = Arc2;
  2843. var Path2 = (function () {
  2844. function Path2(x, y) {
  2845. this._points = new Array();
  2846. this._length = 0;
  2847. this.closed = false;
  2848. this._points.push(new Vector2(x, y));
  2849. }
  2850. Path2.prototype.addLineTo = function (x, y) {
  2851. if (closed) {
  2852. //Tools.Error("cannot add lines to closed paths");
  2853. return this;
  2854. }
  2855. var newPoint = new Vector2(x, y);
  2856. var previousPoint = this._points[this._points.length - 1];
  2857. this._points.push(newPoint);
  2858. this._length += newPoint.subtract(previousPoint).length();
  2859. return this;
  2860. };
  2861. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2862. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2863. if (closed) {
  2864. //Tools.Error("cannot add arcs to closed paths");
  2865. return this;
  2866. }
  2867. var startPoint = this._points[this._points.length - 1];
  2868. var midPoint = new Vector2(midX, midY);
  2869. var endPoint = new Vector2(endX, endY);
  2870. var arc = new Arc2(startPoint, midPoint, endPoint);
  2871. var increment = arc.angle.radians() / numberOfSegments;
  2872. if (arc.orientation === Orientation.CW)
  2873. increment *= -1;
  2874. var currentAngle = arc.startAngle.radians() + increment;
  2875. for (var i = 0; i < numberOfSegments; i++) {
  2876. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2877. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2878. this.addLineTo(x, y);
  2879. currentAngle += increment;
  2880. }
  2881. return this;
  2882. };
  2883. Path2.prototype.close = function () {
  2884. this.closed = true;
  2885. return this;
  2886. };
  2887. Path2.prototype.length = function () {
  2888. var result = this._length;
  2889. if (!this.closed) {
  2890. var lastPoint = this._points[this._points.length - 1];
  2891. var firstPoint = this._points[0];
  2892. result += (firstPoint.subtract(lastPoint).length());
  2893. }
  2894. return result;
  2895. };
  2896. Path2.prototype.getPoints = function () {
  2897. return this._points;
  2898. };
  2899. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2900. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2901. //Tools.Error("normalized length position should be between 0 and 1.");
  2902. return Vector2.Zero();
  2903. }
  2904. var lengthPosition = normalizedLengthPosition * this.length();
  2905. var previousOffset = 0;
  2906. for (var i = 0; i < this._points.length; i++) {
  2907. var j = (i + 1) % this._points.length;
  2908. var a = this._points[i];
  2909. var b = this._points[j];
  2910. var bToA = b.subtract(a);
  2911. var nextOffset = (bToA.length() + previousOffset);
  2912. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2913. var dir = bToA.normalize();
  2914. var localOffset = lengthPosition - previousOffset;
  2915. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2916. }
  2917. previousOffset = nextOffset;
  2918. }
  2919. //Tools.Error("internal error");
  2920. return Vector2.Zero();
  2921. };
  2922. Path2.StartingAt = function (x, y) {
  2923. return new Path2(x, y);
  2924. };
  2925. return Path2;
  2926. }());
  2927. BABYLON.Path2 = Path2;
  2928. var Path3D = (function () {
  2929. /**
  2930. * new Path3D(path, normal, raw)
  2931. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2932. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2933. * path : an array of Vector3, the curve axis of the Path3D
  2934. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2935. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2936. */
  2937. function Path3D(path, firstNormal, raw) {
  2938. this.path = path;
  2939. this._curve = new Array();
  2940. this._distances = new Array();
  2941. this._tangents = new Array();
  2942. this._normals = new Array();
  2943. this._binormals = new Array();
  2944. for (var p = 0; p < path.length; p++) {
  2945. this._curve[p] = path[p].clone(); // hard copy
  2946. }
  2947. this._raw = raw || false;
  2948. this._compute(firstNormal);
  2949. }
  2950. /**
  2951. * Returns the Path3D array of successive Vector3 designing its curve.
  2952. */
  2953. Path3D.prototype.getCurve = function () {
  2954. return this._curve;
  2955. };
  2956. /**
  2957. * Returns an array populated with tangent vectors on each Path3D curve point.
  2958. */
  2959. Path3D.prototype.getTangents = function () {
  2960. return this._tangents;
  2961. };
  2962. /**
  2963. * Returns an array populated with normal vectors on each Path3D curve point.
  2964. */
  2965. Path3D.prototype.getNormals = function () {
  2966. return this._normals;
  2967. };
  2968. /**
  2969. * Returns an array populated with binormal vectors on each Path3D curve point.
  2970. */
  2971. Path3D.prototype.getBinormals = function () {
  2972. return this._binormals;
  2973. };
  2974. /**
  2975. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2976. */
  2977. Path3D.prototype.getDistances = function () {
  2978. return this._distances;
  2979. };
  2980. /**
  2981. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2982. * Returns the same object updated.
  2983. */
  2984. Path3D.prototype.update = function (path, firstNormal) {
  2985. for (var p = 0; p < path.length; p++) {
  2986. this._curve[p].x = path[p].x;
  2987. this._curve[p].y = path[p].y;
  2988. this._curve[p].z = path[p].z;
  2989. }
  2990. this._compute(firstNormal);
  2991. return this;
  2992. };
  2993. // private function compute() : computes tangents, normals and binormals
  2994. Path3D.prototype._compute = function (firstNormal) {
  2995. var l = this._curve.length;
  2996. // first and last tangents
  2997. this._tangents[0] = this._getFirstNonNullVector(0);
  2998. if (!this._raw) {
  2999. this._tangents[0].normalize();
  3000. }
  3001. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  3002. if (!this._raw) {
  3003. this._tangents[l - 1].normalize();
  3004. }
  3005. // normals and binormals at first point : arbitrary vector with _normalVector()
  3006. var tg0 = this._tangents[0];
  3007. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  3008. this._normals[0] = pp0;
  3009. if (!this._raw) {
  3010. this._normals[0].normalize();
  3011. }
  3012. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  3013. if (!this._raw) {
  3014. this._binormals[0].normalize();
  3015. }
  3016. this._distances[0] = 0.0;
  3017. // normals and binormals : next points
  3018. var prev; // previous vector (segment)
  3019. var cur; // current vector (segment)
  3020. var curTang; // current tangent
  3021. // previous normal
  3022. var prevBinor; // previous binormal
  3023. for (var i = 1; i < l; i++) {
  3024. // tangents
  3025. prev = this._getLastNonNullVector(i);
  3026. if (i < l - 1) {
  3027. cur = this._getFirstNonNullVector(i);
  3028. this._tangents[i] = prev.add(cur);
  3029. this._tangents[i].normalize();
  3030. }
  3031. this._distances[i] = this._distances[i - 1] + prev.length();
  3032. // normals and binormals
  3033. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  3034. curTang = this._tangents[i];
  3035. prevBinor = this._binormals[i - 1];
  3036. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  3037. if (!this._raw) {
  3038. this._normals[i].normalize();
  3039. }
  3040. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  3041. if (!this._raw) {
  3042. this._binormals[i].normalize();
  3043. }
  3044. }
  3045. };
  3046. // private function getFirstNonNullVector(index)
  3047. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  3048. Path3D.prototype._getFirstNonNullVector = function (index) {
  3049. var i = 1;
  3050. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  3051. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  3052. i++;
  3053. nNVector = this._curve[index + i].subtract(this._curve[index]);
  3054. }
  3055. return nNVector;
  3056. };
  3057. // private function getLastNonNullVector(index)
  3058. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3059. Path3D.prototype._getLastNonNullVector = function (index) {
  3060. var i = 1;
  3061. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3062. while (nLVector.length() === 0 && index > i + 1) {
  3063. i++;
  3064. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3065. }
  3066. return nLVector;
  3067. };
  3068. // private function normalVector(v0, vt, va) :
  3069. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3070. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3071. Path3D.prototype._normalVector = function (v0, vt, va) {
  3072. var normal0;
  3073. var tgl = vt.length();
  3074. if (tgl === 0.0) {
  3075. tgl = 1.0;
  3076. }
  3077. if (va === undefined || va === null) {
  3078. var point;
  3079. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3080. point = new Vector3(0.0, -1.0, 0.0);
  3081. }
  3082. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3083. point = new Vector3(1.0, 0.0, 0.0);
  3084. }
  3085. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3086. point = new Vector3(0.0, 0.0, 1.0);
  3087. }
  3088. normal0 = Vector3.Cross(vt, point);
  3089. }
  3090. else {
  3091. normal0 = Vector3.Cross(vt, va);
  3092. Vector3.CrossToRef(normal0, vt, normal0);
  3093. }
  3094. normal0.normalize();
  3095. return normal0;
  3096. };
  3097. return Path3D;
  3098. }());
  3099. BABYLON.Path3D = Path3D;
  3100. var Curve3 = (function () {
  3101. /**
  3102. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3103. * A Curve3 is designed from a series of successive Vector3.
  3104. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3105. */
  3106. function Curve3(points) {
  3107. this._length = 0.0;
  3108. this._points = points;
  3109. this._length = this._computeLength(points);
  3110. }
  3111. /**
  3112. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3113. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3114. * @param v1 (Vector3) the control point
  3115. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3116. * @param nbPoints (integer) the wanted number of points in the curve
  3117. */
  3118. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3119. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3120. var bez = new Array();
  3121. var equation = function (t, val0, val1, val2) {
  3122. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3123. return res;
  3124. };
  3125. for (var i = 0; i <= nbPoints; i++) {
  3126. 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)));
  3127. }
  3128. return new Curve3(bez);
  3129. };
  3130. /**
  3131. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3132. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3133. * @param v1 (Vector3) the first control point
  3134. * @param v2 (Vector3) the second control point
  3135. * @param v3 (Vector3) the end point of the Cubic Bezier
  3136. * @param nbPoints (integer) the wanted number of points in the curve
  3137. */
  3138. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3139. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3140. var bez = new Array();
  3141. var equation = function (t, val0, val1, val2, val3) {
  3142. 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;
  3143. return res;
  3144. };
  3145. for (var i = 0; i <= nbPoints; i++) {
  3146. 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)));
  3147. }
  3148. return new Curve3(bez);
  3149. };
  3150. /**
  3151. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3152. * @param p1 (Vector3) the origin point of the Hermite Spline
  3153. * @param t1 (Vector3) the tangent vector at the origin point
  3154. * @param p2 (Vector3) the end point of the Hermite Spline
  3155. * @param t2 (Vector3) the tangent vector at the end point
  3156. * @param nbPoints (integer) the wanted number of points in the curve
  3157. */
  3158. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3159. var hermite = new Array();
  3160. var step = 1.0 / nbPoints;
  3161. for (var i = 0; i <= nbPoints; i++) {
  3162. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3163. }
  3164. return new Curve3(hermite);
  3165. };
  3166. /**
  3167. * Returns the Curve3 stored array of successive Vector3
  3168. */
  3169. Curve3.prototype.getPoints = function () {
  3170. return this._points;
  3171. };
  3172. /**
  3173. * Returns the computed length (float) of the curve.
  3174. */
  3175. Curve3.prototype.length = function () {
  3176. return this._length;
  3177. };
  3178. /**
  3179. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3180. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3181. * curveA and curveB keep unchanged.
  3182. */
  3183. Curve3.prototype.continue = function (curve) {
  3184. var lastPoint = this._points[this._points.length - 1];
  3185. var continuedPoints = this._points.slice();
  3186. var curvePoints = curve.getPoints();
  3187. for (var i = 1; i < curvePoints.length; i++) {
  3188. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3189. }
  3190. var continuedCurve = new Curve3(continuedPoints);
  3191. return continuedCurve;
  3192. };
  3193. Curve3.prototype._computeLength = function (path) {
  3194. var l = 0;
  3195. for (var i = 1; i < path.length; i++) {
  3196. l += (path[i].subtract(path[i - 1])).length();
  3197. }
  3198. return l;
  3199. };
  3200. return Curve3;
  3201. }());
  3202. BABYLON.Curve3 = Curve3;
  3203. // SphericalHarmonics
  3204. var SphericalHarmonics = (function () {
  3205. function SphericalHarmonics() {
  3206. this.L00 = Vector3.Zero();
  3207. this.L1_1 = Vector3.Zero();
  3208. this.L10 = Vector3.Zero();
  3209. this.L11 = Vector3.Zero();
  3210. this.L2_2 = Vector3.Zero();
  3211. this.L2_1 = Vector3.Zero();
  3212. this.L20 = Vector3.Zero();
  3213. this.L21 = Vector3.Zero();
  3214. this.L22 = Vector3.Zero();
  3215. }
  3216. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3217. var colorVector = new Vector3(color.r, color.g, color.b);
  3218. var c = colorVector.scale(deltaSolidAngle);
  3219. this.L00 = this.L00.add(c.scale(0.282095));
  3220. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3221. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3222. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3223. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3224. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3225. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3226. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3227. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3228. };
  3229. SphericalHarmonics.prototype.scale = function (scale) {
  3230. this.L00 = this.L00.scale(scale);
  3231. this.L1_1 = this.L1_1.scale(scale);
  3232. this.L10 = this.L10.scale(scale);
  3233. this.L11 = this.L11.scale(scale);
  3234. this.L2_2 = this.L2_2.scale(scale);
  3235. this.L2_1 = this.L2_1.scale(scale);
  3236. this.L20 = this.L20.scale(scale);
  3237. this.L21 = this.L21.scale(scale);
  3238. this.L22 = this.L22.scale(scale);
  3239. };
  3240. return SphericalHarmonics;
  3241. }());
  3242. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3243. // SphericalPolynomial
  3244. var SphericalPolynomial = (function () {
  3245. function SphericalPolynomial() {
  3246. this.x = Vector3.Zero();
  3247. this.y = Vector3.Zero();
  3248. this.z = Vector3.Zero();
  3249. this.xx = Vector3.Zero();
  3250. this.yy = Vector3.Zero();
  3251. this.zz = Vector3.Zero();
  3252. this.xy = Vector3.Zero();
  3253. this.yz = Vector3.Zero();
  3254. this.zx = Vector3.Zero();
  3255. }
  3256. SphericalPolynomial.prototype.addAmbient = function (color) {
  3257. var colorVector = new Vector3(color.r, color.g, color.b);
  3258. this.xx = this.xx.add(colorVector);
  3259. this.yy = this.yy.add(colorVector);
  3260. this.zz = this.zz.add(colorVector);
  3261. };
  3262. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3263. var result = new SphericalPolynomial();
  3264. result.x = harmonics.L11.scale(1.02333);
  3265. result.y = harmonics.L1_1.scale(1.02333);
  3266. result.z = harmonics.L10.scale(1.02333);
  3267. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3268. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3269. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3270. result.yz = harmonics.L2_1.scale(0.858086);
  3271. result.zx = harmonics.L21.scale(0.858086);
  3272. result.xy = harmonics.L2_2.scale(0.858086);
  3273. return result;
  3274. };
  3275. return SphericalPolynomial;
  3276. }());
  3277. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3278. // Vertex formats
  3279. var PositionNormalVertex = (function () {
  3280. function PositionNormalVertex(position, normal) {
  3281. if (position === void 0) { position = Vector3.Zero(); }
  3282. if (normal === void 0) { normal = Vector3.Up(); }
  3283. this.position = position;
  3284. this.normal = normal;
  3285. }
  3286. PositionNormalVertex.prototype.clone = function () {
  3287. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3288. };
  3289. return PositionNormalVertex;
  3290. }());
  3291. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3292. var PositionNormalTextureVertex = (function () {
  3293. function PositionNormalTextureVertex(position, normal, uv) {
  3294. if (position === void 0) { position = Vector3.Zero(); }
  3295. if (normal === void 0) { normal = Vector3.Up(); }
  3296. if (uv === void 0) { uv = Vector2.Zero(); }
  3297. this.position = position;
  3298. this.normal = normal;
  3299. this.uv = uv;
  3300. }
  3301. PositionNormalTextureVertex.prototype.clone = function () {
  3302. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3303. };
  3304. return PositionNormalTextureVertex;
  3305. }());
  3306. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3307. // Temporary pre-allocated objects for engine internal use
  3308. // usage in any internal function :
  3309. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3310. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3311. var Tmp = (function () {
  3312. function Tmp() {
  3313. }
  3314. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3315. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3316. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3317. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3318. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3319. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3320. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3321. Matrix.Zero(), Matrix.Zero(),
  3322. Matrix.Zero(), Matrix.Zero(),
  3323. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3324. return Tmp;
  3325. }());
  3326. BABYLON.Tmp = Tmp;
  3327. })(BABYLON || (BABYLON = {}));
  3328. //# sourceMappingURL=babylon.math.js.map
  3329. //# sourceMappingURL=babylon.mixins.js.map
  3330. var BABYLON;
  3331. (function (BABYLON) {
  3332. function generateSerializableMember(type, sourceName) {
  3333. return function (target, propertyKey) {
  3334. if (!target.__serializableMembers) {
  3335. target.__serializableMembers = {};
  3336. }
  3337. if (!target.__serializableMembers[propertyKey]) {
  3338. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3339. }
  3340. };
  3341. }
  3342. function serialize(sourceName) {
  3343. return generateSerializableMember(0, sourceName); // value member
  3344. }
  3345. BABYLON.serialize = serialize;
  3346. function serializeAsTexture(sourceName) {
  3347. return generateSerializableMember(1, sourceName); // texture member
  3348. }
  3349. BABYLON.serializeAsTexture = serializeAsTexture;
  3350. function serializeAsColor3(sourceName) {
  3351. return generateSerializableMember(2, sourceName); // color3 member
  3352. }
  3353. BABYLON.serializeAsColor3 = serializeAsColor3;
  3354. function serializeAsFresnelParameters(sourceName) {
  3355. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3356. }
  3357. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3358. function serializeAsVector2(sourceName) {
  3359. return generateSerializableMember(4, sourceName); // vector2 member
  3360. }
  3361. BABYLON.serializeAsVector2 = serializeAsVector2;
  3362. function serializeAsVector3(sourceName) {
  3363. return generateSerializableMember(5, sourceName); // vector3 member
  3364. }
  3365. BABYLON.serializeAsVector3 = serializeAsVector3;
  3366. function serializeAsMeshReference(sourceName) {
  3367. return generateSerializableMember(6, sourceName); // mesh reference member
  3368. }
  3369. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3370. function serializeAsColorCurves(sourceName) {
  3371. return generateSerializableMember(7, sourceName); // color curves
  3372. }
  3373. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3374. var SerializationHelper = (function () {
  3375. function SerializationHelper() {
  3376. }
  3377. SerializationHelper.Serialize = function (entity, serializationObject) {
  3378. if (!serializationObject) {
  3379. serializationObject = {};
  3380. }
  3381. // Tags
  3382. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3383. // Properties
  3384. for (var property in entity.__serializableMembers) {
  3385. var propertyDescriptor = entity.__serializableMembers[property];
  3386. var targetPropertyName = propertyDescriptor.sourceName || property;
  3387. var propertyType = propertyDescriptor.type;
  3388. var sourceProperty = entity[property];
  3389. if (sourceProperty !== undefined && sourceProperty !== null) {
  3390. switch (propertyType) {
  3391. case 0:
  3392. serializationObject[targetPropertyName] = sourceProperty;
  3393. break;
  3394. case 1:
  3395. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3396. break;
  3397. case 2:
  3398. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3399. break;
  3400. case 3:
  3401. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3402. break;
  3403. case 4:
  3404. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3405. break;
  3406. case 5:
  3407. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3408. break;
  3409. case 6:
  3410. serializationObject[targetPropertyName] = sourceProperty.id;
  3411. break;
  3412. case 7:
  3413. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3414. break;
  3415. }
  3416. }
  3417. }
  3418. return serializationObject;
  3419. };
  3420. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3421. var destination = creationFunction();
  3422. // Tags
  3423. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3424. // Properties
  3425. for (var property in destination.__serializableMembers) {
  3426. var propertyDescriptor = destination.__serializableMembers[property];
  3427. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3428. var propertyType = propertyDescriptor.type;
  3429. if (sourceProperty !== undefined && sourceProperty !== null) {
  3430. switch (propertyType) {
  3431. case 0:
  3432. destination[property] = sourceProperty;
  3433. break;
  3434. case 1:
  3435. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3436. break;
  3437. case 2:
  3438. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3439. break;
  3440. case 3:
  3441. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3442. break;
  3443. case 4:
  3444. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3445. break;
  3446. case 5:
  3447. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3448. break;
  3449. case 6:
  3450. destination[property] = scene.getLastMeshByID(sourceProperty);
  3451. break;
  3452. case 7:
  3453. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3454. break;
  3455. }
  3456. }
  3457. }
  3458. return destination;
  3459. };
  3460. SerializationHelper.Clone = function (creationFunction, source) {
  3461. var destination = creationFunction();
  3462. // Tags
  3463. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3464. // Properties
  3465. for (var property in destination.__serializableMembers) {
  3466. var propertyDescriptor = destination.__serializableMembers[property];
  3467. var sourceProperty = source[property];
  3468. var propertyType = propertyDescriptor.type;
  3469. if (sourceProperty !== undefined && sourceProperty !== null) {
  3470. switch (propertyType) {
  3471. case 0: // Value
  3472. case 6:
  3473. destination[property] = sourceProperty;
  3474. break;
  3475. case 1: // Texture
  3476. case 2: // Color3
  3477. case 3: // FresnelParameters
  3478. case 4: // Vector2
  3479. case 5: // Vector3
  3480. case 7:
  3481. destination[property] = sourceProperty.clone();
  3482. break;
  3483. }
  3484. }
  3485. }
  3486. return destination;
  3487. };
  3488. return SerializationHelper;
  3489. }());
  3490. BABYLON.SerializationHelper = SerializationHelper;
  3491. })(BABYLON || (BABYLON = {}));
  3492. //# sourceMappingURL=babylon.decorators.js.map
  3493. var BABYLON;
  3494. (function (BABYLON) {
  3495. /**
  3496. * A class serves as a medium between the observable and its observers
  3497. */
  3498. var EventState = (function () {
  3499. /**
  3500. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3501. */
  3502. function EventState(mask, skipNextObservers) {
  3503. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3504. this.initalize(mask, skipNextObservers);
  3505. }
  3506. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3507. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3508. this.mask = mask;
  3509. this.skipNextObservers = skipNextObservers;
  3510. return this;
  3511. };
  3512. return EventState;
  3513. }());
  3514. BABYLON.EventState = EventState;
  3515. /**
  3516. * Represent an Observer registered to a given Observable object.
  3517. */
  3518. var Observer = (function () {
  3519. function Observer(callback, mask) {
  3520. this.callback = callback;
  3521. this.mask = mask;
  3522. }
  3523. return Observer;
  3524. }());
  3525. BABYLON.Observer = Observer;
  3526. /**
  3527. * The Observable class is a simple implementation of the Observable pattern.
  3528. * 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.
  3529. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3530. * 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).
  3531. * 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.
  3532. */
  3533. var Observable = (function () {
  3534. function Observable() {
  3535. this._observers = new Array();
  3536. this._eventState = new EventState(0);
  3537. }
  3538. /**
  3539. * Create a new Observer with the specified callback
  3540. * @param callback the callback that will be executed for that Observer
  3541. * @param mask the mask used to filter observers
  3542. * @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.
  3543. */
  3544. Observable.prototype.add = function (callback, mask, insertFirst) {
  3545. if (mask === void 0) { mask = -1; }
  3546. if (insertFirst === void 0) { insertFirst = false; }
  3547. if (!callback) {
  3548. return null;
  3549. }
  3550. var observer = new Observer(callback, mask);
  3551. if (insertFirst) {
  3552. this._observers.unshift(observer);
  3553. }
  3554. else {
  3555. this._observers.push(observer);
  3556. }
  3557. return observer;
  3558. };
  3559. /**
  3560. * Remove an Observer from the Observable object
  3561. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3562. */
  3563. Observable.prototype.remove = function (observer) {
  3564. var index = this._observers.indexOf(observer);
  3565. if (index !== -1) {
  3566. this._observers.splice(index, 1);
  3567. return true;
  3568. }
  3569. return false;
  3570. };
  3571. /**
  3572. * Remove a callback from the Observable object
  3573. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3574. */
  3575. Observable.prototype.removeCallback = function (callback) {
  3576. for (var index = 0; index < this._observers.length; index++) {
  3577. if (this._observers[index].callback === callback) {
  3578. this._observers.splice(index, 1);
  3579. return true;
  3580. }
  3581. }
  3582. return false;
  3583. };
  3584. /**
  3585. * Notify all Observers by calling their respective callback with the given data
  3586. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3587. * @param eventData
  3588. * @param mask
  3589. */
  3590. Observable.prototype.notifyObservers = function (eventData, mask) {
  3591. if (mask === void 0) { mask = -1; }
  3592. var state = this._eventState;
  3593. state.mask = mask;
  3594. state.skipNextObservers = false;
  3595. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3596. var obs = _a[_i];
  3597. if (obs.mask & mask) {
  3598. obs.callback(eventData, state);
  3599. }
  3600. if (state.skipNextObservers) {
  3601. return false;
  3602. }
  3603. }
  3604. return true;
  3605. };
  3606. /**
  3607. * return true is the Observable has at least one Observer registered
  3608. */
  3609. Observable.prototype.hasObservers = function () {
  3610. return this._observers.length > 0;
  3611. };
  3612. /**
  3613. * Clear the list of observers
  3614. */
  3615. Observable.prototype.clear = function () {
  3616. this._observers = new Array();
  3617. };
  3618. /**
  3619. * Clone the current observable
  3620. */
  3621. Observable.prototype.clone = function () {
  3622. var result = new Observable();
  3623. result._observers = this._observers.slice(0);
  3624. return result;
  3625. };
  3626. return Observable;
  3627. }());
  3628. BABYLON.Observable = Observable;
  3629. })(BABYLON || (BABYLON = {}));
  3630. //# sourceMappingURL=babylon.observable.js.map
  3631. var BABYLON;
  3632. (function (BABYLON) {
  3633. var Database = (function () {
  3634. function Database(urlToScene, callbackManifestChecked) {
  3635. // Handling various flavors of prefixed version of IndexedDB
  3636. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3637. this.callbackManifestChecked = callbackManifestChecked;
  3638. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3639. this.db = null;
  3640. this.enableSceneOffline = false;
  3641. this.enableTexturesOffline = false;
  3642. this.manifestVersionFound = 0;
  3643. this.mustUpdateRessources = false;
  3644. this.hasReachedQuota = false;
  3645. if (!Database.IDBStorageEnabled) {
  3646. this.callbackManifestChecked(true);
  3647. }
  3648. else {
  3649. this.checkManifestFile();
  3650. }
  3651. }
  3652. Database.prototype.checkManifestFile = function () {
  3653. var _this = this;
  3654. function noManifestFile() {
  3655. that.enableSceneOffline = false;
  3656. that.enableTexturesOffline = false;
  3657. that.callbackManifestChecked(false);
  3658. }
  3659. var that = this;
  3660. var timeStampUsed = false;
  3661. var manifestURL = this.currentSceneUrl + ".manifest";
  3662. var xhr = new XMLHttpRequest();
  3663. if (navigator.onLine) {
  3664. // Adding a timestamp to by-pass browsers' cache
  3665. timeStampUsed = true;
  3666. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3667. }
  3668. xhr.open("GET", manifestURL, true);
  3669. xhr.addEventListener("load", function () {
  3670. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3671. try {
  3672. var manifestFile = JSON.parse(xhr.response);
  3673. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3674. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3675. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3676. _this.manifestVersionFound = manifestFile.version;
  3677. }
  3678. if (_this.callbackManifestChecked) {
  3679. _this.callbackManifestChecked(true);
  3680. }
  3681. }
  3682. catch (ex) {
  3683. noManifestFile();
  3684. }
  3685. }
  3686. else {
  3687. noManifestFile();
  3688. }
  3689. }, false);
  3690. xhr.addEventListener("error", function (event) {
  3691. if (timeStampUsed) {
  3692. timeStampUsed = false;
  3693. // Let's retry without the timeStamp
  3694. // It could fail when coupled with HTML5 Offline API
  3695. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3696. xhr.open("GET", retryManifestURL, true);
  3697. xhr.send();
  3698. }
  3699. else {
  3700. noManifestFile();
  3701. }
  3702. }, false);
  3703. try {
  3704. xhr.send();
  3705. }
  3706. catch (ex) {
  3707. BABYLON.Tools.Error("Error on XHR send request.");
  3708. that.callbackManifestChecked(false);
  3709. }
  3710. };
  3711. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3712. var _this = this;
  3713. function handleError() {
  3714. that.isSupported = false;
  3715. if (errorCallback)
  3716. errorCallback();
  3717. }
  3718. var that = this;
  3719. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3720. // Your browser doesn't support IndexedDB
  3721. this.isSupported = false;
  3722. if (errorCallback)
  3723. errorCallback();
  3724. }
  3725. else {
  3726. // If the DB hasn't been opened or created yet
  3727. if (!this.db) {
  3728. this.hasReachedQuota = false;
  3729. this.isSupported = true;
  3730. var request = this.idbFactory.open("babylonjs", 1);
  3731. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3732. request.onerror = function (event) {
  3733. handleError();
  3734. };
  3735. // executes when a version change transaction cannot complete due to other active transactions
  3736. request.onblocked = function (event) {
  3737. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3738. handleError();
  3739. };
  3740. // DB has been opened successfully
  3741. request.onsuccess = function (event) {
  3742. _this.db = request.result;
  3743. successCallback();
  3744. };
  3745. // Initialization of the DB. Creating Scenes & Textures stores
  3746. request.onupgradeneeded = function (event) {
  3747. _this.db = (event.target).result;
  3748. try {
  3749. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3750. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3751. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3752. }
  3753. catch (ex) {
  3754. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3755. handleError();
  3756. }
  3757. };
  3758. }
  3759. else {
  3760. if (successCallback)
  3761. successCallback();
  3762. }
  3763. }
  3764. };
  3765. Database.prototype.loadImageFromDB = function (url, image) {
  3766. var _this = this;
  3767. var completeURL = Database.ReturnFullUrlLocation(url);
  3768. var saveAndLoadImage = function () {
  3769. if (!_this.hasReachedQuota && _this.db !== null) {
  3770. // the texture is not yet in the DB, let's try to save it
  3771. _this._saveImageIntoDBAsync(completeURL, image);
  3772. }
  3773. else {
  3774. image.src = url;
  3775. }
  3776. };
  3777. if (!this.mustUpdateRessources) {
  3778. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3779. }
  3780. else {
  3781. saveAndLoadImage();
  3782. }
  3783. };
  3784. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3785. if (this.isSupported && this.db !== null) {
  3786. var texture;
  3787. var transaction = this.db.transaction(["textures"]);
  3788. transaction.onabort = function (event) {
  3789. image.src = url;
  3790. };
  3791. transaction.oncomplete = function (event) {
  3792. var blobTextureURL;
  3793. if (texture) {
  3794. var URL = window.URL || window.webkitURL;
  3795. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3796. image.onerror = function () {
  3797. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3798. image.src = url;
  3799. };
  3800. image.src = blobTextureURL;
  3801. }
  3802. else {
  3803. notInDBCallback();
  3804. }
  3805. };
  3806. var getRequest = transaction.objectStore("textures").get(url);
  3807. getRequest.onsuccess = function (event) {
  3808. texture = (event.target).result;
  3809. };
  3810. getRequest.onerror = function (event) {
  3811. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3812. image.src = url;
  3813. };
  3814. }
  3815. else {
  3816. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3817. image.src = url;
  3818. }
  3819. };
  3820. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3821. var _this = this;
  3822. if (this.isSupported) {
  3823. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3824. var generateBlobUrl = function () {
  3825. var blobTextureURL;
  3826. if (blob) {
  3827. var URL = window.URL || window.webkitURL;
  3828. try {
  3829. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3830. }
  3831. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3832. catch (ex) {
  3833. blobTextureURL = URL.createObjectURL(blob);
  3834. }
  3835. }
  3836. image.src = blobTextureURL;
  3837. };
  3838. if (Database.IsUASupportingBlobStorage) {
  3839. var xhr = new XMLHttpRequest(), blob;
  3840. xhr.open("GET", url, true);
  3841. xhr.responseType = "blob";
  3842. xhr.addEventListener("load", function () {
  3843. if (xhr.status === 200) {
  3844. // Blob as response (XHR2)
  3845. blob = xhr.response;
  3846. var transaction = _this.db.transaction(["textures"], "readwrite");
  3847. // the transaction could abort because of a QuotaExceededError error
  3848. transaction.onabort = function (event) {
  3849. try {
  3850. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3851. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3852. _this.hasReachedQuota = true;
  3853. }
  3854. }
  3855. catch (ex) { }
  3856. generateBlobUrl();
  3857. };
  3858. transaction.oncomplete = function (event) {
  3859. generateBlobUrl();
  3860. };
  3861. var newTexture = { textureUrl: url, data: blob };
  3862. try {
  3863. // Put the blob into the dabase
  3864. var addRequest = transaction.objectStore("textures").put(newTexture);
  3865. addRequest.onsuccess = function (event) {
  3866. };
  3867. addRequest.onerror = function (event) {
  3868. generateBlobUrl();
  3869. };
  3870. }
  3871. catch (ex) {
  3872. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3873. if (ex.code === 25) {
  3874. Database.IsUASupportingBlobStorage = false;
  3875. }
  3876. image.src = url;
  3877. }
  3878. }
  3879. else {
  3880. image.src = url;
  3881. }
  3882. }, false);
  3883. xhr.addEventListener("error", function (event) {
  3884. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3885. image.src = url;
  3886. }, false);
  3887. xhr.send();
  3888. }
  3889. else {
  3890. image.src = url;
  3891. }
  3892. }
  3893. else {
  3894. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3895. image.src = url;
  3896. }
  3897. };
  3898. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3899. var _this = this;
  3900. var updateVersion = function (event) {
  3901. // the version is not yet in the DB or we need to update it
  3902. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3903. };
  3904. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3905. };
  3906. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3907. var _this = this;
  3908. if (this.isSupported) {
  3909. var version;
  3910. try {
  3911. var transaction = this.db.transaction(["versions"]);
  3912. transaction.oncomplete = function (event) {
  3913. if (version) {
  3914. // If the version in the JSON file is > than the version in DB
  3915. if (_this.manifestVersionFound > version.data) {
  3916. _this.mustUpdateRessources = true;
  3917. updateInDBCallback();
  3918. }
  3919. else {
  3920. callback(version.data);
  3921. }
  3922. }
  3923. else {
  3924. _this.mustUpdateRessources = true;
  3925. updateInDBCallback();
  3926. }
  3927. };
  3928. transaction.onabort = function (event) {
  3929. callback(-1);
  3930. };
  3931. var getRequest = transaction.objectStore("versions").get(url);
  3932. getRequest.onsuccess = function (event) {
  3933. version = (event.target).result;
  3934. };
  3935. getRequest.onerror = function (event) {
  3936. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3937. callback(-1);
  3938. };
  3939. }
  3940. catch (ex) {
  3941. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3942. callback(-1);
  3943. }
  3944. }
  3945. else {
  3946. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3947. callback(-1);
  3948. }
  3949. };
  3950. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3951. var _this = this;
  3952. if (this.isSupported && !this.hasReachedQuota) {
  3953. try {
  3954. // Open a transaction to the database
  3955. var transaction = this.db.transaction(["versions"], "readwrite");
  3956. // the transaction could abort because of a QuotaExceededError error
  3957. transaction.onabort = function (event) {
  3958. try {
  3959. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3960. _this.hasReachedQuota = true;
  3961. }
  3962. }
  3963. catch (ex) { }
  3964. callback(-1);
  3965. };
  3966. transaction.oncomplete = function (event) {
  3967. callback(_this.manifestVersionFound);
  3968. };
  3969. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3970. // Put the scene into the database
  3971. var addRequest = transaction.objectStore("versions").put(newVersion);
  3972. addRequest.onsuccess = function (event) {
  3973. };
  3974. addRequest.onerror = function (event) {
  3975. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3976. };
  3977. }
  3978. catch (ex) {
  3979. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3980. callback(-1);
  3981. }
  3982. }
  3983. else {
  3984. callback(-1);
  3985. }
  3986. };
  3987. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3988. var _this = this;
  3989. var completeUrl = Database.ReturnFullUrlLocation(url);
  3990. var saveAndLoadFile = function (event) {
  3991. // the scene is not yet in the DB, let's try to save it
  3992. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3993. };
  3994. this._checkVersionFromDB(completeUrl, function (version) {
  3995. if (version !== -1) {
  3996. if (!_this.mustUpdateRessources) {
  3997. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3998. }
  3999. else {
  4000. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  4001. }
  4002. }
  4003. else {
  4004. errorCallback();
  4005. }
  4006. });
  4007. };
  4008. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  4009. if (this.isSupported) {
  4010. var targetStore;
  4011. if (url.indexOf(".babylon") !== -1) {
  4012. targetStore = "scenes";
  4013. }
  4014. else {
  4015. targetStore = "textures";
  4016. }
  4017. var file;
  4018. var transaction = this.db.transaction([targetStore]);
  4019. transaction.oncomplete = function (event) {
  4020. if (file) {
  4021. callback(file.data);
  4022. }
  4023. else {
  4024. notInDBCallback();
  4025. }
  4026. };
  4027. transaction.onabort = function (event) {
  4028. notInDBCallback();
  4029. };
  4030. var getRequest = transaction.objectStore(targetStore).get(url);
  4031. getRequest.onsuccess = function (event) {
  4032. file = (event.target).result;
  4033. };
  4034. getRequest.onerror = function (event) {
  4035. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  4036. notInDBCallback();
  4037. };
  4038. }
  4039. else {
  4040. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4041. callback();
  4042. }
  4043. };
  4044. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  4045. var _this = this;
  4046. if (this.isSupported) {
  4047. var targetStore;
  4048. if (url.indexOf(".babylon") !== -1) {
  4049. targetStore = "scenes";
  4050. }
  4051. else {
  4052. targetStore = "textures";
  4053. }
  4054. // Create XHR
  4055. var xhr = new XMLHttpRequest(), fileData;
  4056. xhr.open("GET", url, true);
  4057. if (useArrayBuffer) {
  4058. xhr.responseType = "arraybuffer";
  4059. }
  4060. xhr.onprogress = progressCallback;
  4061. xhr.addEventListener("load", function () {
  4062. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4063. // Blob as response (XHR2)
  4064. //fileData = xhr.responseText;
  4065. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4066. if (!_this.hasReachedQuota) {
  4067. // Open a transaction to the database
  4068. var transaction = _this.db.transaction([targetStore], "readwrite");
  4069. // the transaction could abort because of a QuotaExceededError error
  4070. transaction.onabort = function (event) {
  4071. try {
  4072. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4073. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4074. _this.hasReachedQuota = true;
  4075. }
  4076. }
  4077. catch (ex) { }
  4078. callback(fileData);
  4079. };
  4080. transaction.oncomplete = function (event) {
  4081. callback(fileData);
  4082. };
  4083. var newFile;
  4084. if (targetStore === "scenes") {
  4085. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4086. }
  4087. else {
  4088. newFile = { textureUrl: url, data: fileData };
  4089. }
  4090. try {
  4091. // Put the scene into the database
  4092. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4093. addRequest.onsuccess = function (event) {
  4094. };
  4095. addRequest.onerror = function (event) {
  4096. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4097. };
  4098. }
  4099. catch (ex) {
  4100. callback(fileData);
  4101. }
  4102. }
  4103. else {
  4104. callback(fileData);
  4105. }
  4106. }
  4107. else {
  4108. callback();
  4109. }
  4110. }, false);
  4111. xhr.addEventListener("error", function (event) {
  4112. BABYLON.Tools.Error("error on XHR request.");
  4113. callback();
  4114. }, false);
  4115. xhr.send();
  4116. }
  4117. else {
  4118. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4119. callback();
  4120. }
  4121. };
  4122. Database.IsUASupportingBlobStorage = true;
  4123. Database.IDBStorageEnabled = true;
  4124. Database.parseURL = function (url) {
  4125. var a = document.createElement('a');
  4126. a.href = url;
  4127. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4128. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4129. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4130. return absLocation;
  4131. };
  4132. Database.ReturnFullUrlLocation = function (url) {
  4133. if (url.indexOf("http:/") === -1) {
  4134. return (Database.parseURL(window.location.href) + url);
  4135. }
  4136. else {
  4137. return url;
  4138. }
  4139. };
  4140. return Database;
  4141. }());
  4142. BABYLON.Database = Database;
  4143. })(BABYLON || (BABYLON = {}));
  4144. //# sourceMappingURL=babylon.database.js.map
  4145. var BABYLON;
  4146. (function (BABYLON) {
  4147. var Internals;
  4148. (function (Internals) {
  4149. /*
  4150. * Based on jsTGALoader - Javascript loader for TGA file
  4151. * By Vincent Thibault
  4152. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4153. */
  4154. var TGATools = (function () {
  4155. function TGATools() {
  4156. }
  4157. TGATools.GetTGAHeader = function (data) {
  4158. var offset = 0;
  4159. var header = {
  4160. id_length: data[offset++],
  4161. colormap_type: data[offset++],
  4162. image_type: data[offset++],
  4163. colormap_index: data[offset++] | data[offset++] << 8,
  4164. colormap_length: data[offset++] | data[offset++] << 8,
  4165. colormap_size: data[offset++],
  4166. origin: [
  4167. data[offset++] | data[offset++] << 8,
  4168. data[offset++] | data[offset++] << 8
  4169. ],
  4170. width: data[offset++] | data[offset++] << 8,
  4171. height: data[offset++] | data[offset++] << 8,
  4172. pixel_size: data[offset++],
  4173. flags: data[offset++]
  4174. };
  4175. return header;
  4176. };
  4177. TGATools.UploadContent = function (gl, data) {
  4178. // Not enough data to contain header ?
  4179. if (data.length < 19) {
  4180. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4181. return;
  4182. }
  4183. // Read Header
  4184. var offset = 18;
  4185. var header = TGATools.GetTGAHeader(data);
  4186. // Assume it's a valid Targa file.
  4187. if (header.id_length + offset > data.length) {
  4188. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4189. return;
  4190. }
  4191. // Skip not needed data
  4192. offset += header.id_length;
  4193. var use_rle = false;
  4194. var use_pal = false;
  4195. var use_rgb = false;
  4196. var use_grey = false;
  4197. // Get some informations.
  4198. switch (header.image_type) {
  4199. case TGATools._TYPE_RLE_INDEXED:
  4200. use_rle = true;
  4201. case TGATools._TYPE_INDEXED:
  4202. use_pal = true;
  4203. break;
  4204. case TGATools._TYPE_RLE_RGB:
  4205. use_rle = true;
  4206. case TGATools._TYPE_RGB:
  4207. use_rgb = true;
  4208. break;
  4209. case TGATools._TYPE_RLE_GREY:
  4210. use_rle = true;
  4211. case TGATools._TYPE_GREY:
  4212. use_grey = true;
  4213. break;
  4214. }
  4215. var pixel_data;
  4216. var numAlphaBits = header.flags & 0xf;
  4217. var pixel_size = header.pixel_size >> 3;
  4218. var pixel_total = header.width * header.height * pixel_size;
  4219. // Read palettes
  4220. var palettes;
  4221. if (use_pal) {
  4222. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4223. }
  4224. // Read LRE
  4225. if (use_rle) {
  4226. pixel_data = new Uint8Array(pixel_total);
  4227. var c, count, i;
  4228. var localOffset = 0;
  4229. var pixels = new Uint8Array(pixel_size);
  4230. while (offset < pixel_total && localOffset < pixel_total) {
  4231. c = data[offset++];
  4232. count = (c & 0x7f) + 1;
  4233. // RLE pixels
  4234. if (c & 0x80) {
  4235. // Bind pixel tmp array
  4236. for (i = 0; i < pixel_size; ++i) {
  4237. pixels[i] = data[offset++];
  4238. }
  4239. // Copy pixel array
  4240. for (i = 0; i < count; ++i) {
  4241. pixel_data.set(pixels, localOffset + i * pixel_size);
  4242. }
  4243. localOffset += pixel_size * count;
  4244. }
  4245. else {
  4246. count *= pixel_size;
  4247. for (i = 0; i < count; ++i) {
  4248. pixel_data[localOffset + i] = data[offset++];
  4249. }
  4250. localOffset += count;
  4251. }
  4252. }
  4253. }
  4254. else {
  4255. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4256. }
  4257. // Load to texture
  4258. var x_start, y_start, x_step, y_step, y_end, x_end;
  4259. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4260. default:
  4261. case TGATools._ORIGIN_UL:
  4262. x_start = 0;
  4263. x_step = 1;
  4264. x_end = header.width;
  4265. y_start = 0;
  4266. y_step = 1;
  4267. y_end = header.height;
  4268. break;
  4269. case TGATools._ORIGIN_BL:
  4270. x_start = 0;
  4271. x_step = 1;
  4272. x_end = header.width;
  4273. y_start = header.height - 1;
  4274. y_step = -1;
  4275. y_end = -1;
  4276. break;
  4277. case TGATools._ORIGIN_UR:
  4278. x_start = header.width - 1;
  4279. x_step = -1;
  4280. x_end = -1;
  4281. y_start = 0;
  4282. y_step = 1;
  4283. y_end = header.height;
  4284. break;
  4285. case TGATools._ORIGIN_BR:
  4286. x_start = header.width - 1;
  4287. x_step = -1;
  4288. x_end = -1;
  4289. y_start = header.height - 1;
  4290. y_step = -1;
  4291. y_end = -1;
  4292. break;
  4293. }
  4294. // Load the specify method
  4295. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4296. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4297. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4298. };
  4299. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4300. var image = pixel_data, colormap = palettes;
  4301. var width = header.width, height = header.height;
  4302. var color, i = 0, x, y;
  4303. var imageData = new Uint8Array(width * height * 4);
  4304. for (y = y_start; y !== y_end; y += y_step) {
  4305. for (x = x_start; x !== x_end; x += x_step, i++) {
  4306. color = image[i];
  4307. imageData[(x + width * y) * 4 + 3] = 255;
  4308. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4309. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4310. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4311. }
  4312. }
  4313. return imageData;
  4314. };
  4315. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4316. var image = pixel_data;
  4317. var width = header.width, height = header.height;
  4318. var color, i = 0, x, y;
  4319. var imageData = new Uint8Array(width * height * 4);
  4320. for (y = y_start; y !== y_end; y += y_step) {
  4321. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4322. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4323. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4324. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4325. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4326. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4327. }
  4328. }
  4329. return imageData;
  4330. };
  4331. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4332. var image = pixel_data;
  4333. var width = header.width, height = header.height;
  4334. var i = 0, x, y;
  4335. var imageData = new Uint8Array(width * height * 4);
  4336. for (y = y_start; y !== y_end; y += y_step) {
  4337. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4338. imageData[(x + width * y) * 4 + 3] = 255;
  4339. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4340. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4341. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4342. }
  4343. }
  4344. return imageData;
  4345. };
  4346. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4347. var image = pixel_data;
  4348. var width = header.width, height = header.height;
  4349. var i = 0, x, y;
  4350. var imageData = new Uint8Array(width * height * 4);
  4351. for (y = y_start; y !== y_end; y += y_step) {
  4352. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4353. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4354. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4355. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4356. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4357. }
  4358. }
  4359. return imageData;
  4360. };
  4361. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4362. var image = pixel_data;
  4363. var width = header.width, height = header.height;
  4364. var color, i = 0, x, y;
  4365. var imageData = new Uint8Array(width * height * 4);
  4366. for (y = y_start; y !== y_end; y += y_step) {
  4367. for (x = x_start; x !== x_end; x += x_step, i++) {
  4368. color = image[i];
  4369. imageData[(x + width * y) * 4 + 0] = color;
  4370. imageData[(x + width * y) * 4 + 1] = color;
  4371. imageData[(x + width * y) * 4 + 2] = color;
  4372. imageData[(x + width * y) * 4 + 3] = 255;
  4373. }
  4374. }
  4375. return imageData;
  4376. };
  4377. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4378. var image = pixel_data;
  4379. var width = header.width, height = header.height;
  4380. var i = 0, x, y;
  4381. var imageData = new Uint8Array(width * height * 4);
  4382. for (y = y_start; y !== y_end; y += y_step) {
  4383. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4384. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4385. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4386. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4387. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4388. }
  4389. }
  4390. return imageData;
  4391. };
  4392. TGATools._TYPE_NO_DATA = 0;
  4393. TGATools._TYPE_INDEXED = 1;
  4394. TGATools._TYPE_RGB = 2;
  4395. TGATools._TYPE_GREY = 3;
  4396. TGATools._TYPE_RLE_INDEXED = 9;
  4397. TGATools._TYPE_RLE_RGB = 10;
  4398. TGATools._TYPE_RLE_GREY = 11;
  4399. TGATools._ORIGIN_MASK = 0x30;
  4400. TGATools._ORIGIN_SHIFT = 0x04;
  4401. TGATools._ORIGIN_BL = 0x00;
  4402. TGATools._ORIGIN_BR = 0x01;
  4403. TGATools._ORIGIN_UL = 0x02;
  4404. TGATools._ORIGIN_UR = 0x03;
  4405. return TGATools;
  4406. }());
  4407. Internals.TGATools = TGATools;
  4408. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4409. })(BABYLON || (BABYLON = {}));
  4410. //# sourceMappingURL=babylon.tools.tga.js.map
  4411. var BABYLON;
  4412. (function (BABYLON) {
  4413. var SmartArray = (function () {
  4414. function SmartArray(capacity) {
  4415. this.length = 0;
  4416. this._duplicateId = 0;
  4417. this.data = new Array(capacity);
  4418. this._id = SmartArray._GlobalId++;
  4419. }
  4420. SmartArray.prototype.push = function (value) {
  4421. this.data[this.length++] = value;
  4422. if (this.length > this.data.length) {
  4423. this.data.length *= 2;
  4424. }
  4425. if (!value.__smartArrayFlags) {
  4426. value.__smartArrayFlags = {};
  4427. }
  4428. value.__smartArrayFlags[this._id] = this._duplicateId;
  4429. };
  4430. SmartArray.prototype.pushNoDuplicate = function (value) {
  4431. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4432. return false;
  4433. }
  4434. this.push(value);
  4435. return true;
  4436. };
  4437. SmartArray.prototype.sort = function (compareFn) {
  4438. this.data.sort(compareFn);
  4439. };
  4440. SmartArray.prototype.reset = function () {
  4441. this.length = 0;
  4442. this._duplicateId++;
  4443. };
  4444. SmartArray.prototype.concat = function (array) {
  4445. if (array.length === 0) {
  4446. return;
  4447. }
  4448. if (this.length + array.length > this.data.length) {
  4449. this.data.length = (this.length + array.length) * 2;
  4450. }
  4451. for (var index = 0; index < array.length; index++) {
  4452. this.data[this.length++] = (array.data || array)[index];
  4453. }
  4454. };
  4455. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4456. if (array.length === 0) {
  4457. return;
  4458. }
  4459. if (this.length + array.length > this.data.length) {
  4460. this.data.length = (this.length + array.length) * 2;
  4461. }
  4462. for (var index = 0; index < array.length; index++) {
  4463. var item = (array.data || array)[index];
  4464. this.pushNoDuplicate(item);
  4465. }
  4466. };
  4467. SmartArray.prototype.indexOf = function (value) {
  4468. var position = this.data.indexOf(value);
  4469. if (position >= this.length) {
  4470. return -1;
  4471. }
  4472. return position;
  4473. };
  4474. // Statics
  4475. SmartArray._GlobalId = 0;
  4476. return SmartArray;
  4477. }());
  4478. BABYLON.SmartArray = SmartArray;
  4479. })(BABYLON || (BABYLON = {}));
  4480. //# sourceMappingURL=babylon.smartArray.js.map
  4481. var BABYLON;
  4482. (function (BABYLON) {
  4483. /**
  4484. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4485. * The underlying implementation relies on an associative array to ensure the best performances.
  4486. * The value can be anything including 'null' but except 'undefined'
  4487. */
  4488. var StringDictionary = (function () {
  4489. function StringDictionary() {
  4490. this._count = 0;
  4491. this._data = {};
  4492. }
  4493. /**
  4494. * This will clear this dictionary and copy the content from the 'source' one.
  4495. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4496. * @param source the dictionary to take the content from and copy to this dictionary
  4497. */
  4498. StringDictionary.prototype.copyFrom = function (source) {
  4499. var _this = this;
  4500. this.clear();
  4501. source.forEach(function (t, v) { return _this.add(t, v); });
  4502. };
  4503. /**
  4504. * Get a value based from its key
  4505. * @param key the given key to get the matching value from
  4506. * @return the value if found, otherwise undefined is returned
  4507. */
  4508. StringDictionary.prototype.get = function (key) {
  4509. var val = this._data[key];
  4510. if (val !== undefined) {
  4511. return val;
  4512. }
  4513. return undefined;
  4514. };
  4515. /**
  4516. * Get a value from its key or add it if it doesn't exist.
  4517. * This method will ensure you that a given key/data will be present in the dictionary.
  4518. * @param key the given key to get the matching value from
  4519. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4520. * The factory will only be invoked if there's no data for the given key.
  4521. * @return the value corresponding to the key.
  4522. */
  4523. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4524. var val = this.get(key);
  4525. if (val !== undefined) {
  4526. return val;
  4527. }
  4528. val = factory(key);
  4529. if (val) {
  4530. this.add(key, val);
  4531. }
  4532. return val;
  4533. };
  4534. /**
  4535. * Get a value from its key if present in the dictionary otherwise add it
  4536. * @param key the key to get the value from
  4537. * @param val if there's no such key/value pair in the dictionary add it with this value
  4538. * @return the value corresponding to the key
  4539. */
  4540. StringDictionary.prototype.getOrAdd = function (key, val) {
  4541. var curVal = this.get(key);
  4542. if (curVal !== undefined) {
  4543. return curVal;
  4544. }
  4545. this.add(key, val);
  4546. return val;
  4547. };
  4548. /**
  4549. * Check if there's a given key in the dictionary
  4550. * @param key the key to check for
  4551. * @return true if the key is present, false otherwise
  4552. */
  4553. StringDictionary.prototype.contains = function (key) {
  4554. return this._data[key] !== undefined;
  4555. };
  4556. /**
  4557. * Add a new key and its corresponding value
  4558. * @param key the key to add
  4559. * @param value the value corresponding to the key
  4560. * @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
  4561. */
  4562. StringDictionary.prototype.add = function (key, value) {
  4563. if (this._data[key] !== undefined) {
  4564. return false;
  4565. }
  4566. this._data[key] = value;
  4567. ++this._count;
  4568. return true;
  4569. };
  4570. StringDictionary.prototype.set = function (key, value) {
  4571. if (this._data[key] === undefined) {
  4572. return false;
  4573. }
  4574. this._data[key] = value;
  4575. return true;
  4576. };
  4577. /**
  4578. * Get the element of the given key and remove it from the dictionary
  4579. * @param key
  4580. */
  4581. StringDictionary.prototype.getAndRemove = function (key) {
  4582. var val = this.get(key);
  4583. if (val !== undefined) {
  4584. delete this._data[key];
  4585. --this._count;
  4586. return val;
  4587. }
  4588. return null;
  4589. };
  4590. /**
  4591. * Remove a key/value from the dictionary.
  4592. * @param key the key to remove
  4593. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4594. */
  4595. StringDictionary.prototype.remove = function (key) {
  4596. if (this.contains(key)) {
  4597. delete this._data[key];
  4598. --this._count;
  4599. return true;
  4600. }
  4601. return false;
  4602. };
  4603. /**
  4604. * Clear the whole content of the dictionary
  4605. */
  4606. StringDictionary.prototype.clear = function () {
  4607. this._data = {};
  4608. this._count = 0;
  4609. };
  4610. Object.defineProperty(StringDictionary.prototype, "count", {
  4611. get: function () {
  4612. return this._count;
  4613. },
  4614. enumerable: true,
  4615. configurable: true
  4616. });
  4617. /**
  4618. * Execute a callback on each key/val of the dictionary.
  4619. * Note that you can remove any element in this dictionary in the callback implementation
  4620. * @param callback the callback to execute on a given key/value pair
  4621. */
  4622. StringDictionary.prototype.forEach = function (callback) {
  4623. for (var cur in this._data) {
  4624. var val = this._data[cur];
  4625. callback(cur, val);
  4626. }
  4627. };
  4628. /**
  4629. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4630. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4631. * Note that you can remove any element in this dictionary in the callback implementation
  4632. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4633. */
  4634. StringDictionary.prototype.first = function (callback) {
  4635. for (var cur in this._data) {
  4636. var val = this._data[cur];
  4637. var res = callback(cur, val);
  4638. if (res) {
  4639. return res;
  4640. }
  4641. }
  4642. return null;
  4643. };
  4644. return StringDictionary;
  4645. }());
  4646. BABYLON.StringDictionary = StringDictionary;
  4647. })(BABYLON || (BABYLON = {}));
  4648. //# sourceMappingURL=babylon.stringDictionary.js.map
  4649. var BABYLON;
  4650. (function (BABYLON) {
  4651. // Screenshots
  4652. var screenshotCanvas;
  4653. var cloneValue = function (source, destinationObject) {
  4654. if (!source)
  4655. return null;
  4656. if (source instanceof BABYLON.Mesh) {
  4657. return null;
  4658. }
  4659. if (source instanceof BABYLON.SubMesh) {
  4660. return source.clone(destinationObject);
  4661. }
  4662. else if (source.clone) {
  4663. return source.clone();
  4664. }
  4665. return null;
  4666. };
  4667. var Tools = (function () {
  4668. function Tools() {
  4669. }
  4670. Tools.Instantiate = function (className) {
  4671. var arr = className.split(".");
  4672. var fn = (window || this);
  4673. for (var i = 0, len = arr.length; i < len; i++) {
  4674. fn = fn[arr[i]];
  4675. }
  4676. if (typeof fn !== "function") {
  4677. return null;
  4678. }
  4679. return fn;
  4680. };
  4681. Tools.SetImmediate = function (action) {
  4682. if (window.setImmediate) {
  4683. window.setImmediate(action);
  4684. }
  4685. else {
  4686. setTimeout(action, 1);
  4687. }
  4688. };
  4689. Tools.IsExponentOfTwo = function (value) {
  4690. var count = 1;
  4691. do {
  4692. count *= 2;
  4693. } while (count < value);
  4694. return count === value;
  4695. };
  4696. Tools.GetExponentOfTwo = function (value, max) {
  4697. var count = 1;
  4698. do {
  4699. count *= 2;
  4700. } while (count < value);
  4701. if (count > max)
  4702. count = max;
  4703. return count;
  4704. };
  4705. Tools.GetFilename = function (path) {
  4706. var index = path.lastIndexOf("/");
  4707. if (index < 0)
  4708. return path;
  4709. return path.substring(index + 1);
  4710. };
  4711. Tools.GetDOMTextContent = function (element) {
  4712. var result = "";
  4713. var child = element.firstChild;
  4714. while (child) {
  4715. if (child.nodeType === 3) {
  4716. result += child.textContent;
  4717. }
  4718. child = child.nextSibling;
  4719. }
  4720. return result;
  4721. };
  4722. Tools.ToDegrees = function (angle) {
  4723. return angle * 180 / Math.PI;
  4724. };
  4725. Tools.ToRadians = function (angle) {
  4726. return angle * Math.PI / 180;
  4727. };
  4728. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4729. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4730. var output = "";
  4731. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4732. var i = 0;
  4733. var bytes = new Uint8Array(buffer);
  4734. while (i < bytes.length) {
  4735. chr1 = bytes[i++];
  4736. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4737. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4738. enc1 = chr1 >> 2;
  4739. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4740. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4741. enc4 = chr3 & 63;
  4742. if (isNaN(chr2)) {
  4743. enc3 = enc4 = 64;
  4744. }
  4745. else if (isNaN(chr3)) {
  4746. enc4 = 64;
  4747. }
  4748. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4749. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4750. }
  4751. return "data:image/png;base64," + output;
  4752. };
  4753. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4754. if (bias === void 0) { bias = null; }
  4755. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4756. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4757. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4758. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4759. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4760. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4761. }
  4762. if (bias) {
  4763. minimum.x -= minimum.x * bias.x + bias.y;
  4764. minimum.y -= minimum.y * bias.x + bias.y;
  4765. minimum.z -= minimum.z * bias.x + bias.y;
  4766. maximum.x += maximum.x * bias.x + bias.y;
  4767. maximum.y += maximum.y * bias.x + bias.y;
  4768. maximum.z += maximum.z * bias.x + bias.y;
  4769. }
  4770. return {
  4771. minimum: minimum,
  4772. maximum: maximum
  4773. };
  4774. };
  4775. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4776. if (bias === void 0) { bias = null; }
  4777. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4778. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4779. if (!stride) {
  4780. stride = 3;
  4781. }
  4782. for (var index = start; index < start + count; index++) {
  4783. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4784. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4785. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4786. }
  4787. if (bias) {
  4788. minimum.x -= minimum.x * bias.x + bias.y;
  4789. minimum.y -= minimum.y * bias.x + bias.y;
  4790. minimum.z -= minimum.z * bias.x + bias.y;
  4791. maximum.x += maximum.x * bias.x + bias.y;
  4792. maximum.y += maximum.y * bias.x + bias.y;
  4793. maximum.z += maximum.z * bias.x + bias.y;
  4794. }
  4795. return {
  4796. minimum: minimum,
  4797. maximum: maximum
  4798. };
  4799. };
  4800. Tools.Vector2ArrayFeeder = function (array) {
  4801. return function (index) {
  4802. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4803. var length = isFloatArray ? array.length / 2 : array.length;
  4804. if (index >= length) {
  4805. return null;
  4806. }
  4807. if (isFloatArray) {
  4808. var fa = array;
  4809. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4810. }
  4811. var a = array;
  4812. return a[index];
  4813. };
  4814. };
  4815. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4816. if (bias === void 0) { bias = null; }
  4817. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4818. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4819. var i = 0;
  4820. var cur = feeder(i++);
  4821. while (cur) {
  4822. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4823. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4824. cur = feeder(i++);
  4825. }
  4826. if (bias) {
  4827. minimum.x -= minimum.x * bias.x + bias.y;
  4828. minimum.y -= minimum.y * bias.x + bias.y;
  4829. maximum.x += maximum.x * bias.x + bias.y;
  4830. maximum.y += maximum.y * bias.x + bias.y;
  4831. }
  4832. return {
  4833. minimum: minimum,
  4834. maximum: maximum
  4835. };
  4836. };
  4837. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4838. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4839. return undefined;
  4840. return Array.isArray(obj) ? obj : [obj];
  4841. };
  4842. // Misc.
  4843. Tools.GetPointerPrefix = function () {
  4844. var eventPrefix = "pointer";
  4845. // Check if pointer events are supported
  4846. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4847. eventPrefix = "mouse";
  4848. }
  4849. return eventPrefix;
  4850. };
  4851. /**
  4852. * @param func - the function to be called
  4853. * @param requester - the object that will request the next frame. Falls back to window.
  4854. */
  4855. Tools.QueueNewFrame = function (func, requester) {
  4856. if (requester === void 0) { requester = window; }
  4857. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4858. /*if(requester.isPresenting) {
  4859. return;
  4860. } else*/ if (requester.requestAnimationFrame)
  4861. requester.requestAnimationFrame(func);
  4862. else if (requester.msRequestAnimationFrame)
  4863. requester.msRequestAnimationFrame(func);
  4864. else if (requester.webkitRequestAnimationFrame)
  4865. requester.webkitRequestAnimationFrame(func);
  4866. else if (requester.mozRequestAnimationFrame)
  4867. requester.mozRequestAnimationFrame(func);
  4868. else if (requester.oRequestAnimationFrame)
  4869. requester.oRequestAnimationFrame(func);
  4870. else {
  4871. window.setTimeout(func, 16);
  4872. }
  4873. };
  4874. Tools.RequestFullscreen = function (element) {
  4875. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4876. if (!requestFunction)
  4877. return;
  4878. requestFunction.call(element);
  4879. };
  4880. Tools.ExitFullscreen = function () {
  4881. if (document.exitFullscreen) {
  4882. document.exitFullscreen();
  4883. }
  4884. else if (document.mozCancelFullScreen) {
  4885. document.mozCancelFullScreen();
  4886. }
  4887. else if (document.webkitCancelFullScreen) {
  4888. document.webkitCancelFullScreen();
  4889. }
  4890. else if (document.msCancelFullScreen) {
  4891. document.msCancelFullScreen();
  4892. }
  4893. };
  4894. Tools.SetCorsBehavior = function (url, img) {
  4895. if (Tools.CorsBehavior) {
  4896. switch (typeof (Tools.CorsBehavior)) {
  4897. case "function":
  4898. var result = Tools.CorsBehavior(url);
  4899. if (result) {
  4900. return result;
  4901. }
  4902. break;
  4903. case "string":
  4904. default:
  4905. img.crossOrigin = Tools.CorsBehavior;
  4906. break;
  4907. }
  4908. }
  4909. };
  4910. // External files
  4911. Tools.CleanUrl = function (url) {
  4912. url = url.replace(/#/mg, "%23");
  4913. return url;
  4914. };
  4915. Tools.LoadImage = function (url, onload, onerror, database) {
  4916. if (url instanceof ArrayBuffer) {
  4917. url = Tools.EncodeArrayBufferTobase64(url);
  4918. }
  4919. url = Tools.CleanUrl(url);
  4920. var img = new Image();
  4921. if (url.substr(0, 5) !== "data:") {
  4922. Tools.SetCorsBehavior(url, img);
  4923. }
  4924. img.onload = function () {
  4925. onload(img);
  4926. };
  4927. img.onerror = function (err) {
  4928. Tools.Error("Error while trying to load texture: " + url);
  4929. if (Tools.UseFallbackTexture) {
  4930. 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";
  4931. onload(img);
  4932. }
  4933. else {
  4934. onerror();
  4935. }
  4936. };
  4937. var noIndexedDB = function () {
  4938. img.src = url;
  4939. };
  4940. var loadFromIndexedDB = function () {
  4941. database.loadImageFromDB(url, img);
  4942. };
  4943. //ANY database to do!
  4944. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4945. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4946. }
  4947. else {
  4948. if (url.indexOf("file:") === -1) {
  4949. noIndexedDB();
  4950. }
  4951. else {
  4952. try {
  4953. var textureName = url.substring(5).toLowerCase();
  4954. var blobURL;
  4955. try {
  4956. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4957. }
  4958. catch (ex) {
  4959. // Chrome doesn't support oneTimeOnly parameter
  4960. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4961. }
  4962. img.src = blobURL;
  4963. }
  4964. catch (e) {
  4965. img.src = null;
  4966. }
  4967. }
  4968. }
  4969. return img;
  4970. };
  4971. //ANY
  4972. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4973. url = Tools.CleanUrl(url);
  4974. var noIndexedDB = function () {
  4975. var request = new XMLHttpRequest();
  4976. var loadUrl = Tools.BaseUrl + url;
  4977. request.open('GET', loadUrl, true);
  4978. if (useArrayBuffer) {
  4979. request.responseType = "arraybuffer";
  4980. }
  4981. request.onprogress = progressCallBack;
  4982. request.onreadystatechange = function () {
  4983. if (request.readyState === 4) {
  4984. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4985. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4986. callback(!useArrayBuffer ? request.responseText : request.response);
  4987. }
  4988. else {
  4989. if (onError) {
  4990. onError();
  4991. }
  4992. else {
  4993. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4994. }
  4995. }
  4996. }
  4997. };
  4998. request.send(null);
  4999. };
  5000. var loadFromIndexedDB = function () {
  5001. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5002. };
  5003. if (url.indexOf("file:") !== -1) {
  5004. var fileName = url.substring(5).toLowerCase();
  5005. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5006. }
  5007. else {
  5008. // Caching all files
  5009. if (database && database.enableSceneOffline) {
  5010. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5011. }
  5012. else {
  5013. noIndexedDB();
  5014. }
  5015. }
  5016. };
  5017. /**
  5018. * Load a script (identified by an url). When the url returns, the
  5019. * content of this file is added into a new script element, attached to the DOM (body element)
  5020. */
  5021. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5022. var head = document.getElementsByTagName('head')[0];
  5023. var script = document.createElement('script');
  5024. script.type = 'text/javascript';
  5025. script.src = scriptUrl;
  5026. var self = this;
  5027. script.onload = function () {
  5028. if (onSuccess) {
  5029. onSuccess();
  5030. }
  5031. };
  5032. script.onerror = function () {
  5033. if (onError) {
  5034. onError();
  5035. }
  5036. };
  5037. head.appendChild(script);
  5038. };
  5039. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5040. var reader = new FileReader();
  5041. reader.onload = function (e) {
  5042. //target doesn't have result from ts 1.3
  5043. callback(e.target['result']);
  5044. };
  5045. reader.onprogress = progressCallback;
  5046. reader.readAsDataURL(fileToLoad);
  5047. };
  5048. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5049. var reader = new FileReader();
  5050. reader.onerror = function (e) {
  5051. Tools.Log("Error while reading file: " + fileToLoad.name);
  5052. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5053. };
  5054. reader.onload = function (e) {
  5055. //target doesn't have result from ts 1.3
  5056. callback(e.target['result']);
  5057. };
  5058. reader.onprogress = progressCallBack;
  5059. if (!useArrayBuffer) {
  5060. // Asynchronous read
  5061. reader.readAsText(fileToLoad);
  5062. }
  5063. else {
  5064. reader.readAsArrayBuffer(fileToLoad);
  5065. }
  5066. };
  5067. //returns a downloadable url to a file content.
  5068. Tools.FileAsURL = function (content) {
  5069. var fileBlob = new Blob([content]);
  5070. var url = window.URL || window.webkitURL;
  5071. var link = url.createObjectURL(fileBlob);
  5072. return link;
  5073. };
  5074. // Misc.
  5075. Tools.Format = function (value, decimals) {
  5076. if (decimals === void 0) { decimals = 2; }
  5077. return value.toFixed(decimals);
  5078. };
  5079. Tools.CheckExtends = function (v, min, max) {
  5080. if (v.x < min.x)
  5081. min.x = v.x;
  5082. if (v.y < min.y)
  5083. min.y = v.y;
  5084. if (v.z < min.z)
  5085. min.z = v.z;
  5086. if (v.x > max.x)
  5087. max.x = v.x;
  5088. if (v.y > max.y)
  5089. max.y = v.y;
  5090. if (v.z > max.z)
  5091. max.z = v.z;
  5092. };
  5093. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5094. for (var prop in source) {
  5095. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5096. continue;
  5097. }
  5098. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5099. continue;
  5100. }
  5101. var sourceValue = source[prop];
  5102. var typeOfSourceValue = typeof sourceValue;
  5103. if (typeOfSourceValue === "function") {
  5104. continue;
  5105. }
  5106. if (typeOfSourceValue === "object") {
  5107. if (sourceValue instanceof Array) {
  5108. destination[prop] = [];
  5109. if (sourceValue.length > 0) {
  5110. if (typeof sourceValue[0] == "object") {
  5111. for (var index = 0; index < sourceValue.length; index++) {
  5112. var clonedValue = cloneValue(sourceValue[index], destination);
  5113. if (destination[prop].indexOf(clonedValue) === -1) {
  5114. destination[prop].push(clonedValue);
  5115. }
  5116. }
  5117. }
  5118. else {
  5119. destination[prop] = sourceValue.slice(0);
  5120. }
  5121. }
  5122. }
  5123. else {
  5124. destination[prop] = cloneValue(sourceValue, destination);
  5125. }
  5126. }
  5127. else {
  5128. destination[prop] = sourceValue;
  5129. }
  5130. }
  5131. };
  5132. Tools.IsEmpty = function (obj) {
  5133. for (var i in obj) {
  5134. return false;
  5135. }
  5136. return true;
  5137. };
  5138. Tools.RegisterTopRootEvents = function (events) {
  5139. for (var index = 0; index < events.length; index++) {
  5140. var event = events[index];
  5141. window.addEventListener(event.name, event.handler, false);
  5142. try {
  5143. if (window.parent) {
  5144. window.parent.addEventListener(event.name, event.handler, false);
  5145. }
  5146. }
  5147. catch (e) {
  5148. }
  5149. }
  5150. };
  5151. Tools.UnregisterTopRootEvents = function (events) {
  5152. for (var index = 0; index < events.length; index++) {
  5153. var event = events[index];
  5154. window.removeEventListener(event.name, event.handler);
  5155. try {
  5156. if (window.parent) {
  5157. window.parent.removeEventListener(event.name, event.handler);
  5158. }
  5159. }
  5160. catch (e) {
  5161. }
  5162. }
  5163. };
  5164. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5165. if (mimeType === void 0) { mimeType = "image/png"; }
  5166. // Read the contents of the framebuffer
  5167. var numberOfChannelsByLine = width * 4;
  5168. var halfHeight = height / 2;
  5169. //Reading datas from WebGL
  5170. var data = engine.readPixels(0, 0, width, height);
  5171. //To flip image on Y axis.
  5172. for (var i = 0; i < halfHeight; i++) {
  5173. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5174. var currentCell = j + i * numberOfChannelsByLine;
  5175. var targetLine = height - i - 1;
  5176. var targetCell = j + targetLine * numberOfChannelsByLine;
  5177. var temp = data[currentCell];
  5178. data[currentCell] = data[targetCell];
  5179. data[targetCell] = temp;
  5180. }
  5181. }
  5182. // Create a 2D canvas to store the result
  5183. if (!screenshotCanvas) {
  5184. screenshotCanvas = document.createElement('canvas');
  5185. }
  5186. screenshotCanvas.width = width;
  5187. screenshotCanvas.height = height;
  5188. var context = screenshotCanvas.getContext('2d');
  5189. // Copy the pixels to a 2D canvas
  5190. var imageData = context.createImageData(width, height);
  5191. var castData = (imageData.data);
  5192. castData.set(data);
  5193. context.putImageData(imageData, 0, 0);
  5194. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5195. };
  5196. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5197. if (mimeType === void 0) { mimeType = "image/png"; }
  5198. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5199. if (successCallback) {
  5200. successCallback(base64Image);
  5201. }
  5202. else {
  5203. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5204. if (("download" in document.createElement("a"))) {
  5205. var a = window.document.createElement("a");
  5206. a.href = base64Image;
  5207. var date = new Date();
  5208. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5209. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5210. window.document.body.appendChild(a);
  5211. a.addEventListener("click", function () {
  5212. a.parentElement.removeChild(a);
  5213. });
  5214. a.click();
  5215. }
  5216. else {
  5217. var newWindow = window.open("");
  5218. var img = newWindow.document.createElement("img");
  5219. img.src = base64Image;
  5220. newWindow.document.body.appendChild(img);
  5221. }
  5222. }
  5223. };
  5224. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5225. if (mimeType === void 0) { mimeType = "image/png"; }
  5226. var width;
  5227. var height;
  5228. // If a precision value is specified
  5229. if (size.precision) {
  5230. width = Math.round(engine.getRenderWidth() * size.precision);
  5231. height = Math.round(width / engine.getAspectRatio(camera));
  5232. }
  5233. else if (size.width && size.height) {
  5234. width = size.width;
  5235. height = size.height;
  5236. }
  5237. else if (size.width && !size.height) {
  5238. width = size.width;
  5239. height = Math.round(width / engine.getAspectRatio(camera));
  5240. }
  5241. else if (size.height && !size.width) {
  5242. height = size.height;
  5243. width = Math.round(height * engine.getAspectRatio(camera));
  5244. }
  5245. else if (!isNaN(size)) {
  5246. height = size;
  5247. width = size;
  5248. }
  5249. else {
  5250. Tools.Error("Invalid 'size' parameter !");
  5251. return;
  5252. }
  5253. if (!screenshotCanvas) {
  5254. screenshotCanvas = document.createElement('canvas');
  5255. }
  5256. screenshotCanvas.width = width;
  5257. screenshotCanvas.height = height;
  5258. var renderContext = screenshotCanvas.getContext("2d");
  5259. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5260. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5261. };
  5262. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5263. if (mimeType === void 0) { mimeType = "image/png"; }
  5264. var width;
  5265. var height;
  5266. //If a precision value is specified
  5267. if (size.precision) {
  5268. width = Math.round(engine.getRenderWidth() * size.precision);
  5269. height = Math.round(width / engine.getAspectRatio(camera));
  5270. size = { width: width, height: height };
  5271. }
  5272. else if (size.width && size.height) {
  5273. width = size.width;
  5274. height = size.height;
  5275. }
  5276. else if (size.width && !size.height) {
  5277. width = size.width;
  5278. height = Math.round(width / engine.getAspectRatio(camera));
  5279. size = { width: width, height: height };
  5280. }
  5281. else if (size.height && !size.width) {
  5282. height = size.height;
  5283. width = Math.round(height * engine.getAspectRatio(camera));
  5284. size = { width: width, height: height };
  5285. }
  5286. else if (!isNaN(size)) {
  5287. height = size;
  5288. width = size;
  5289. }
  5290. else {
  5291. Tools.Error("Invalid 'size' parameter !");
  5292. return;
  5293. }
  5294. var scene = camera.getScene();
  5295. var previousCamera = null;
  5296. if (scene.activeCamera !== camera) {
  5297. previousCamera = scene.activeCamera;
  5298. scene.activeCamera = camera;
  5299. }
  5300. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5301. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5302. texture.renderList = scene.meshes;
  5303. texture.onAfterRenderObservable.add(function () {
  5304. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5305. });
  5306. scene.incrementRenderId();
  5307. scene.resetCachedMaterial();
  5308. texture.render(true);
  5309. texture.dispose();
  5310. if (previousCamera) {
  5311. scene.activeCamera = previousCamera;
  5312. }
  5313. camera.getProjectionMatrix(true); // Force cache refresh;
  5314. };
  5315. // XHR response validator for local file scenario
  5316. Tools.ValidateXHRData = function (xhr, dataType) {
  5317. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5318. if (dataType === void 0) { dataType = 7; }
  5319. try {
  5320. if (dataType & 1) {
  5321. if (xhr.responseText && xhr.responseText.length > 0) {
  5322. return true;
  5323. }
  5324. else if (dataType === 1) {
  5325. return false;
  5326. }
  5327. }
  5328. if (dataType & 2) {
  5329. // Check header width and height since there is no "TGA" magic number
  5330. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5331. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5332. return true;
  5333. }
  5334. else if (dataType === 2) {
  5335. return false;
  5336. }
  5337. }
  5338. if (dataType & 4) {
  5339. // Check for the "DDS" magic number
  5340. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5341. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5342. return true;
  5343. }
  5344. else {
  5345. return false;
  5346. }
  5347. }
  5348. }
  5349. catch (e) {
  5350. }
  5351. return false;
  5352. };
  5353. /**
  5354. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5355. * Be aware Math.random() could cause collisions, but:
  5356. * "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"
  5357. */
  5358. Tools.RandomId = function () {
  5359. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5360. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5361. return v.toString(16);
  5362. });
  5363. };
  5364. Object.defineProperty(Tools, "NoneLogLevel", {
  5365. get: function () {
  5366. return Tools._NoneLogLevel;
  5367. },
  5368. enumerable: true,
  5369. configurable: true
  5370. });
  5371. Object.defineProperty(Tools, "MessageLogLevel", {
  5372. get: function () {
  5373. return Tools._MessageLogLevel;
  5374. },
  5375. enumerable: true,
  5376. configurable: true
  5377. });
  5378. Object.defineProperty(Tools, "WarningLogLevel", {
  5379. get: function () {
  5380. return Tools._WarningLogLevel;
  5381. },
  5382. enumerable: true,
  5383. configurable: true
  5384. });
  5385. Object.defineProperty(Tools, "ErrorLogLevel", {
  5386. get: function () {
  5387. return Tools._ErrorLogLevel;
  5388. },
  5389. enumerable: true,
  5390. configurable: true
  5391. });
  5392. Object.defineProperty(Tools, "AllLogLevel", {
  5393. get: function () {
  5394. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5395. },
  5396. enumerable: true,
  5397. configurable: true
  5398. });
  5399. Tools._AddLogEntry = function (entry) {
  5400. Tools._LogCache = entry + Tools._LogCache;
  5401. if (Tools.OnNewCacheEntry) {
  5402. Tools.OnNewCacheEntry(entry);
  5403. }
  5404. };
  5405. Tools._FormatMessage = function (message) {
  5406. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5407. var date = new Date();
  5408. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5409. };
  5410. Tools._LogDisabled = function (message) {
  5411. // nothing to do
  5412. };
  5413. Tools._LogEnabled = function (message) {
  5414. var formattedMessage = Tools._FormatMessage(message);
  5415. console.log("BJS - " + formattedMessage);
  5416. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5417. Tools._AddLogEntry(entry);
  5418. };
  5419. Tools._WarnDisabled = function (message) {
  5420. // nothing to do
  5421. };
  5422. Tools._WarnEnabled = function (message) {
  5423. var formattedMessage = Tools._FormatMessage(message);
  5424. console.warn("BJS - " + formattedMessage);
  5425. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5426. Tools._AddLogEntry(entry);
  5427. };
  5428. Tools._ErrorDisabled = function (message) {
  5429. // nothing to do
  5430. };
  5431. Tools._ErrorEnabled = function (message) {
  5432. Tools.errorsCount++;
  5433. var formattedMessage = Tools._FormatMessage(message);
  5434. console.error("BJS - " + formattedMessage);
  5435. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5436. Tools._AddLogEntry(entry);
  5437. };
  5438. Object.defineProperty(Tools, "LogCache", {
  5439. get: function () {
  5440. return Tools._LogCache;
  5441. },
  5442. enumerable: true,
  5443. configurable: true
  5444. });
  5445. Tools.ClearLogCache = function () {
  5446. Tools._LogCache = "";
  5447. Tools.errorsCount = 0;
  5448. };
  5449. Object.defineProperty(Tools, "LogLevels", {
  5450. set: function (level) {
  5451. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5452. Tools.Log = Tools._LogEnabled;
  5453. }
  5454. else {
  5455. Tools.Log = Tools._LogDisabled;
  5456. }
  5457. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5458. Tools.Warn = Tools._WarnEnabled;
  5459. }
  5460. else {
  5461. Tools.Warn = Tools._WarnDisabled;
  5462. }
  5463. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5464. Tools.Error = Tools._ErrorEnabled;
  5465. }
  5466. else {
  5467. Tools.Error = Tools._ErrorDisabled;
  5468. }
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5474. get: function () {
  5475. return Tools._PerformanceNoneLogLevel;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5481. get: function () {
  5482. return Tools._PerformanceUserMarkLogLevel;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5488. get: function () {
  5489. return Tools._PerformanceConsoleLogLevel;
  5490. },
  5491. enumerable: true,
  5492. configurable: true
  5493. });
  5494. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5495. set: function (level) {
  5496. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5497. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5498. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5499. return;
  5500. }
  5501. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5502. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5503. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5504. return;
  5505. }
  5506. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5507. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5508. },
  5509. enumerable: true,
  5510. configurable: true
  5511. });
  5512. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5513. };
  5514. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5515. };
  5516. Tools._StartUserMark = function (counterName, condition) {
  5517. if (condition === void 0) { condition = true; }
  5518. if (!condition || !Tools._performance.mark) {
  5519. return;
  5520. }
  5521. Tools._performance.mark(counterName + "-Begin");
  5522. };
  5523. Tools._EndUserMark = function (counterName, condition) {
  5524. if (condition === void 0) { condition = true; }
  5525. if (!condition || !Tools._performance.mark) {
  5526. return;
  5527. }
  5528. Tools._performance.mark(counterName + "-End");
  5529. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5530. };
  5531. Tools._StartPerformanceConsole = function (counterName, condition) {
  5532. if (condition === void 0) { condition = true; }
  5533. if (!condition) {
  5534. return;
  5535. }
  5536. Tools._StartUserMark(counterName, condition);
  5537. if (console.time) {
  5538. console.time(counterName);
  5539. }
  5540. };
  5541. Tools._EndPerformanceConsole = function (counterName, condition) {
  5542. if (condition === void 0) { condition = true; }
  5543. if (!condition) {
  5544. return;
  5545. }
  5546. Tools._EndUserMark(counterName, condition);
  5547. if (console.time) {
  5548. console.timeEnd(counterName);
  5549. }
  5550. };
  5551. Object.defineProperty(Tools, "Now", {
  5552. get: function () {
  5553. if (window.performance && window.performance.now) {
  5554. return window.performance.now();
  5555. }
  5556. return new Date().getTime();
  5557. },
  5558. enumerable: true,
  5559. configurable: true
  5560. });
  5561. /**
  5562. * This method will return the name of the class used to create the instance of the given object.
  5563. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5564. * @param object the object to get the class name from
  5565. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5566. */
  5567. Tools.getClassName = function (object, isType) {
  5568. if (isType === void 0) { isType = false; }
  5569. var name = null;
  5570. if (!isType && object.getClassName) {
  5571. name = object.getClassName();
  5572. }
  5573. else {
  5574. if (object instanceof Object) {
  5575. var classObj = isType ? object : Object.getPrototypeOf(object);
  5576. name = classObj.constructor["__bjsclassName__"];
  5577. }
  5578. if (!name) {
  5579. name = typeof object;
  5580. }
  5581. }
  5582. return name;
  5583. };
  5584. Tools.first = function (array, predicate) {
  5585. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5586. var el = array_1[_i];
  5587. if (predicate(el)) {
  5588. return el;
  5589. }
  5590. }
  5591. };
  5592. /**
  5593. * This method will return the name of the full name of the class, including its owning module (if any).
  5594. * 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).
  5595. * @param object the object to get the class name from
  5596. * @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.
  5597. */
  5598. Tools.getFullClassName = function (object, isType) {
  5599. if (isType === void 0) { isType = false; }
  5600. var className = null;
  5601. var moduleName = null;
  5602. if (!isType && object.getClassName) {
  5603. className = object.getClassName();
  5604. }
  5605. else {
  5606. if (object instanceof Object) {
  5607. var classObj = isType ? object : Object.getPrototypeOf(object);
  5608. className = classObj.constructor["__bjsclassName__"];
  5609. moduleName = classObj.constructor["__bjsmoduleName__"];
  5610. }
  5611. if (!className) {
  5612. className = typeof object;
  5613. }
  5614. }
  5615. if (!className) {
  5616. return null;
  5617. }
  5618. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5619. };
  5620. /**
  5621. * 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.
  5622. * @param array
  5623. */
  5624. Tools.arrayOrStringFeeder = function (array) {
  5625. return function (index) {
  5626. if (index >= array.length) {
  5627. return null;
  5628. }
  5629. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5630. if (val && val.getHashCode) {
  5631. val = val.getHashCode();
  5632. }
  5633. if (typeof val === "string") {
  5634. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5635. }
  5636. return val;
  5637. };
  5638. };
  5639. /**
  5640. * Compute the hashCode of a stream of number
  5641. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5642. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5643. * @return the hash code computed
  5644. */
  5645. Tools.hashCodeFromStream = function (feeder) {
  5646. // Based from here: http://stackoverflow.com/a/7616484/802124
  5647. var hash = 0;
  5648. var index = 0;
  5649. var chr = feeder(index++);
  5650. while (chr != null) {
  5651. hash = ((hash << 5) - hash) + chr;
  5652. hash |= 0; // Convert to 32bit integer
  5653. chr = feeder(index++);
  5654. }
  5655. return hash;
  5656. };
  5657. Tools.BaseUrl = "";
  5658. Tools.CorsBehavior = "anonymous";
  5659. Tools.UseFallbackTexture = true;
  5660. // Logs
  5661. Tools._NoneLogLevel = 0;
  5662. Tools._MessageLogLevel = 1;
  5663. Tools._WarningLogLevel = 2;
  5664. Tools._ErrorLogLevel = 4;
  5665. Tools._LogCache = "";
  5666. Tools.errorsCount = 0;
  5667. Tools.Log = Tools._LogEnabled;
  5668. Tools.Warn = Tools._WarnEnabled;
  5669. Tools.Error = Tools._ErrorEnabled;
  5670. // Performances
  5671. Tools._PerformanceNoneLogLevel = 0;
  5672. Tools._PerformanceUserMarkLogLevel = 1;
  5673. Tools._PerformanceConsoleLogLevel = 2;
  5674. Tools._performance = window.performance;
  5675. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5676. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5677. return Tools;
  5678. }());
  5679. BABYLON.Tools = Tools;
  5680. /**
  5681. * This class is used to track a performance counter which is number based.
  5682. * The user has access to many properties which give statistics of different nature
  5683. *
  5684. * The implementer can track two kinds of Performance Counter: time and count
  5685. * 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.
  5686. * 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.
  5687. */
  5688. var PerfCounter = (function () {
  5689. function PerfCounter() {
  5690. this._startMonitoringTime = 0;
  5691. this._min = 0;
  5692. this._max = 0;
  5693. this._average = 0;
  5694. this._lastSecAverage = 0;
  5695. this._current = 0;
  5696. this._totalValueCount = 0;
  5697. this._totalAccumulated = 0;
  5698. this._lastSecAccumulated = 0;
  5699. this._lastSecTime = 0;
  5700. this._lastSecValueCount = 0;
  5701. }
  5702. Object.defineProperty(PerfCounter.prototype, "min", {
  5703. /**
  5704. * Returns the smallest value ever
  5705. */
  5706. get: function () {
  5707. return this._min;
  5708. },
  5709. enumerable: true,
  5710. configurable: true
  5711. });
  5712. Object.defineProperty(PerfCounter.prototype, "max", {
  5713. /**
  5714. * Returns the biggest value ever
  5715. */
  5716. get: function () {
  5717. return this._max;
  5718. },
  5719. enumerable: true,
  5720. configurable: true
  5721. });
  5722. Object.defineProperty(PerfCounter.prototype, "average", {
  5723. /**
  5724. * Returns the average value since the performance counter is running
  5725. */
  5726. get: function () {
  5727. return this._average;
  5728. },
  5729. enumerable: true,
  5730. configurable: true
  5731. });
  5732. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5733. /**
  5734. * Returns the average value of the last second the counter was monitored
  5735. */
  5736. get: function () {
  5737. return this._lastSecAverage;
  5738. },
  5739. enumerable: true,
  5740. configurable: true
  5741. });
  5742. Object.defineProperty(PerfCounter.prototype, "current", {
  5743. /**
  5744. * Returns the current value
  5745. */
  5746. get: function () {
  5747. return this._current;
  5748. },
  5749. enumerable: true,
  5750. configurable: true
  5751. });
  5752. Object.defineProperty(PerfCounter.prototype, "total", {
  5753. get: function () {
  5754. return this._totalAccumulated;
  5755. },
  5756. enumerable: true,
  5757. configurable: true
  5758. });
  5759. /**
  5760. * Call this method to start monitoring a new frame.
  5761. * 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.
  5762. */
  5763. PerfCounter.prototype.fetchNewFrame = function () {
  5764. this._totalValueCount++;
  5765. this._current = 0;
  5766. this._lastSecValueCount++;
  5767. };
  5768. /**
  5769. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5770. * @param newCount the count value to add to the monitored count
  5771. * @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.
  5772. */
  5773. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5774. this._current += newCount;
  5775. if (fetchResult) {
  5776. this._fetchResult();
  5777. }
  5778. };
  5779. /**
  5780. * Start monitoring this performance counter
  5781. */
  5782. PerfCounter.prototype.beginMonitoring = function () {
  5783. this._startMonitoringTime = Tools.Now;
  5784. };
  5785. /**
  5786. * Compute the time lapsed since the previous beginMonitoring() call.
  5787. * @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
  5788. */
  5789. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5790. if (newFrame === void 0) { newFrame = true; }
  5791. if (newFrame) {
  5792. this.fetchNewFrame();
  5793. }
  5794. var currentTime = Tools.Now;
  5795. this._current = currentTime - this._startMonitoringTime;
  5796. if (newFrame) {
  5797. this._fetchResult();
  5798. }
  5799. };
  5800. PerfCounter.prototype._fetchResult = function () {
  5801. this._totalAccumulated += this._current;
  5802. this._lastSecAccumulated += this._current;
  5803. // Min/Max update
  5804. this._min = Math.min(this._min, this._current);
  5805. this._max = Math.max(this._max, this._current);
  5806. this._average = this._totalAccumulated / this._totalValueCount;
  5807. // Reset last sec?
  5808. var now = Tools.Now;
  5809. if ((now - this._lastSecTime) > 1000) {
  5810. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5811. this._lastSecTime = now;
  5812. this._lastSecAccumulated = 0;
  5813. this._lastSecValueCount = 0;
  5814. }
  5815. };
  5816. return PerfCounter;
  5817. }());
  5818. BABYLON.PerfCounter = PerfCounter;
  5819. /**
  5820. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5821. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5822. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5823. * @param name The name of the class, case should be preserved
  5824. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5825. */
  5826. function className(name, module) {
  5827. return function (target) {
  5828. target["__bjsclassName__"] = name;
  5829. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5830. };
  5831. }
  5832. BABYLON.className = className;
  5833. /**
  5834. * An implementation of a loop for asynchronous functions.
  5835. */
  5836. var AsyncLoop = (function () {
  5837. /**
  5838. * Constroctor.
  5839. * @param iterations the number of iterations.
  5840. * @param _fn the function to run each iteration
  5841. * @param _successCallback the callback that will be called upon succesful execution
  5842. * @param offset starting offset.
  5843. */
  5844. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5845. if (offset === void 0) { offset = 0; }
  5846. this.iterations = iterations;
  5847. this._fn = _fn;
  5848. this._successCallback = _successCallback;
  5849. this.index = offset - 1;
  5850. this._done = false;
  5851. }
  5852. /**
  5853. * Execute the next iteration. Must be called after the last iteration was finished.
  5854. */
  5855. AsyncLoop.prototype.executeNext = function () {
  5856. if (!this._done) {
  5857. if (this.index + 1 < this.iterations) {
  5858. ++this.index;
  5859. this._fn(this);
  5860. }
  5861. else {
  5862. this.breakLoop();
  5863. }
  5864. }
  5865. };
  5866. /**
  5867. * Break the loop and run the success callback.
  5868. */
  5869. AsyncLoop.prototype.breakLoop = function () {
  5870. this._done = true;
  5871. this._successCallback();
  5872. };
  5873. /**
  5874. * Helper function
  5875. */
  5876. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5877. if (offset === void 0) { offset = 0; }
  5878. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5879. loop.executeNext();
  5880. return loop;
  5881. };
  5882. /**
  5883. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5884. * @param iterations total number of iterations
  5885. * @param syncedIterations number of synchronous iterations in each async iteration.
  5886. * @param fn the function to call each iteration.
  5887. * @param callback a success call back that will be called when iterating stops.
  5888. * @param breakFunction a break condition (optional)
  5889. * @param timeout timeout settings for the setTimeout function. default - 0.
  5890. * @constructor
  5891. */
  5892. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5893. if (timeout === void 0) { timeout = 0; }
  5894. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5895. if (breakFunction && breakFunction())
  5896. loop.breakLoop();
  5897. else {
  5898. setTimeout(function () {
  5899. for (var i = 0; i < syncedIterations; ++i) {
  5900. var iteration = (loop.index * syncedIterations) + i;
  5901. if (iteration >= iterations)
  5902. break;
  5903. fn(iteration);
  5904. if (breakFunction && breakFunction()) {
  5905. loop.breakLoop();
  5906. break;
  5907. }
  5908. }
  5909. loop.executeNext();
  5910. }, timeout);
  5911. }
  5912. }, callback);
  5913. };
  5914. return AsyncLoop;
  5915. }());
  5916. BABYLON.AsyncLoop = AsyncLoop;
  5917. })(BABYLON || (BABYLON = {}));
  5918. //# sourceMappingURL=babylon.tools.js.map
  5919. var BABYLON;
  5920. (function (BABYLON) {
  5921. var Internals;
  5922. (function (Internals) {
  5923. var _AlphaState = (function () {
  5924. /**
  5925. * Initializes the state.
  5926. */
  5927. function _AlphaState() {
  5928. this._isAlphaBlendDirty = false;
  5929. this._isBlendFunctionParametersDirty = false;
  5930. this._alphaBlend = false;
  5931. this._blendFunctionParameters = new Array(4);
  5932. this.reset();
  5933. }
  5934. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5935. get: function () {
  5936. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5937. },
  5938. enumerable: true,
  5939. configurable: true
  5940. });
  5941. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5942. get: function () {
  5943. return this._alphaBlend;
  5944. },
  5945. set: function (value) {
  5946. if (this._alphaBlend === value) {
  5947. return;
  5948. }
  5949. this._alphaBlend = value;
  5950. this._isAlphaBlendDirty = true;
  5951. },
  5952. enumerable: true,
  5953. configurable: true
  5954. });
  5955. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5956. if (this._blendFunctionParameters[0] === value0 &&
  5957. this._blendFunctionParameters[1] === value1 &&
  5958. this._blendFunctionParameters[2] === value2 &&
  5959. this._blendFunctionParameters[3] === value3) {
  5960. return;
  5961. }
  5962. this._blendFunctionParameters[0] = value0;
  5963. this._blendFunctionParameters[1] = value1;
  5964. this._blendFunctionParameters[2] = value2;
  5965. this._blendFunctionParameters[3] = value3;
  5966. this._isBlendFunctionParametersDirty = true;
  5967. };
  5968. _AlphaState.prototype.reset = function () {
  5969. this._alphaBlend = false;
  5970. this._blendFunctionParameters[0] = null;
  5971. this._blendFunctionParameters[1] = null;
  5972. this._blendFunctionParameters[2] = null;
  5973. this._blendFunctionParameters[3] = null;
  5974. this._isAlphaBlendDirty = true;
  5975. this._isBlendFunctionParametersDirty = false;
  5976. };
  5977. _AlphaState.prototype.apply = function (gl) {
  5978. if (!this.isDirty) {
  5979. return;
  5980. }
  5981. // Alpha blend
  5982. if (this._isAlphaBlendDirty) {
  5983. if (this._alphaBlend) {
  5984. gl.enable(gl.BLEND);
  5985. }
  5986. else {
  5987. gl.disable(gl.BLEND);
  5988. }
  5989. this._isAlphaBlendDirty = false;
  5990. }
  5991. // Alpha function
  5992. if (this._isBlendFunctionParametersDirty) {
  5993. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5994. this._isBlendFunctionParametersDirty = false;
  5995. }
  5996. };
  5997. return _AlphaState;
  5998. }());
  5999. Internals._AlphaState = _AlphaState;
  6000. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6001. })(BABYLON || (BABYLON = {}));
  6002. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6003. var BABYLON;
  6004. (function (BABYLON) {
  6005. var Internals;
  6006. (function (Internals) {
  6007. var _DepthCullingState = (function () {
  6008. /**
  6009. * Initializes the state.
  6010. */
  6011. function _DepthCullingState() {
  6012. this._isDepthTestDirty = false;
  6013. this._isDepthMaskDirty = false;
  6014. this._isDepthFuncDirty = false;
  6015. this._isCullFaceDirty = false;
  6016. this._isCullDirty = false;
  6017. this._isZOffsetDirty = false;
  6018. this.reset();
  6019. }
  6020. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6021. get: function () {
  6022. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6023. },
  6024. enumerable: true,
  6025. configurable: true
  6026. });
  6027. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6028. get: function () {
  6029. return this._zOffset;
  6030. },
  6031. set: function (value) {
  6032. if (this._zOffset === value) {
  6033. return;
  6034. }
  6035. this._zOffset = value;
  6036. this._isZOffsetDirty = true;
  6037. },
  6038. enumerable: true,
  6039. configurable: true
  6040. });
  6041. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6042. get: function () {
  6043. return this._cullFace;
  6044. },
  6045. set: function (value) {
  6046. if (this._cullFace === value) {
  6047. return;
  6048. }
  6049. this._cullFace = value;
  6050. this._isCullFaceDirty = true;
  6051. },
  6052. enumerable: true,
  6053. configurable: true
  6054. });
  6055. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6056. get: function () {
  6057. return this._cull;
  6058. },
  6059. set: function (value) {
  6060. if (this._cull === value) {
  6061. return;
  6062. }
  6063. this._cull = value;
  6064. this._isCullDirty = true;
  6065. },
  6066. enumerable: true,
  6067. configurable: true
  6068. });
  6069. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6070. get: function () {
  6071. return this._depthFunc;
  6072. },
  6073. set: function (value) {
  6074. if (this._depthFunc === value) {
  6075. return;
  6076. }
  6077. this._depthFunc = value;
  6078. this._isDepthFuncDirty = true;
  6079. },
  6080. enumerable: true,
  6081. configurable: true
  6082. });
  6083. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6084. get: function () {
  6085. return this._depthMask;
  6086. },
  6087. set: function (value) {
  6088. if (this._depthMask === value) {
  6089. return;
  6090. }
  6091. this._depthMask = value;
  6092. this._isDepthMaskDirty = true;
  6093. },
  6094. enumerable: true,
  6095. configurable: true
  6096. });
  6097. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6098. get: function () {
  6099. return this._depthTest;
  6100. },
  6101. set: function (value) {
  6102. if (this._depthTest === value) {
  6103. return;
  6104. }
  6105. this._depthTest = value;
  6106. this._isDepthTestDirty = true;
  6107. },
  6108. enumerable: true,
  6109. configurable: true
  6110. });
  6111. _DepthCullingState.prototype.reset = function () {
  6112. this._depthMask = true;
  6113. this._depthTest = true;
  6114. this._depthFunc = null;
  6115. this._cullFace = null;
  6116. this._cull = null;
  6117. this._zOffset = 0;
  6118. this._isDepthTestDirty = true;
  6119. this._isDepthMaskDirty = true;
  6120. this._isDepthFuncDirty = false;
  6121. this._isCullFaceDirty = false;
  6122. this._isCullDirty = false;
  6123. this._isZOffsetDirty = false;
  6124. };
  6125. _DepthCullingState.prototype.apply = function (gl) {
  6126. if (!this.isDirty) {
  6127. return;
  6128. }
  6129. // Cull
  6130. if (this._isCullDirty) {
  6131. if (this.cull) {
  6132. gl.enable(gl.CULL_FACE);
  6133. }
  6134. else {
  6135. gl.disable(gl.CULL_FACE);
  6136. }
  6137. this._isCullDirty = false;
  6138. }
  6139. // Cull face
  6140. if (this._isCullFaceDirty) {
  6141. gl.cullFace(this.cullFace);
  6142. this._isCullFaceDirty = false;
  6143. }
  6144. // Depth mask
  6145. if (this._isDepthMaskDirty) {
  6146. gl.depthMask(this.depthMask);
  6147. this._isDepthMaskDirty = false;
  6148. }
  6149. // Depth test
  6150. if (this._isDepthTestDirty) {
  6151. if (this.depthTest) {
  6152. gl.enable(gl.DEPTH_TEST);
  6153. }
  6154. else {
  6155. gl.disable(gl.DEPTH_TEST);
  6156. }
  6157. this._isDepthTestDirty = false;
  6158. }
  6159. // Depth func
  6160. if (this._isDepthFuncDirty) {
  6161. gl.depthFunc(this.depthFunc);
  6162. this._isDepthFuncDirty = false;
  6163. }
  6164. // zOffset
  6165. if (this._isZOffsetDirty) {
  6166. if (this.zOffset) {
  6167. gl.enable(gl.POLYGON_OFFSET_FILL);
  6168. gl.polygonOffset(this.zOffset, 0);
  6169. }
  6170. else {
  6171. gl.disable(gl.POLYGON_OFFSET_FILL);
  6172. }
  6173. this._isZOffsetDirty = false;
  6174. }
  6175. };
  6176. return _DepthCullingState;
  6177. }());
  6178. Internals._DepthCullingState = _DepthCullingState;
  6179. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6180. })(BABYLON || (BABYLON = {}));
  6181. //# sourceMappingURL=babylon.depthCullingState.js.map
  6182. var BABYLON;
  6183. (function (BABYLON) {
  6184. var Internals;
  6185. (function (Internals) {
  6186. var _StencilState = (function () {
  6187. function _StencilState() {
  6188. this._isStencilTestDirty = false;
  6189. this._isStencilMaskDirty = false;
  6190. this._isStencilFuncDirty = false;
  6191. this._isStencilOpDirty = false;
  6192. this.reset();
  6193. }
  6194. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6195. get: function () {
  6196. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6197. },
  6198. enumerable: true,
  6199. configurable: true
  6200. });
  6201. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6202. get: function () {
  6203. return this._stencilFunc;
  6204. },
  6205. set: function (value) {
  6206. if (this._stencilFunc === value) {
  6207. return;
  6208. }
  6209. this._stencilFunc = value;
  6210. this._isStencilFuncDirty = true;
  6211. },
  6212. enumerable: true,
  6213. configurable: true
  6214. });
  6215. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6216. get: function () {
  6217. return this._stencilFuncRef;
  6218. },
  6219. set: function (value) {
  6220. if (this._stencilFuncRef === value) {
  6221. return;
  6222. }
  6223. this._stencilFuncRef = value;
  6224. this._isStencilFuncDirty = true;
  6225. },
  6226. enumerable: true,
  6227. configurable: true
  6228. });
  6229. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6230. get: function () {
  6231. return this._stencilFuncMask;
  6232. },
  6233. set: function (value) {
  6234. if (this._stencilFuncMask === value) {
  6235. return;
  6236. }
  6237. this._stencilFuncMask = value;
  6238. this._isStencilFuncDirty = true;
  6239. },
  6240. enumerable: true,
  6241. configurable: true
  6242. });
  6243. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6244. get: function () {
  6245. return this._stencilOpStencilFail;
  6246. },
  6247. set: function (value) {
  6248. if (this._stencilOpStencilFail === value) {
  6249. return;
  6250. }
  6251. this._stencilOpStencilFail = value;
  6252. this._isStencilOpDirty = true;
  6253. },
  6254. enumerable: true,
  6255. configurable: true
  6256. });
  6257. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6258. get: function () {
  6259. return this._stencilOpDepthFail;
  6260. },
  6261. set: function (value) {
  6262. if (this._stencilOpDepthFail === value) {
  6263. return;
  6264. }
  6265. this._stencilOpDepthFail = value;
  6266. this._isStencilOpDirty = true;
  6267. },
  6268. enumerable: true,
  6269. configurable: true
  6270. });
  6271. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6272. get: function () {
  6273. return this._stencilOpStencilDepthPass;
  6274. },
  6275. set: function (value) {
  6276. if (this._stencilOpStencilDepthPass === value) {
  6277. return;
  6278. }
  6279. this._stencilOpStencilDepthPass = value;
  6280. this._isStencilOpDirty = true;
  6281. },
  6282. enumerable: true,
  6283. configurable: true
  6284. });
  6285. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6286. get: function () {
  6287. return this._stencilMask;
  6288. },
  6289. set: function (value) {
  6290. if (this._stencilMask === value) {
  6291. return;
  6292. }
  6293. this._stencilMask = value;
  6294. this._isStencilMaskDirty = true;
  6295. },
  6296. enumerable: true,
  6297. configurable: true
  6298. });
  6299. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6300. get: function () {
  6301. return this._stencilTest;
  6302. },
  6303. set: function (value) {
  6304. if (this._stencilTest === value) {
  6305. return;
  6306. }
  6307. this._stencilTest = value;
  6308. this._isStencilTestDirty = true;
  6309. },
  6310. enumerable: true,
  6311. configurable: true
  6312. });
  6313. _StencilState.prototype.reset = function () {
  6314. this._stencilTest = false;
  6315. this._stencilMask = 0xFF;
  6316. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6317. this._stencilFuncRef = 1;
  6318. this._stencilFuncMask = 0xFF;
  6319. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6320. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6321. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6322. this._isStencilTestDirty = true;
  6323. this._isStencilMaskDirty = true;
  6324. this._isStencilFuncDirty = true;
  6325. this._isStencilOpDirty = true;
  6326. };
  6327. _StencilState.prototype.apply = function (gl) {
  6328. if (!this.isDirty) {
  6329. return;
  6330. }
  6331. // Stencil test
  6332. if (this._isStencilTestDirty) {
  6333. if (this.stencilTest) {
  6334. gl.enable(gl.STENCIL_TEST);
  6335. }
  6336. else {
  6337. gl.disable(gl.STENCIL_TEST);
  6338. }
  6339. this._isStencilTestDirty = false;
  6340. }
  6341. // Stencil mask
  6342. if (this._isStencilMaskDirty) {
  6343. gl.stencilMask(this.stencilMask);
  6344. this._isStencilMaskDirty = false;
  6345. }
  6346. // Stencil func
  6347. if (this._isStencilFuncDirty) {
  6348. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6349. this._isStencilFuncDirty = false;
  6350. }
  6351. // Stencil op
  6352. if (this._isStencilOpDirty) {
  6353. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6354. this._isStencilOpDirty = false;
  6355. }
  6356. };
  6357. return _StencilState;
  6358. }());
  6359. Internals._StencilState = _StencilState;
  6360. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6361. })(BABYLON || (BABYLON = {}));
  6362. //# sourceMappingURL=babylon.stencilState.js.map
  6363. var BABYLON;
  6364. (function (BABYLON) {
  6365. var compileShader = function (gl, source, type, defines) {
  6366. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6367. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6368. gl.compileShader(shader);
  6369. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6370. throw new Error(gl.getShaderInfoLog(shader));
  6371. }
  6372. return shader;
  6373. };
  6374. var HALF_FLOAT_OES = 0x8D61;
  6375. var getWebGLTextureType = function (gl, type) {
  6376. if (type === Engine.TEXTURETYPE_FLOAT) {
  6377. return gl.FLOAT;
  6378. }
  6379. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6380. // Add Half Float Constant.
  6381. return HALF_FLOAT_OES;
  6382. }
  6383. return gl.UNSIGNED_BYTE;
  6384. };
  6385. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6386. var magFilter = gl.NEAREST;
  6387. var minFilter = gl.NEAREST;
  6388. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6389. magFilter = gl.LINEAR;
  6390. if (generateMipMaps) {
  6391. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6392. }
  6393. else {
  6394. minFilter = gl.LINEAR;
  6395. }
  6396. }
  6397. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6398. magFilter = gl.LINEAR;
  6399. if (generateMipMaps) {
  6400. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6401. }
  6402. else {
  6403. minFilter = gl.LINEAR;
  6404. }
  6405. }
  6406. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6407. magFilter = gl.NEAREST;
  6408. if (generateMipMaps) {
  6409. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6410. }
  6411. else {
  6412. minFilter = gl.NEAREST;
  6413. }
  6414. }
  6415. return {
  6416. min: minFilter,
  6417. mag: magFilter
  6418. };
  6419. };
  6420. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6422. var engine = scene.getEngine();
  6423. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6424. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6425. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6426. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6427. texture._baseWidth = width;
  6428. texture._baseHeight = height;
  6429. texture._width = potWidth;
  6430. texture._height = potHeight;
  6431. texture.isReady = true;
  6432. processFunction(potWidth, potHeight);
  6433. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6436. if (!noMipmap && !isCompressed) {
  6437. gl.generateMipmap(gl.TEXTURE_2D);
  6438. }
  6439. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6440. engine.resetTextureCache();
  6441. scene._removePendingData(texture);
  6442. texture.onLoadedCallbacks.forEach(function (callback) {
  6443. callback();
  6444. });
  6445. texture.onLoadedCallbacks = [];
  6446. };
  6447. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6448. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6449. var img;
  6450. var onload = function () {
  6451. loadedImages[index] = img;
  6452. loadedImages._internalCount++;
  6453. scene._removePendingData(img);
  6454. if (loadedImages._internalCount === 6) {
  6455. onfinish(loadedImages);
  6456. }
  6457. };
  6458. var onerror = function () {
  6459. scene._removePendingData(img);
  6460. if (onErrorCallBack) {
  6461. onErrorCallBack();
  6462. }
  6463. };
  6464. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6465. scene._addPendingData(img);
  6466. };
  6467. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6468. if (onError === void 0) { onError = null; }
  6469. var loadedImages = [];
  6470. loadedImages._internalCount = 0;
  6471. for (var index = 0; index < 6; index++) {
  6472. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6473. }
  6474. };
  6475. var InstancingAttributeInfo = (function () {
  6476. function InstancingAttributeInfo() {
  6477. }
  6478. return InstancingAttributeInfo;
  6479. }());
  6480. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6481. var EngineCapabilities = (function () {
  6482. function EngineCapabilities() {
  6483. }
  6484. return EngineCapabilities;
  6485. }());
  6486. BABYLON.EngineCapabilities = EngineCapabilities;
  6487. /**
  6488. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6489. */
  6490. var Engine = (function () {
  6491. /**
  6492. * @constructor
  6493. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6494. * @param {boolean} [antialias] - enable antialias
  6495. * @param options - further options to be sent to the getContext function
  6496. */
  6497. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6498. var _this = this;
  6499. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6500. // Public members
  6501. this.isFullscreen = false;
  6502. this.isPointerLock = false;
  6503. this.cullBackFaces = true;
  6504. this.renderEvenInBackground = true;
  6505. // To enable/disable IDB support and avoid XHR on .manifest
  6506. this.enableOfflineSupport = true;
  6507. this.scenes = new Array();
  6508. this._windowIsBackground = false;
  6509. this._webGLVersion = "1.0";
  6510. this._badOS = false;
  6511. this._drawCalls = new BABYLON.PerfCounter();
  6512. this._renderingQueueLaunched = false;
  6513. this._activeRenderLoops = [];
  6514. // FPS
  6515. this.fpsRange = 60;
  6516. this.previousFramesDuration = [];
  6517. this.fps = 60;
  6518. this.deltaTime = 0;
  6519. // States
  6520. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6521. this._stencilState = new BABYLON.Internals._StencilState();
  6522. this._alphaState = new BABYLON.Internals._AlphaState();
  6523. this._alphaMode = Engine.ALPHA_DISABLE;
  6524. // Cache
  6525. this._loadedTexturesCache = new Array();
  6526. this._maxTextureChannels = 16;
  6527. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6528. this._compiledEffects = {};
  6529. this._vertexAttribArraysEnabled = [];
  6530. this._uintIndicesCurrentlySet = false;
  6531. this._currentBoundBuffer = new Array();
  6532. this._currentBufferPointers = [];
  6533. this._currentInstanceLocations = new Array();
  6534. this._currentInstanceBuffers = new Array();
  6535. // Hardware supported Compressed Textures
  6536. this._texturesSupported = new Array();
  6537. this._onVRFullScreenTriggered = function () {
  6538. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6539. //get the old size before we change
  6540. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6541. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6542. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6543. //But actually, no browser follow the specs...
  6544. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6545. //get the width and height, change the render size
  6546. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6547. var width, height;
  6548. _this.setHardwareScalingLevel(1);
  6549. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6550. }
  6551. else {
  6552. //When the specs are implemented, need to uncomment this.
  6553. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6554. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6555. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6556. _this._vrDisplayEnabled = undefined;
  6557. }
  6558. };
  6559. this._renderingCanvas = canvas;
  6560. this._externalData = new BABYLON.StringDictionary();
  6561. options = options || {};
  6562. if (antialias != null) {
  6563. options.antialias = antialias;
  6564. }
  6565. if (options.preserveDrawingBuffer === undefined) {
  6566. options.preserveDrawingBuffer = false;
  6567. }
  6568. // Checks if some of the format renders first to allow the use of webgl inspector.
  6569. var renderToFullFloat = this._canRenderToFloatTexture();
  6570. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6571. // GL
  6572. //try {
  6573. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6574. // if (this._gl) {
  6575. // this._webGLVersion = "2.0";
  6576. // }
  6577. //} catch (e) {
  6578. // // Do nothing
  6579. //}
  6580. if (!this._gl) {
  6581. if (!canvas) {
  6582. throw new Error("The provided canvas is null or undefined.");
  6583. }
  6584. try {
  6585. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6586. }
  6587. catch (e) {
  6588. throw new Error("WebGL not supported");
  6589. }
  6590. }
  6591. if (!this._gl) {
  6592. throw new Error("WebGL not supported");
  6593. }
  6594. this._onBlur = function () {
  6595. _this._windowIsBackground = true;
  6596. };
  6597. this._onFocus = function () {
  6598. _this._windowIsBackground = false;
  6599. };
  6600. window.addEventListener("blur", this._onBlur);
  6601. window.addEventListener("focus", this._onFocus);
  6602. // Viewport
  6603. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6604. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6605. this.resize();
  6606. // Caps
  6607. this._isStencilEnable = options.stencil;
  6608. this._caps = new EngineCapabilities();
  6609. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6610. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6611. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6612. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6613. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6614. // Infos
  6615. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6616. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6617. if (rendererInfo != null) {
  6618. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6619. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6620. }
  6621. if (!this._glVendor) {
  6622. this._glVendor = "Unknown vendor";
  6623. }
  6624. if (!this._glRenderer) {
  6625. this._glRenderer = "Unknown renderer";
  6626. }
  6627. // Extensions
  6628. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6629. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc');
  6630. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6631. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); // 2nd is what iOS reports
  6632. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1');
  6633. 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
  6634. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6635. 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');
  6636. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6637. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6638. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6639. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6640. this._caps.highPrecisionShaderSupported = true;
  6641. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6642. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6643. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6644. this._caps.textureFloatRender = renderToFullFloat;
  6645. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6646. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6647. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6648. // Intelligently add supported commpressed formats in order to check for.
  6649. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6650. // Next PVR & S3, which are probably superior to ETC1/2.
  6651. // Likely no hardware which supports both PVR & S3, so order matters little.
  6652. // ETC2 is newer and handles ETC1, so check for first.
  6653. if (this._caps.astc)
  6654. this.texturesSupported.push('.astc');
  6655. if (this._caps.s3tc)
  6656. this.texturesSupported.push('.dds');
  6657. if (this._caps.pvrtc)
  6658. this.texturesSupported.push('.pvr');
  6659. if (this._caps.etc2)
  6660. this.texturesSupported.push('.etc2');
  6661. if (this._caps.etc1)
  6662. this.texturesSupported.push('.etc1');
  6663. if (this._gl.getShaderPrecisionFormat) {
  6664. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6665. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6666. }
  6667. // Depth buffer
  6668. this.setDepthBuffer(true);
  6669. this.setDepthFunctionToLessOrEqual();
  6670. this.setDepthWrite(true);
  6671. // Fullscreen
  6672. this._onFullscreenChange = function () {
  6673. if (document.fullscreen !== undefined) {
  6674. _this.isFullscreen = document.fullscreen;
  6675. }
  6676. else if (document.mozFullScreen !== undefined) {
  6677. _this.isFullscreen = document.mozFullScreen;
  6678. }
  6679. else if (document.webkitIsFullScreen !== undefined) {
  6680. _this.isFullscreen = document.webkitIsFullScreen;
  6681. }
  6682. else if (document.msIsFullScreen !== undefined) {
  6683. _this.isFullscreen = document.msIsFullScreen;
  6684. }
  6685. // Pointer lock
  6686. if (_this.isFullscreen && _this._pointerLockRequested) {
  6687. canvas.requestPointerLock = canvas.requestPointerLock ||
  6688. canvas.msRequestPointerLock ||
  6689. canvas.mozRequestPointerLock ||
  6690. canvas.webkitRequestPointerLock;
  6691. if (canvas.requestPointerLock) {
  6692. canvas.requestPointerLock();
  6693. }
  6694. }
  6695. };
  6696. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6697. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6698. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6699. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6700. // Pointer lock
  6701. this._onPointerLockChange = function () {
  6702. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6703. document.webkitPointerLockElement === canvas ||
  6704. document.msPointerLockElement === canvas ||
  6705. document.pointerLockElement === canvas);
  6706. };
  6707. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6708. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6709. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6710. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6711. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6712. Engine.audioEngine = new BABYLON.AudioEngine();
  6713. }
  6714. //default loading screen
  6715. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6716. //Load WebVR Devices
  6717. if (options.autoEnableWebVR) {
  6718. this.initWebVR();
  6719. }
  6720. //Detect if we are running on a faulty buggy OS.
  6721. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6722. //ua sniffing is the tool of the devil.
  6723. this._badOS = regexp.test(navigator.userAgent);
  6724. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6725. }
  6726. Object.defineProperty(Engine, "NEVER", {
  6727. get: function () {
  6728. return Engine._NEVER;
  6729. },
  6730. enumerable: true,
  6731. configurable: true
  6732. });
  6733. Object.defineProperty(Engine, "ALWAYS", {
  6734. get: function () {
  6735. return Engine._ALWAYS;
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(Engine, "LESS", {
  6741. get: function () {
  6742. return Engine._LESS;
  6743. },
  6744. enumerable: true,
  6745. configurable: true
  6746. });
  6747. Object.defineProperty(Engine, "EQUAL", {
  6748. get: function () {
  6749. return Engine._EQUAL;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. Object.defineProperty(Engine, "LEQUAL", {
  6755. get: function () {
  6756. return Engine._LEQUAL;
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Object.defineProperty(Engine, "GREATER", {
  6762. get: function () {
  6763. return Engine._GREATER;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(Engine, "GEQUAL", {
  6769. get: function () {
  6770. return Engine._GEQUAL;
  6771. },
  6772. enumerable: true,
  6773. configurable: true
  6774. });
  6775. Object.defineProperty(Engine, "NOTEQUAL", {
  6776. get: function () {
  6777. return Engine._NOTEQUAL;
  6778. },
  6779. enumerable: true,
  6780. configurable: true
  6781. });
  6782. Object.defineProperty(Engine, "KEEP", {
  6783. get: function () {
  6784. return Engine._KEEP;
  6785. },
  6786. enumerable: true,
  6787. configurable: true
  6788. });
  6789. Object.defineProperty(Engine, "REPLACE", {
  6790. get: function () {
  6791. return Engine._REPLACE;
  6792. },
  6793. enumerable: true,
  6794. configurable: true
  6795. });
  6796. Object.defineProperty(Engine, "INCR", {
  6797. get: function () {
  6798. return Engine._INCR;
  6799. },
  6800. enumerable: true,
  6801. configurable: true
  6802. });
  6803. Object.defineProperty(Engine, "DECR", {
  6804. get: function () {
  6805. return Engine._DECR;
  6806. },
  6807. enumerable: true,
  6808. configurable: true
  6809. });
  6810. Object.defineProperty(Engine, "INVERT", {
  6811. get: function () {
  6812. return Engine._INVERT;
  6813. },
  6814. enumerable: true,
  6815. configurable: true
  6816. });
  6817. Object.defineProperty(Engine, "INCR_WRAP", {
  6818. get: function () {
  6819. return Engine._INCR_WRAP;
  6820. },
  6821. enumerable: true,
  6822. configurable: true
  6823. });
  6824. Object.defineProperty(Engine, "DECR_WRAP", {
  6825. get: function () {
  6826. return Engine._DECR_WRAP;
  6827. },
  6828. enumerable: true,
  6829. configurable: true
  6830. });
  6831. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6832. get: function () {
  6833. return Engine._ALPHA_DISABLE;
  6834. },
  6835. enumerable: true,
  6836. configurable: true
  6837. });
  6838. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6839. get: function () {
  6840. return Engine._ALPHA_ONEONE;
  6841. },
  6842. enumerable: true,
  6843. configurable: true
  6844. });
  6845. Object.defineProperty(Engine, "ALPHA_ADD", {
  6846. get: function () {
  6847. return Engine._ALPHA_ADD;
  6848. },
  6849. enumerable: true,
  6850. configurable: true
  6851. });
  6852. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6853. get: function () {
  6854. return Engine._ALPHA_COMBINE;
  6855. },
  6856. enumerable: true,
  6857. configurable: true
  6858. });
  6859. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6860. get: function () {
  6861. return Engine._ALPHA_SUBTRACT;
  6862. },
  6863. enumerable: true,
  6864. configurable: true
  6865. });
  6866. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6867. get: function () {
  6868. return Engine._ALPHA_MULTIPLY;
  6869. },
  6870. enumerable: true,
  6871. configurable: true
  6872. });
  6873. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6874. get: function () {
  6875. return Engine._ALPHA_MAXIMIZED;
  6876. },
  6877. enumerable: true,
  6878. configurable: true
  6879. });
  6880. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6881. get: function () {
  6882. return Engine._DELAYLOADSTATE_NONE;
  6883. },
  6884. enumerable: true,
  6885. configurable: true
  6886. });
  6887. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6888. get: function () {
  6889. return Engine._DELAYLOADSTATE_LOADED;
  6890. },
  6891. enumerable: true,
  6892. configurable: true
  6893. });
  6894. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6895. get: function () {
  6896. return Engine._DELAYLOADSTATE_LOADING;
  6897. },
  6898. enumerable: true,
  6899. configurable: true
  6900. });
  6901. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6902. get: function () {
  6903. return Engine._DELAYLOADSTATE_NOTLOADED;
  6904. },
  6905. enumerable: true,
  6906. configurable: true
  6907. });
  6908. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6909. get: function () {
  6910. return Engine._TEXTUREFORMAT_ALPHA;
  6911. },
  6912. enumerable: true,
  6913. configurable: true
  6914. });
  6915. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6916. get: function () {
  6917. return Engine._TEXTUREFORMAT_LUMINANCE;
  6918. },
  6919. enumerable: true,
  6920. configurable: true
  6921. });
  6922. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6923. get: function () {
  6924. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6925. },
  6926. enumerable: true,
  6927. configurable: true
  6928. });
  6929. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6930. get: function () {
  6931. return Engine._TEXTUREFORMAT_RGB;
  6932. },
  6933. enumerable: true,
  6934. configurable: true
  6935. });
  6936. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6937. get: function () {
  6938. return Engine._TEXTUREFORMAT_RGBA;
  6939. },
  6940. enumerable: true,
  6941. configurable: true
  6942. });
  6943. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6944. get: function () {
  6945. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6946. },
  6947. enumerable: true,
  6948. configurable: true
  6949. });
  6950. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6951. get: function () {
  6952. return Engine._TEXTURETYPE_FLOAT;
  6953. },
  6954. enumerable: true,
  6955. configurable: true
  6956. });
  6957. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6958. get: function () {
  6959. return Engine._TEXTURETYPE_HALF_FLOAT;
  6960. },
  6961. enumerable: true,
  6962. configurable: true
  6963. });
  6964. Object.defineProperty(Engine, "Version", {
  6965. get: function () {
  6966. return "2.6-alpha";
  6967. },
  6968. enumerable: true,
  6969. configurable: true
  6970. });
  6971. Object.defineProperty(Engine.prototype, "texturesSupported", {
  6972. get: function () {
  6973. return this._texturesSupported;
  6974. },
  6975. enumerable: true,
  6976. configurable: true
  6977. });
  6978. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  6979. get: function () {
  6980. return this._textureFormatInUse;
  6981. },
  6982. enumerable: true,
  6983. configurable: true
  6984. });
  6985. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6986. get: function () {
  6987. return this._webGLVersion;
  6988. },
  6989. enumerable: true,
  6990. configurable: true
  6991. });
  6992. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6993. /**
  6994. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6995. */
  6996. get: function () {
  6997. return this._isStencilEnable;
  6998. },
  6999. enumerable: true,
  7000. configurable: true
  7001. });
  7002. Engine.prototype._prepareWorkingCanvas = function () {
  7003. if (this._workingCanvas) {
  7004. return;
  7005. }
  7006. this._workingCanvas = document.createElement("canvas");
  7007. this._workingContext = this._workingCanvas.getContext("2d");
  7008. };
  7009. Engine.prototype.resetTextureCache = function () {
  7010. for (var index = 0; index < this._maxTextureChannels; index++) {
  7011. this._activeTexturesCache[index] = null;
  7012. }
  7013. };
  7014. Engine.prototype.getGlInfo = function () {
  7015. return {
  7016. vendor: this._glVendor,
  7017. renderer: this._glRenderer,
  7018. version: this._glVersion
  7019. };
  7020. };
  7021. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7022. if (useScreen === void 0) { useScreen = false; }
  7023. var viewport = camera.viewport;
  7024. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7025. };
  7026. Engine.prototype.getRenderWidth = function (useScreen) {
  7027. if (useScreen === void 0) { useScreen = false; }
  7028. if (!useScreen && this._currentRenderTarget) {
  7029. return this._currentRenderTarget._width;
  7030. }
  7031. return this._renderingCanvas.width;
  7032. };
  7033. Engine.prototype.getRenderHeight = function (useScreen) {
  7034. if (useScreen === void 0) { useScreen = false; }
  7035. if (!useScreen && this._currentRenderTarget) {
  7036. return this._currentRenderTarget._height;
  7037. }
  7038. return this._renderingCanvas.height;
  7039. };
  7040. Engine.prototype.getRenderingCanvas = function () {
  7041. return this._renderingCanvas;
  7042. };
  7043. Engine.prototype.getRenderingCanvasClientRect = function () {
  7044. return this._renderingCanvas.getBoundingClientRect();
  7045. };
  7046. Engine.prototype.setHardwareScalingLevel = function (level) {
  7047. this._hardwareScalingLevel = level;
  7048. this.resize();
  7049. };
  7050. Engine.prototype.getHardwareScalingLevel = function () {
  7051. return this._hardwareScalingLevel;
  7052. };
  7053. Engine.prototype.getLoadedTexturesCache = function () {
  7054. return this._loadedTexturesCache;
  7055. };
  7056. Engine.prototype.getCaps = function () {
  7057. return this._caps;
  7058. };
  7059. Object.defineProperty(Engine.prototype, "drawCalls", {
  7060. get: function () {
  7061. return this._drawCalls.current;
  7062. },
  7063. enumerable: true,
  7064. configurable: true
  7065. });
  7066. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7067. get: function () {
  7068. return this._drawCalls;
  7069. },
  7070. enumerable: true,
  7071. configurable: true
  7072. });
  7073. Engine.prototype.getDepthFunction = function () {
  7074. return this._depthCullingState.depthFunc;
  7075. };
  7076. Engine.prototype.setDepthFunction = function (depthFunc) {
  7077. this._depthCullingState.depthFunc = depthFunc;
  7078. };
  7079. Engine.prototype.setDepthFunctionToGreater = function () {
  7080. this._depthCullingState.depthFunc = this._gl.GREATER;
  7081. };
  7082. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7083. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7084. };
  7085. Engine.prototype.setDepthFunctionToLess = function () {
  7086. this._depthCullingState.depthFunc = this._gl.LESS;
  7087. };
  7088. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7089. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7090. };
  7091. Engine.prototype.getStencilBuffer = function () {
  7092. return this._stencilState.stencilTest;
  7093. };
  7094. Engine.prototype.setStencilBuffer = function (enable) {
  7095. this._stencilState.stencilTest = enable;
  7096. };
  7097. Engine.prototype.getStencilMask = function () {
  7098. return this._stencilState.stencilMask;
  7099. };
  7100. Engine.prototype.setStencilMask = function (mask) {
  7101. this._stencilState.stencilMask = mask;
  7102. };
  7103. Engine.prototype.getStencilFunction = function () {
  7104. return this._stencilState.stencilFunc;
  7105. };
  7106. Engine.prototype.getStencilFunctionReference = function () {
  7107. return this._stencilState.stencilFuncRef;
  7108. };
  7109. Engine.prototype.getStencilFunctionMask = function () {
  7110. return this._stencilState.stencilFuncMask;
  7111. };
  7112. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7113. this._stencilState.stencilFunc = stencilFunc;
  7114. };
  7115. Engine.prototype.setStencilFunctionReference = function (reference) {
  7116. this._stencilState.stencilFuncRef = reference;
  7117. };
  7118. Engine.prototype.setStencilFunctionMask = function (mask) {
  7119. this._stencilState.stencilFuncMask = mask;
  7120. };
  7121. Engine.prototype.getStencilOperationFail = function () {
  7122. return this._stencilState.stencilOpStencilFail;
  7123. };
  7124. Engine.prototype.getStencilOperationDepthFail = function () {
  7125. return this._stencilState.stencilOpDepthFail;
  7126. };
  7127. Engine.prototype.getStencilOperationPass = function () {
  7128. return this._stencilState.stencilOpStencilDepthPass;
  7129. };
  7130. Engine.prototype.setStencilOperationFail = function (operation) {
  7131. this._stencilState.stencilOpStencilFail = operation;
  7132. };
  7133. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7134. this._stencilState.stencilOpDepthFail = operation;
  7135. };
  7136. Engine.prototype.setStencilOperationPass = function (operation) {
  7137. this._stencilState.stencilOpStencilDepthPass = operation;
  7138. };
  7139. /**
  7140. * stop executing a render loop function and remove it from the execution array
  7141. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7142. */
  7143. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7144. if (!renderFunction) {
  7145. this._activeRenderLoops = [];
  7146. return;
  7147. }
  7148. var index = this._activeRenderLoops.indexOf(renderFunction);
  7149. if (index >= 0) {
  7150. this._activeRenderLoops.splice(index, 1);
  7151. }
  7152. };
  7153. Engine.prototype._renderLoop = function () {
  7154. var shouldRender = true;
  7155. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7156. shouldRender = false;
  7157. }
  7158. if (shouldRender) {
  7159. // Start new frame
  7160. this.beginFrame();
  7161. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7162. var renderFunction = this._activeRenderLoops[index];
  7163. renderFunction();
  7164. }
  7165. // Present
  7166. this.endFrame();
  7167. }
  7168. if (this._activeRenderLoops.length > 0) {
  7169. // Register new frame
  7170. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7171. }
  7172. else {
  7173. this._renderingQueueLaunched = false;
  7174. }
  7175. };
  7176. /**
  7177. * Register and execute a render loop. The engine can have more than one render function.
  7178. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7179. * @example
  7180. * engine.runRenderLoop(function () {
  7181. * scene.render()
  7182. * })
  7183. */
  7184. Engine.prototype.runRenderLoop = function (renderFunction) {
  7185. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7186. return;
  7187. }
  7188. this._activeRenderLoops.push(renderFunction);
  7189. if (!this._renderingQueueLaunched) {
  7190. this._renderingQueueLaunched = true;
  7191. this._bindedRenderFunction = this._renderLoop.bind(this);
  7192. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7193. }
  7194. };
  7195. /**
  7196. * Toggle full screen mode.
  7197. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7198. * @param {any} options - an options object to be sent to the requestFullscreen function
  7199. */
  7200. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7201. if (this.isFullscreen) {
  7202. BABYLON.Tools.ExitFullscreen();
  7203. }
  7204. else {
  7205. this._pointerLockRequested = requestPointerLock;
  7206. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7207. }
  7208. };
  7209. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7210. if (stencil === void 0) { stencil = false; }
  7211. this.applyStates();
  7212. var mode = 0;
  7213. if (backBuffer) {
  7214. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7215. mode |= this._gl.COLOR_BUFFER_BIT;
  7216. }
  7217. if (depth) {
  7218. this._gl.clearDepth(1.0);
  7219. mode |= this._gl.DEPTH_BUFFER_BIT;
  7220. }
  7221. if (stencil) {
  7222. this._gl.clearStencil(0);
  7223. mode |= this._gl.STENCIL_BUFFER_BIT;
  7224. }
  7225. this._gl.clear(mode);
  7226. };
  7227. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7228. var gl = this._gl;
  7229. // Save state
  7230. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7231. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7232. // Change state
  7233. gl.enable(gl.SCISSOR_TEST);
  7234. gl.scissor(x, y, width, height);
  7235. // Clear
  7236. this.clear(clearColor, true, true, true);
  7237. // Restore state
  7238. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7239. if (curScissor === true) {
  7240. gl.enable(gl.SCISSOR_TEST);
  7241. }
  7242. else {
  7243. gl.disable(gl.SCISSOR_TEST);
  7244. }
  7245. };
  7246. /**
  7247. * Set the WebGL's viewport
  7248. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7249. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7250. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7251. */
  7252. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7253. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  7254. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  7255. var x = viewport.x || 0;
  7256. var y = viewport.y || 0;
  7257. this._cachedViewport = viewport;
  7258. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7259. };
  7260. /**
  7261. * Directly set the WebGL Viewport
  7262. * The x, y, width & height are directly passed to the WebGL call
  7263. * @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.
  7264. */
  7265. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7266. var currentViewport = this._cachedViewport;
  7267. this._cachedViewport = null;
  7268. this._gl.viewport(x, y, width, height);
  7269. return currentViewport;
  7270. };
  7271. Engine.prototype.beginFrame = function () {
  7272. this._measureFps();
  7273. };
  7274. Engine.prototype.endFrame = function () {
  7275. //force a flush in case we are using a bad OS.
  7276. if (this._badOS) {
  7277. this.flushFramebuffer();
  7278. }
  7279. //submit frame to the vr device, if enabled
  7280. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7281. this._vrDisplayEnabled.submitFrame();
  7282. }
  7283. };
  7284. /**
  7285. * resize the view according to the canvas' size.
  7286. * @example
  7287. * window.addEventListener("resize", function () {
  7288. * engine.resize();
  7289. * });
  7290. */
  7291. Engine.prototype.resize = function () {
  7292. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7293. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7294. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7295. };
  7296. /**
  7297. * force a specific size of the canvas
  7298. * @param {number} width - the new canvas' width
  7299. * @param {number} height - the new canvas' height
  7300. */
  7301. Engine.prototype.setSize = function (width, height) {
  7302. this._renderingCanvas.width = width;
  7303. this._renderingCanvas.height = height;
  7304. for (var index = 0; index < this.scenes.length; index++) {
  7305. var scene = this.scenes[index];
  7306. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7307. var cam = scene.cameras[camIndex];
  7308. cam._currentRenderId = 0;
  7309. }
  7310. }
  7311. };
  7312. //WebVR functions
  7313. Engine.prototype.initWebVR = function () {
  7314. if (!this.vrDisplaysPromise) {
  7315. this._getVRDisplays();
  7316. }
  7317. };
  7318. Engine.prototype.enableVR = function (vrDevice) {
  7319. this._vrDisplayEnabled = vrDevice;
  7320. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7321. };
  7322. Engine.prototype.disableVR = function () {
  7323. if (this._vrDisplayEnabled) {
  7324. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7325. }
  7326. };
  7327. Engine.prototype._getVRDisplays = function () {
  7328. var _this = this;
  7329. var getWebVRDevices = function (devices) {
  7330. var size = devices.length;
  7331. var i = 0;
  7332. _this._vrDisplays = devices.filter(function (device) {
  7333. return devices[i] instanceof VRDisplay;
  7334. });
  7335. return _this._vrDisplays;
  7336. };
  7337. //using a key due to typescript
  7338. if (navigator.getVRDisplays) {
  7339. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7340. }
  7341. };
  7342. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7343. this._currentRenderTarget = texture;
  7344. this.bindUnboundFramebuffer(texture._framebuffer);
  7345. var gl = this._gl;
  7346. if (texture.isCube) {
  7347. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7348. }
  7349. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7350. this.wipeCaches();
  7351. };
  7352. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7353. if (this._currentFramebuffer !== framebuffer) {
  7354. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7355. this._currentFramebuffer = framebuffer;
  7356. }
  7357. };
  7358. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7359. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7360. this._currentRenderTarget = null;
  7361. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7362. var gl = this._gl;
  7363. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7364. gl.generateMipmap(gl.TEXTURE_2D);
  7365. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7366. }
  7367. this.bindUnboundFramebuffer(null);
  7368. };
  7369. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7370. if (texture.generateMipMaps) {
  7371. var gl = this._gl;
  7372. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7373. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7374. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7375. }
  7376. };
  7377. Engine.prototype.flushFramebuffer = function () {
  7378. this._gl.flush();
  7379. };
  7380. Engine.prototype.restoreDefaultFramebuffer = function () {
  7381. this._currentRenderTarget = null;
  7382. this.bindUnboundFramebuffer(null);
  7383. this.setViewport(this._cachedViewport);
  7384. this.wipeCaches();
  7385. };
  7386. // VBOs
  7387. Engine.prototype._resetVertexBufferBinding = function () {
  7388. this.bindArrayBuffer(null);
  7389. this._cachedVertexBuffers = null;
  7390. };
  7391. Engine.prototype.createVertexBuffer = function (vertices) {
  7392. var vbo = this._gl.createBuffer();
  7393. this.bindArrayBuffer(vbo);
  7394. if (vertices instanceof Float32Array) {
  7395. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7396. }
  7397. else {
  7398. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7399. }
  7400. this._resetVertexBufferBinding();
  7401. vbo.references = 1;
  7402. return vbo;
  7403. };
  7404. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7405. var vbo = this._gl.createBuffer();
  7406. this.bindArrayBuffer(vbo);
  7407. if (vertices instanceof Float32Array) {
  7408. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7409. }
  7410. else {
  7411. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7412. }
  7413. this._resetVertexBufferBinding();
  7414. vbo.references = 1;
  7415. return vbo;
  7416. };
  7417. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7418. this.bindArrayBuffer(vertexBuffer);
  7419. if (offset === undefined) {
  7420. offset = 0;
  7421. }
  7422. if (count === undefined) {
  7423. if (vertices instanceof Float32Array) {
  7424. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7425. }
  7426. else {
  7427. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7428. }
  7429. }
  7430. else {
  7431. if (vertices instanceof Float32Array) {
  7432. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7433. }
  7434. else {
  7435. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7436. }
  7437. }
  7438. this._resetVertexBufferBinding();
  7439. };
  7440. Engine.prototype._resetIndexBufferBinding = function () {
  7441. this.bindIndexBuffer(null);
  7442. this._cachedIndexBuffer = null;
  7443. };
  7444. Engine.prototype.createIndexBuffer = function (indices) {
  7445. var vbo = this._gl.createBuffer();
  7446. this.bindIndexBuffer(vbo);
  7447. // Check for 32 bits indices
  7448. var arrayBuffer;
  7449. var need32Bits = false;
  7450. if (this._caps.uintIndices) {
  7451. for (var index = 0; index < indices.length; index++) {
  7452. if (indices[index] > 65535) {
  7453. need32Bits = true;
  7454. break;
  7455. }
  7456. }
  7457. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7458. }
  7459. else {
  7460. arrayBuffer = new Uint16Array(indices);
  7461. }
  7462. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7463. this._resetIndexBufferBinding();
  7464. vbo.references = 1;
  7465. vbo.is32Bits = need32Bits;
  7466. return vbo;
  7467. };
  7468. Engine.prototype.bindArrayBuffer = function (buffer) {
  7469. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7470. };
  7471. Engine.prototype.bindIndexBuffer = function (buffer) {
  7472. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7473. };
  7474. Engine.prototype.bindBuffer = function (buffer, target) {
  7475. if (this._currentBoundBuffer[target] !== buffer) {
  7476. this._gl.bindBuffer(target, buffer);
  7477. this._currentBoundBuffer[target] = buffer;
  7478. }
  7479. };
  7480. Engine.prototype.updateArrayBuffer = function (data) {
  7481. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7482. };
  7483. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7484. var pointer = this._currentBufferPointers[indx];
  7485. var changed = false;
  7486. if (!pointer) {
  7487. changed = true;
  7488. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7489. }
  7490. else {
  7491. if (pointer.buffer !== buffer) {
  7492. pointer.buffer = buffer;
  7493. changed = true;
  7494. }
  7495. if (pointer.size !== size) {
  7496. pointer.size = size;
  7497. changed = true;
  7498. }
  7499. if (pointer.type !== type) {
  7500. pointer.type = type;
  7501. changed = true;
  7502. }
  7503. if (pointer.normalized !== normalized) {
  7504. pointer.normalized = normalized;
  7505. changed = true;
  7506. }
  7507. if (pointer.stride !== stride) {
  7508. pointer.stride = stride;
  7509. changed = true;
  7510. }
  7511. if (pointer.offset !== offset) {
  7512. pointer.offset = offset;
  7513. changed = true;
  7514. }
  7515. }
  7516. if (changed) {
  7517. this.bindArrayBuffer(buffer);
  7518. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7519. }
  7520. };
  7521. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7522. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7523. this._cachedVertexBuffers = vertexBuffer;
  7524. this._cachedEffectForVertexBuffers = effect;
  7525. var attributesCount = effect.getAttributesCount();
  7526. var offset = 0;
  7527. for (var index = 0; index < attributesCount; index++) {
  7528. if (index < vertexDeclaration.length) {
  7529. var order = effect.getAttributeLocation(index);
  7530. if (order >= 0) {
  7531. if (!this._vertexAttribArraysEnabled[order]) {
  7532. this._gl.enableVertexAttribArray(order);
  7533. this._vertexAttribArraysEnabled[order] = true;
  7534. }
  7535. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7536. }
  7537. offset += vertexDeclaration[index] * 4;
  7538. }
  7539. else {
  7540. //disable effect attributes that have no data
  7541. var order = effect.getAttributeLocation(index);
  7542. if (this._vertexAttribArraysEnabled[order]) {
  7543. this._gl.disableVertexAttribArray(order);
  7544. this._vertexAttribArraysEnabled[order] = false;
  7545. }
  7546. }
  7547. }
  7548. }
  7549. if (this._cachedIndexBuffer !== indexBuffer) {
  7550. this._cachedIndexBuffer = indexBuffer;
  7551. this.bindIndexBuffer(indexBuffer);
  7552. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7553. }
  7554. };
  7555. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7556. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7557. this._cachedVertexBuffers = vertexBuffers;
  7558. this._cachedEffectForVertexBuffers = effect;
  7559. var attributes = effect.getAttributesNames();
  7560. for (var index = 0; index < attributes.length; index++) {
  7561. var order = effect.getAttributeLocation(index);
  7562. if (order >= 0) {
  7563. var vertexBuffer = vertexBuffers[attributes[index]];
  7564. if (!vertexBuffer) {
  7565. if (this._vertexAttribArraysEnabled[order]) {
  7566. this._gl.disableVertexAttribArray(order);
  7567. this._vertexAttribArraysEnabled[order] = false;
  7568. }
  7569. continue;
  7570. }
  7571. if (!this._vertexAttribArraysEnabled[order]) {
  7572. this._gl.enableVertexAttribArray(order);
  7573. this._vertexAttribArraysEnabled[order] = true;
  7574. }
  7575. var buffer = vertexBuffer.getBuffer();
  7576. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7577. if (vertexBuffer.getIsInstanced()) {
  7578. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7579. this._currentInstanceLocations.push(order);
  7580. this._currentInstanceBuffers.push(buffer);
  7581. }
  7582. }
  7583. }
  7584. }
  7585. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7586. this._cachedIndexBuffer = indexBuffer;
  7587. this.bindIndexBuffer(indexBuffer);
  7588. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7589. }
  7590. };
  7591. Engine.prototype.unbindInstanceAttributes = function () {
  7592. var boundBuffer;
  7593. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7594. var instancesBuffer = this._currentInstanceBuffers[i];
  7595. if (boundBuffer != instancesBuffer) {
  7596. boundBuffer = instancesBuffer;
  7597. this.bindArrayBuffer(instancesBuffer);
  7598. }
  7599. var offsetLocation = this._currentInstanceLocations[i];
  7600. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7601. }
  7602. this._currentInstanceBuffers.length = 0;
  7603. this._currentInstanceLocations.length = 0;
  7604. };
  7605. Engine.prototype._releaseBuffer = function (buffer) {
  7606. buffer.references--;
  7607. if (buffer.references === 0) {
  7608. this._gl.deleteBuffer(buffer);
  7609. return true;
  7610. }
  7611. return false;
  7612. };
  7613. Engine.prototype.createInstancesBuffer = function (capacity) {
  7614. var buffer = this._gl.createBuffer();
  7615. buffer.capacity = capacity;
  7616. this.bindArrayBuffer(buffer);
  7617. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7618. return buffer;
  7619. };
  7620. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7621. this._gl.deleteBuffer(buffer);
  7622. };
  7623. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7624. this.bindArrayBuffer(instancesBuffer);
  7625. if (data) {
  7626. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7627. }
  7628. if (offsetLocations[0].index !== undefined) {
  7629. var stride = 0;
  7630. for (var i = 0; i < offsetLocations.length; i++) {
  7631. var ai = offsetLocations[i];
  7632. stride += ai.attributeSize * 4;
  7633. }
  7634. for (var i = 0; i < offsetLocations.length; i++) {
  7635. var ai = offsetLocations[i];
  7636. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7637. this._gl.enableVertexAttribArray(ai.index);
  7638. this._vertexAttribArraysEnabled[ai.index] = true;
  7639. }
  7640. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7641. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7642. this._currentInstanceLocations.push(ai.index);
  7643. this._currentInstanceBuffers.push(instancesBuffer);
  7644. }
  7645. }
  7646. else {
  7647. for (var index = 0; index < 4; index++) {
  7648. var offsetLocation = offsetLocations[index];
  7649. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7650. this._gl.enableVertexAttribArray(offsetLocation);
  7651. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7652. }
  7653. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7654. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7655. this._currentInstanceLocations.push(offsetLocation);
  7656. this._currentInstanceBuffers.push(instancesBuffer);
  7657. }
  7658. }
  7659. };
  7660. Engine.prototype.applyStates = function () {
  7661. this._depthCullingState.apply(this._gl);
  7662. this._stencilState.apply(this._gl);
  7663. this._alphaState.apply(this._gl);
  7664. };
  7665. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7666. // Apply states
  7667. this.applyStates();
  7668. this._drawCalls.addCount(1, false);
  7669. // Render
  7670. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7671. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7672. if (instancesCount) {
  7673. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7674. return;
  7675. }
  7676. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7677. };
  7678. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7679. // Apply states
  7680. this.applyStates();
  7681. this._drawCalls.addCount(1, false);
  7682. if (instancesCount) {
  7683. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7684. return;
  7685. }
  7686. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7687. };
  7688. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7689. // Apply states
  7690. this.applyStates();
  7691. this._drawCalls.addCount(1, false);
  7692. if (instancesCount) {
  7693. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7694. return;
  7695. }
  7696. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7697. };
  7698. // Shaders
  7699. Engine.prototype._releaseEffect = function (effect) {
  7700. if (this._compiledEffects[effect._key]) {
  7701. delete this._compiledEffects[effect._key];
  7702. if (effect.getProgram()) {
  7703. this._gl.deleteProgram(effect.getProgram());
  7704. }
  7705. }
  7706. };
  7707. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7708. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7709. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7710. var name = vertex + "+" + fragment + "@" + defines;
  7711. if (this._compiledEffects[name]) {
  7712. return this._compiledEffects[name];
  7713. }
  7714. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7715. effect._key = name;
  7716. this._compiledEffects[name] = effect;
  7717. return effect;
  7718. };
  7719. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7720. if (uniformsNames === void 0) { uniformsNames = []; }
  7721. if (samplers === void 0) { samplers = []; }
  7722. if (defines === void 0) { defines = ""; }
  7723. return this.createEffect({
  7724. vertex: "particles",
  7725. fragmentElement: fragmentName
  7726. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7727. };
  7728. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7729. context = context || this._gl;
  7730. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7731. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7732. var shaderProgram = context.createProgram();
  7733. context.attachShader(shaderProgram, vertexShader);
  7734. context.attachShader(shaderProgram, fragmentShader);
  7735. context.linkProgram(shaderProgram);
  7736. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7737. if (!linked) {
  7738. var error = context.getProgramInfoLog(shaderProgram);
  7739. if (error) {
  7740. throw new Error(error);
  7741. }
  7742. }
  7743. context.deleteShader(vertexShader);
  7744. context.deleteShader(fragmentShader);
  7745. return shaderProgram;
  7746. };
  7747. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7748. var results = [];
  7749. for (var index = 0; index < uniformsNames.length; index++) {
  7750. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7751. }
  7752. return results;
  7753. };
  7754. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7755. var results = [];
  7756. for (var index = 0; index < attributesNames.length; index++) {
  7757. try {
  7758. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7759. }
  7760. catch (e) {
  7761. results.push(-1);
  7762. }
  7763. }
  7764. return results;
  7765. };
  7766. Engine.prototype.enableEffect = function (effect) {
  7767. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7768. // if (effect && effect.onBind) {
  7769. // effect.onBind(effect);
  7770. // }
  7771. // return;
  7772. //}
  7773. // Use program
  7774. this.setProgram(effect.getProgram());
  7775. this._currentEffect = effect;
  7776. if (effect.onBind) {
  7777. effect.onBind(effect);
  7778. }
  7779. };
  7780. Engine.prototype.setIntArray = function (uniform, array) {
  7781. if (!uniform)
  7782. return;
  7783. this._gl.uniform1iv(uniform, array);
  7784. };
  7785. Engine.prototype.setIntArray2 = function (uniform, array) {
  7786. if (!uniform || array.length % 2 !== 0)
  7787. return;
  7788. this._gl.uniform2iv(uniform, array);
  7789. };
  7790. Engine.prototype.setIntArray3 = function (uniform, array) {
  7791. if (!uniform || array.length % 3 !== 0)
  7792. return;
  7793. this._gl.uniform3iv(uniform, array);
  7794. };
  7795. Engine.prototype.setIntArray4 = function (uniform, array) {
  7796. if (!uniform || array.length % 4 !== 0)
  7797. return;
  7798. this._gl.uniform4iv(uniform, array);
  7799. };
  7800. Engine.prototype.setFloatArray = function (uniform, array) {
  7801. if (!uniform)
  7802. return;
  7803. this._gl.uniform1fv(uniform, array);
  7804. };
  7805. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7806. if (!uniform || array.length % 2 !== 0)
  7807. return;
  7808. this._gl.uniform2fv(uniform, array);
  7809. };
  7810. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7811. if (!uniform || array.length % 3 !== 0)
  7812. return;
  7813. this._gl.uniform3fv(uniform, array);
  7814. };
  7815. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7816. if (!uniform || array.length % 4 !== 0)
  7817. return;
  7818. this._gl.uniform4fv(uniform, array);
  7819. };
  7820. Engine.prototype.setArray = function (uniform, array) {
  7821. if (!uniform)
  7822. return;
  7823. this._gl.uniform1fv(uniform, array);
  7824. };
  7825. Engine.prototype.setArray2 = function (uniform, array) {
  7826. if (!uniform || array.length % 2 !== 0)
  7827. return;
  7828. this._gl.uniform2fv(uniform, array);
  7829. };
  7830. Engine.prototype.setArray3 = function (uniform, array) {
  7831. if (!uniform || array.length % 3 !== 0)
  7832. return;
  7833. this._gl.uniform3fv(uniform, array);
  7834. };
  7835. Engine.prototype.setArray4 = function (uniform, array) {
  7836. if (!uniform || array.length % 4 !== 0)
  7837. return;
  7838. this._gl.uniform4fv(uniform, array);
  7839. };
  7840. Engine.prototype.setMatrices = function (uniform, matrices) {
  7841. if (!uniform)
  7842. return;
  7843. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7844. };
  7845. Engine.prototype.setMatrix = function (uniform, matrix) {
  7846. if (!uniform)
  7847. return;
  7848. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7849. };
  7850. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7851. if (!uniform)
  7852. return;
  7853. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7854. };
  7855. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7856. if (!uniform)
  7857. return;
  7858. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7859. };
  7860. Engine.prototype.setFloat = function (uniform, value) {
  7861. if (!uniform)
  7862. return;
  7863. this._gl.uniform1f(uniform, value);
  7864. };
  7865. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7866. if (!uniform)
  7867. return;
  7868. this._gl.uniform2f(uniform, x, y);
  7869. };
  7870. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7871. if (!uniform)
  7872. return;
  7873. this._gl.uniform3f(uniform, x, y, z);
  7874. };
  7875. Engine.prototype.setBool = function (uniform, bool) {
  7876. if (!uniform)
  7877. return;
  7878. this._gl.uniform1i(uniform, bool);
  7879. };
  7880. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7881. if (!uniform)
  7882. return;
  7883. this._gl.uniform4f(uniform, x, y, z, w);
  7884. };
  7885. Engine.prototype.setColor3 = function (uniform, color3) {
  7886. if (!uniform)
  7887. return;
  7888. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7889. };
  7890. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7891. if (!uniform)
  7892. return;
  7893. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7894. };
  7895. // States
  7896. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7897. if (zOffset === void 0) { zOffset = 0; }
  7898. if (reverseSide === void 0) { reverseSide = false; }
  7899. // Culling
  7900. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7901. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7902. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7903. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7904. if (culling) {
  7905. this._depthCullingState.cullFace = cullFace;
  7906. this._depthCullingState.cull = true;
  7907. }
  7908. else {
  7909. this._depthCullingState.cull = false;
  7910. }
  7911. }
  7912. // Z offset
  7913. this._depthCullingState.zOffset = zOffset;
  7914. };
  7915. Engine.prototype.setDepthBuffer = function (enable) {
  7916. this._depthCullingState.depthTest = enable;
  7917. };
  7918. Engine.prototype.getDepthWrite = function () {
  7919. return this._depthCullingState.depthMask;
  7920. };
  7921. Engine.prototype.setDepthWrite = function (enable) {
  7922. this._depthCullingState.depthMask = enable;
  7923. };
  7924. Engine.prototype.setColorWrite = function (enable) {
  7925. this._gl.colorMask(enable, enable, enable, enable);
  7926. };
  7927. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7928. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7929. if (this._alphaMode === mode) {
  7930. return;
  7931. }
  7932. switch (mode) {
  7933. case Engine.ALPHA_DISABLE:
  7934. this._alphaState.alphaBlend = false;
  7935. break;
  7936. case Engine.ALPHA_COMBINE:
  7937. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7938. this._alphaState.alphaBlend = true;
  7939. break;
  7940. case Engine.ALPHA_ONEONE:
  7941. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7942. this._alphaState.alphaBlend = true;
  7943. break;
  7944. case Engine.ALPHA_ADD:
  7945. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7946. this._alphaState.alphaBlend = true;
  7947. break;
  7948. case Engine.ALPHA_SUBTRACT:
  7949. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7950. this._alphaState.alphaBlend = true;
  7951. break;
  7952. case Engine.ALPHA_MULTIPLY:
  7953. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7954. this._alphaState.alphaBlend = true;
  7955. break;
  7956. case Engine.ALPHA_MAXIMIZED:
  7957. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7958. this._alphaState.alphaBlend = true;
  7959. break;
  7960. }
  7961. if (!noDepthWriteChange) {
  7962. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7963. }
  7964. this._alphaMode = mode;
  7965. };
  7966. Engine.prototype.getAlphaMode = function () {
  7967. return this._alphaMode;
  7968. };
  7969. Engine.prototype.setAlphaTesting = function (enable) {
  7970. this._alphaTest = enable;
  7971. };
  7972. Engine.prototype.getAlphaTesting = function () {
  7973. return this._alphaTest;
  7974. };
  7975. // Textures
  7976. Engine.prototype.wipeCaches = function () {
  7977. this.resetTextureCache();
  7978. this._currentEffect = null;
  7979. this._stencilState.reset();
  7980. this._depthCullingState.reset();
  7981. this.setDepthFunctionToLessOrEqual();
  7982. this._alphaState.reset();
  7983. this._cachedVertexBuffers = null;
  7984. this._cachedIndexBuffer = null;
  7985. this._cachedEffectForVertexBuffers = null;
  7986. };
  7987. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7988. var gl = this._gl;
  7989. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7990. var magFilter = gl.NEAREST;
  7991. var minFilter = gl.NEAREST;
  7992. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7993. magFilter = gl.LINEAR;
  7994. minFilter = gl.LINEAR;
  7995. }
  7996. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7997. magFilter = gl.LINEAR;
  7998. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7999. }
  8000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  8001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  8002. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8003. texture.samplingMode = samplingMode;
  8004. };
  8005. /**
  8006. * Set the compressed texture format to use, based on the formats you have,
  8007. * the formats supported by the hardware / browser, and those currently implemented
  8008. * in BJS.
  8009. *
  8010. * Note: The result of this call is not taken into account texture is base64 or when
  8011. * using a database / manifest.
  8012. *
  8013. * @param {Array<string>} formatsAvailable - Extension names including dot. Case
  8014. * and order do not matter.
  8015. * @returns The extension selected.
  8016. */
  8017. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8018. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8019. // code to allow the formats to be added as they can be developed / hw tested
  8020. if (this._texturesSupported[i] === '.astc')
  8021. continue;
  8022. if (this._texturesSupported[i] === '.pvr')
  8023. continue;
  8024. if (this._texturesSupported[i] === '.etc1')
  8025. continue;
  8026. if (this._texturesSupported[i] === '.etc2')
  8027. continue;
  8028. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8029. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8030. return this._textureFormatInUse = this._texturesSupported[i];
  8031. }
  8032. }
  8033. }
  8034. // actively set format to nothing, to allow this to be called more than once
  8035. // and possibly fail the 2nd time
  8036. return this._textureFormatInUse = null;
  8037. };
  8038. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  8039. var _this = this;
  8040. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8041. if (onLoad === void 0) { onLoad = null; }
  8042. if (onError === void 0) { onError = null; }
  8043. if (buffer === void 0) { buffer = null; }
  8044. var texture = this._gl.createTexture();
  8045. var extension;
  8046. var fromData = false;
  8047. if (url.substr(0, 5) === "data:") {
  8048. fromData = true;
  8049. }
  8050. if (!fromData) {
  8051. var lastDot = url.lastIndexOf('.');
  8052. extension = url.substring(lastDot).toLowerCase();
  8053. if (this._textureFormatInUse && !fromData && !scene.database) {
  8054. extension = this._textureFormatInUse;
  8055. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8056. }
  8057. }
  8058. else {
  8059. var oldUrl = url;
  8060. fromData = oldUrl.split(':');
  8061. url = oldUrl;
  8062. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8063. }
  8064. var isDDS = (extension === ".dds");
  8065. var isTGA = (extension === ".tga");
  8066. scene._addPendingData(texture);
  8067. texture.url = url;
  8068. texture.noMipmap = noMipmap;
  8069. texture.references = 1;
  8070. texture.samplingMode = samplingMode;
  8071. texture.onLoadedCallbacks = [onLoad];
  8072. this._loadedTexturesCache.push(texture);
  8073. var onerror = function () {
  8074. scene._removePendingData(texture);
  8075. if (onError) {
  8076. onError();
  8077. }
  8078. };
  8079. var callback;
  8080. if (isTGA) {
  8081. callback = function (arrayBuffer) {
  8082. var data = new Uint8Array(arrayBuffer);
  8083. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8084. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8085. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8086. }, samplingMode);
  8087. };
  8088. if (!(fromData instanceof Array))
  8089. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  8090. callback(arrayBuffer);
  8091. }, null, scene.database, true, onerror);
  8092. else
  8093. callback(buffer);
  8094. }
  8095. else if (isDDS) {
  8096. callback = function (data) {
  8097. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8098. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8099. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8100. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8101. }, samplingMode);
  8102. };
  8103. if (!(fromData instanceof Array))
  8104. BABYLON.Tools.LoadFile(url, function (data) {
  8105. callback(data);
  8106. }, null, scene.database, true, onerror);
  8107. else
  8108. callback(buffer);
  8109. }
  8110. else {
  8111. var onload = function (img) {
  8112. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8113. var isPot = (img.width === potWidth && img.height === potHeight);
  8114. if (!isPot) {
  8115. _this._prepareWorkingCanvas();
  8116. _this._workingCanvas.width = potWidth;
  8117. _this._workingCanvas.height = potHeight;
  8118. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8119. _this._workingContext.imageSmoothingEnabled = false;
  8120. _this._workingContext.mozImageSmoothingEnabled = false;
  8121. _this._workingContext.oImageSmoothingEnabled = false;
  8122. _this._workingContext.webkitImageSmoothingEnabled = false;
  8123. _this._workingContext.msImageSmoothingEnabled = false;
  8124. }
  8125. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8126. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8127. _this._workingContext.imageSmoothingEnabled = true;
  8128. _this._workingContext.mozImageSmoothingEnabled = true;
  8129. _this._workingContext.oImageSmoothingEnabled = true;
  8130. _this._workingContext.webkitImageSmoothingEnabled = true;
  8131. _this._workingContext.msImageSmoothingEnabled = true;
  8132. }
  8133. }
  8134. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8135. }, samplingMode);
  8136. };
  8137. if (!(fromData instanceof Array))
  8138. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8139. else
  8140. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8141. }
  8142. return texture;
  8143. };
  8144. Engine.prototype._getInternalFormat = function (format) {
  8145. var internalFormat = this._gl.RGBA;
  8146. switch (format) {
  8147. case Engine.TEXTUREFORMAT_ALPHA:
  8148. internalFormat = this._gl.ALPHA;
  8149. break;
  8150. case Engine.TEXTUREFORMAT_LUMINANCE:
  8151. internalFormat = this._gl.LUMINANCE;
  8152. break;
  8153. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8154. internalFormat = this._gl.LUMINANCE_ALPHA;
  8155. break;
  8156. case Engine.TEXTUREFORMAT_RGB:
  8157. internalFormat = this._gl.RGB;
  8158. break;
  8159. case Engine.TEXTUREFORMAT_RGBA:
  8160. internalFormat = this._gl.RGBA;
  8161. break;
  8162. }
  8163. return internalFormat;
  8164. };
  8165. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8166. if (compression === void 0) { compression = null; }
  8167. var internalFormat = this._getInternalFormat(format);
  8168. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8169. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8170. if (texture._width % 4 !== 0) {
  8171. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8172. }
  8173. if (compression) {
  8174. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8175. }
  8176. else {
  8177. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8178. }
  8179. if (texture.generateMipMaps) {
  8180. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8181. }
  8182. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8183. this.resetTextureCache();
  8184. texture.isReady = true;
  8185. };
  8186. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8187. if (compression === void 0) { compression = null; }
  8188. var texture = this._gl.createTexture();
  8189. texture._baseWidth = width;
  8190. texture._baseHeight = height;
  8191. texture._width = width;
  8192. texture._height = height;
  8193. texture.references = 1;
  8194. this.updateRawTexture(texture, data, format, invertY, compression);
  8195. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8196. // Filters
  8197. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8198. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8199. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8200. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8201. texture.samplingMode = samplingMode;
  8202. this._loadedTexturesCache.push(texture);
  8203. return texture;
  8204. };
  8205. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8206. var texture = this._gl.createTexture();
  8207. texture._baseWidth = width;
  8208. texture._baseHeight = height;
  8209. if (generateMipMaps) {
  8210. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8211. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8212. }
  8213. this.resetTextureCache();
  8214. texture._width = width;
  8215. texture._height = height;
  8216. texture.isReady = false;
  8217. texture.generateMipMaps = generateMipMaps;
  8218. texture.references = 1;
  8219. texture.samplingMode = samplingMode;
  8220. this.updateTextureSamplingMode(samplingMode, texture);
  8221. this._loadedTexturesCache.push(texture);
  8222. return texture;
  8223. };
  8224. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8225. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8226. if (texture.isCube) {
  8227. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8228. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8229. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8230. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8231. }
  8232. else {
  8233. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8234. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8235. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8236. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8237. }
  8238. };
  8239. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8240. if (premulAlpha === void 0) { premulAlpha = false; }
  8241. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8242. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8243. if (premulAlpha) {
  8244. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8245. }
  8246. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8247. if (texture.generateMipMaps) {
  8248. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8249. }
  8250. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8251. if (premulAlpha) {
  8252. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8253. }
  8254. this.resetTextureCache();
  8255. texture.isReady = true;
  8256. };
  8257. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8258. if (texture._isDisabled) {
  8259. return;
  8260. }
  8261. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8262. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8263. try {
  8264. // Testing video texture support
  8265. if (this._videoTextureSupported === undefined) {
  8266. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8267. if (this._gl.getError() !== 0) {
  8268. this._videoTextureSupported = false;
  8269. }
  8270. else {
  8271. this._videoTextureSupported = true;
  8272. }
  8273. }
  8274. // Copy video through the current working canvas if video texture is not supported
  8275. if (!this._videoTextureSupported) {
  8276. if (!texture._workingCanvas) {
  8277. texture._workingCanvas = document.createElement("canvas");
  8278. texture._workingContext = texture._workingCanvas.getContext("2d");
  8279. texture._workingCanvas.width = texture._width;
  8280. texture._workingCanvas.height = texture._height;
  8281. }
  8282. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8283. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8284. }
  8285. else {
  8286. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8287. }
  8288. if (texture.generateMipMaps) {
  8289. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8290. }
  8291. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8292. this.resetTextureCache();
  8293. texture.isReady = true;
  8294. }
  8295. catch (ex) {
  8296. // Something unexpected
  8297. // Let's disable the texture
  8298. texture._isDisabled = true;
  8299. }
  8300. };
  8301. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8302. // old version had a "generateMipMaps" arg instead of options.
  8303. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8304. // in the same way, generateDepthBuffer is defaulted to true
  8305. var generateMipMaps = false;
  8306. var generateDepthBuffer = true;
  8307. var generateStencilBuffer = false;
  8308. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8309. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8310. if (options !== undefined) {
  8311. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8312. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8313. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8314. type = options.type === undefined ? type : options.type;
  8315. if (options.samplingMode !== undefined) {
  8316. samplingMode = options.samplingMode;
  8317. }
  8318. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8319. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8320. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8321. }
  8322. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8323. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8324. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8325. }
  8326. }
  8327. var gl = this._gl;
  8328. var texture = gl.createTexture();
  8329. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8330. var width = size.width || size;
  8331. var height = size.height || size;
  8332. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8333. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8334. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8335. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8336. }
  8337. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8341. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8342. var depthStencilBuffer;
  8343. // Create the depth/stencil buffer
  8344. if (generateStencilBuffer) {
  8345. depthStencilBuffer = gl.createRenderbuffer();
  8346. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8348. }
  8349. else if (generateDepthBuffer) {
  8350. depthStencilBuffer = gl.createRenderbuffer();
  8351. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8352. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8353. }
  8354. // Create the framebuffer
  8355. var framebuffer = gl.createFramebuffer();
  8356. this.bindUnboundFramebuffer(framebuffer);
  8357. // Manage attachments
  8358. if (generateStencilBuffer) {
  8359. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8360. }
  8361. else if (generateDepthBuffer) {
  8362. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8363. }
  8364. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8365. if (generateMipMaps) {
  8366. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8367. }
  8368. // Unbind
  8369. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8370. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8371. this.bindUnboundFramebuffer(null);
  8372. texture._framebuffer = framebuffer;
  8373. if (generateDepthBuffer) {
  8374. texture._depthBuffer = depthStencilBuffer;
  8375. }
  8376. texture._baseWidth = width;
  8377. texture._baseHeight = height;
  8378. texture._width = width;
  8379. texture._height = height;
  8380. texture.isReady = true;
  8381. texture.generateMipMaps = generateMipMaps;
  8382. texture.references = 1;
  8383. texture.samplingMode = samplingMode;
  8384. texture.type = type;
  8385. this.resetTextureCache();
  8386. this._loadedTexturesCache.push(texture);
  8387. return texture;
  8388. };
  8389. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8390. var gl = this._gl;
  8391. var texture = gl.createTexture();
  8392. var generateMipMaps = true;
  8393. var generateDepthBuffer = true;
  8394. var generateStencilBuffer = false;
  8395. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8396. if (options !== undefined) {
  8397. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8398. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8399. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8400. if (options.samplingMode !== undefined) {
  8401. samplingMode = options.samplingMode;
  8402. }
  8403. }
  8404. texture.isCube = true;
  8405. texture.references = 1;
  8406. texture.generateMipMaps = generateMipMaps;
  8407. texture.references = 1;
  8408. texture.samplingMode = samplingMode;
  8409. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8410. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8411. for (var face = 0; face < 6; face++) {
  8412. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8413. }
  8414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8415. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8416. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8417. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8418. // Create the depth buffer
  8419. var depthStencilBuffer;
  8420. // Create the depth/stencil buffer
  8421. if (generateStencilBuffer) {
  8422. depthStencilBuffer = gl.createRenderbuffer();
  8423. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8424. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8425. }
  8426. else if (generateDepthBuffer) {
  8427. depthStencilBuffer = gl.createRenderbuffer();
  8428. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8429. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8430. }
  8431. // Create the framebuffer
  8432. var framebuffer = gl.createFramebuffer();
  8433. this.bindUnboundFramebuffer(framebuffer);
  8434. // Manage attachments
  8435. if (generateStencilBuffer) {
  8436. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8437. }
  8438. else if (generateDepthBuffer) {
  8439. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8440. }
  8441. // Mipmaps
  8442. if (texture.generateMipMaps) {
  8443. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8444. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8445. }
  8446. // Unbind
  8447. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8448. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8449. this.bindUnboundFramebuffer(null);
  8450. texture._framebuffer = framebuffer;
  8451. if (generateDepthBuffer) {
  8452. texture._depthBuffer = depthStencilBuffer;
  8453. }
  8454. texture._width = size;
  8455. texture._height = size;
  8456. texture.isReady = true;
  8457. this.resetTextureCache();
  8458. this._loadedTexturesCache.push(texture);
  8459. return texture;
  8460. };
  8461. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8462. var _this = this;
  8463. if (onLoad === void 0) { onLoad = null; }
  8464. if (onError === void 0) { onError = null; }
  8465. var gl = this._gl;
  8466. var texture = gl.createTexture();
  8467. texture.isCube = true;
  8468. texture.url = rootUrl;
  8469. texture.references = 1;
  8470. texture.onLoadedCallbacks = [];
  8471. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8472. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8473. if (isDDS) {
  8474. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8475. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8476. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8477. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8478. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8479. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8480. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8481. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8482. }
  8483. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8487. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8488. _this.resetTextureCache();
  8489. texture._width = info.width;
  8490. texture._height = info.height;
  8491. texture.isReady = true;
  8492. }, null, null, true, onError);
  8493. }
  8494. else {
  8495. cascadeLoad(rootUrl, scene, function (imgs) {
  8496. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8497. var height = width;
  8498. _this._prepareWorkingCanvas();
  8499. _this._workingCanvas.width = width;
  8500. _this._workingCanvas.height = height;
  8501. var faces = [
  8502. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8503. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8504. ];
  8505. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8506. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8507. for (var index = 0; index < faces.length; index++) {
  8508. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8509. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8510. }
  8511. if (!noMipmap) {
  8512. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8513. }
  8514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8518. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8519. _this.resetTextureCache();
  8520. texture._width = width;
  8521. texture._height = height;
  8522. texture.isReady = true;
  8523. texture.onLoadedCallbacks.forEach(function (callback) {
  8524. callback();
  8525. });
  8526. if (onLoad) {
  8527. onLoad();
  8528. }
  8529. }, files, onError);
  8530. }
  8531. this._loadedTexturesCache.push(texture);
  8532. return texture;
  8533. };
  8534. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8535. texture._width = width;
  8536. texture._height = height;
  8537. texture._size = width * height;
  8538. texture._baseWidth = width;
  8539. texture._baseHeight = height;
  8540. };
  8541. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8542. var _this = this;
  8543. var gl = this._gl;
  8544. var texture = gl.createTexture();
  8545. scene._addPendingData(texture);
  8546. texture.isCube = true;
  8547. texture.references = 1;
  8548. texture.url = url;
  8549. var internalFormat = this._getInternalFormat(format);
  8550. var textureType = gl.UNSIGNED_BYTE;
  8551. if (type === Engine.TEXTURETYPE_FLOAT) {
  8552. textureType = gl.FLOAT;
  8553. }
  8554. var width = size;
  8555. var height = width;
  8556. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8557. texture._width = width;
  8558. texture._height = height;
  8559. var onerror = function () {
  8560. scene._removePendingData(texture);
  8561. };
  8562. var internalCallback = function (data) {
  8563. var rgbeDataArrays = callback(data);
  8564. var facesIndex = [
  8565. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8566. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8567. ];
  8568. width = texture._width;
  8569. height = texture._height;
  8570. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8571. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8572. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8573. if (!noMipmap && isPot) {
  8574. if (mipmmapGenerator) {
  8575. var arrayTemp = [];
  8576. // Data are known to be in +X +Y +Z -X -Y -Z
  8577. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8578. arrayTemp.push(rgbeDataArrays[0]); // +X
  8579. arrayTemp.push(rgbeDataArrays[3]); // -X
  8580. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8581. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8582. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8583. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8584. var mipData = mipmmapGenerator(arrayTemp);
  8585. for (var level = 0; level < mipData.length; level++) {
  8586. var mipSize = width >> level;
  8587. // mipData is order in +X -X +Y -Y +Z -Z
  8588. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8589. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8590. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8591. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8592. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8593. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8594. }
  8595. }
  8596. else {
  8597. // Data are known to be in +X +Y +Z -X -Y -Z
  8598. for (var index = 0; index < facesIndex.length; index++) {
  8599. var faceData = rgbeDataArrays[index];
  8600. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8601. }
  8602. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8603. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8604. // By following the webgl standard changes from Revision 7, 2014/11/24
  8605. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8606. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8607. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8608. // Data are known to be in +X +Y +Z -X -Y -Z
  8609. for (var index = 0; index < facesIndex.length; index++) {
  8610. var faceData = rgbeDataArrays[index];
  8611. // Create a new RGBA Face.
  8612. var newFaceData = new Float32Array(width * height * 4);
  8613. for (var x = 0; x < width; x++) {
  8614. for (var y = 0; y < height; y++) {
  8615. var index_1 = (y * width + x) * 3;
  8616. var newIndex = (y * width + x) * 4;
  8617. // Map Old Value to new value.
  8618. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8619. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8620. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8621. // Add fully opaque alpha channel.
  8622. newFaceData[newIndex + 3] = 1;
  8623. }
  8624. }
  8625. // Reupload the face.
  8626. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8627. }
  8628. // Try to generate mipmap again.
  8629. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8630. }
  8631. }
  8632. }
  8633. else {
  8634. noMipmap = true;
  8635. }
  8636. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8639. }
  8640. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8641. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8643. }
  8644. else {
  8645. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8647. }
  8648. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8649. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8650. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8651. texture.isReady = true;
  8652. _this.resetTextureCache();
  8653. scene._removePendingData(texture);
  8654. };
  8655. BABYLON.Tools.LoadFile(url, function (data) {
  8656. internalCallback(data);
  8657. }, onerror, scene.database, true);
  8658. return texture;
  8659. };
  8660. ;
  8661. Engine.prototype._releaseTexture = function (texture) {
  8662. var gl = this._gl;
  8663. if (texture._framebuffer) {
  8664. gl.deleteFramebuffer(texture._framebuffer);
  8665. }
  8666. if (texture._depthBuffer) {
  8667. gl.deleteRenderbuffer(texture._depthBuffer);
  8668. }
  8669. gl.deleteTexture(texture);
  8670. // Unbind channels
  8671. this.unbindAllTextures();
  8672. var index = this._loadedTexturesCache.indexOf(texture);
  8673. if (index !== -1) {
  8674. this._loadedTexturesCache.splice(index, 1);
  8675. }
  8676. };
  8677. Engine.prototype.setProgram = function (program) {
  8678. if (this._currentProgram !== program) {
  8679. this._gl.useProgram(program);
  8680. this._currentProgram = program;
  8681. }
  8682. };
  8683. Engine.prototype.bindSamplers = function (effect) {
  8684. this.setProgram(effect.getProgram());
  8685. var samplers = effect.getSamplers();
  8686. for (var index = 0; index < samplers.length; index++) {
  8687. var uniform = effect.getUniform(samplers[index]);
  8688. this._gl.uniform1i(uniform, index);
  8689. }
  8690. this._currentEffect = null;
  8691. };
  8692. Engine.prototype.activateTexture = function (texture) {
  8693. if (this._activeTexture !== texture) {
  8694. this._gl.activeTexture(texture);
  8695. this._activeTexture = texture;
  8696. }
  8697. };
  8698. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8699. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8700. this._gl.bindTexture(target, texture);
  8701. this._activeTexturesCache[this._activeTexture] = texture;
  8702. }
  8703. };
  8704. Engine.prototype._bindTexture = function (channel, texture) {
  8705. if (channel < 0) {
  8706. return;
  8707. }
  8708. this.activateTexture(this._gl["TEXTURE" + channel]);
  8709. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8710. };
  8711. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8712. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8713. };
  8714. Engine.prototype.unbindAllTextures = function () {
  8715. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8716. this.activateTexture(this._gl["TEXTURE" + channel]);
  8717. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8718. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8719. }
  8720. };
  8721. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8722. if (channel < 0) {
  8723. return;
  8724. }
  8725. this._gl.uniform1i(uniform, channel);
  8726. this._setTexture(channel, texture);
  8727. };
  8728. Engine.prototype._setTexture = function (channel, texture) {
  8729. // Not ready?
  8730. if (!texture || !texture.isReady()) {
  8731. if (this._activeTexturesCache[channel] != null) {
  8732. this.activateTexture(this._gl["TEXTURE" + channel]);
  8733. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8734. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8735. }
  8736. return;
  8737. }
  8738. // Video
  8739. var alreadyActivated = false;
  8740. if (texture instanceof BABYLON.VideoTexture) {
  8741. this.activateTexture(this._gl["TEXTURE" + channel]);
  8742. alreadyActivated = true;
  8743. texture.update();
  8744. }
  8745. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8746. texture.delayLoad();
  8747. return;
  8748. }
  8749. var internalTexture = texture.getInternalTexture();
  8750. if (this._activeTexturesCache[channel] === internalTexture) {
  8751. return;
  8752. }
  8753. if (!alreadyActivated) {
  8754. this.activateTexture(this._gl["TEXTURE" + channel]);
  8755. }
  8756. if (internalTexture.isCube) {
  8757. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8758. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8759. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8760. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8761. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8762. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8763. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8764. }
  8765. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8766. }
  8767. else {
  8768. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8769. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8770. internalTexture._cachedWrapU = texture.wrapU;
  8771. switch (texture.wrapU) {
  8772. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8773. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8774. break;
  8775. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8776. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8777. break;
  8778. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8779. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8780. break;
  8781. }
  8782. }
  8783. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8784. internalTexture._cachedWrapV = texture.wrapV;
  8785. switch (texture.wrapV) {
  8786. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8787. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8788. break;
  8789. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8790. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8791. break;
  8792. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8793. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8794. break;
  8795. }
  8796. }
  8797. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8798. }
  8799. };
  8800. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8801. if (channel < 0) {
  8802. return;
  8803. }
  8804. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8805. this._textureUnits = new Int32Array(textures.length);
  8806. }
  8807. for (var i = 0; i < textures.length; i++) {
  8808. this._textureUnits[i] = channel + i;
  8809. }
  8810. this._gl.uniform1iv(uniform, this._textureUnits);
  8811. for (var index = 0; index < textures.length; index++) {
  8812. this._setTexture(channel + index, textures[index]);
  8813. }
  8814. };
  8815. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8816. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8817. var value = texture.anisotropicFilteringLevel;
  8818. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8819. value = 1;
  8820. }
  8821. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8822. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8823. texture._cachedAnisotropicFilteringLevel = value;
  8824. }
  8825. };
  8826. Engine.prototype.readPixels = function (x, y, width, height) {
  8827. var data = new Uint8Array(height * width * 4);
  8828. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8829. return data;
  8830. };
  8831. /**
  8832. * Add an externaly attached data from its key.
  8833. * This method call will fail and return false, if such key already exists.
  8834. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8835. * @param key the unique key that identifies the data
  8836. * @param data the data object to associate to the key for this Engine instance
  8837. * @return true if no such key were already present and the data was added successfully, false otherwise
  8838. */
  8839. Engine.prototype.addExternalData = function (key, data) {
  8840. return this._externalData.add(key, data);
  8841. };
  8842. /**
  8843. * Get an externaly attached data from its key
  8844. * @param key the unique key that identifies the data
  8845. * @return the associated data, if present (can be null), or undefined if not present
  8846. */
  8847. Engine.prototype.getExternalData = function (key) {
  8848. return this._externalData.get(key);
  8849. };
  8850. /**
  8851. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8852. * @param key the unique key that identifies the data
  8853. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8854. * @return the associated data, can be null if the factory returned null.
  8855. */
  8856. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8857. return this._externalData.getOrAddWithFactory(key, factory);
  8858. };
  8859. /**
  8860. * Remove an externaly attached data from the Engine instance
  8861. * @param key the unique key that identifies the data
  8862. * @return true if the data was successfully removed, false if it doesn't exist
  8863. */
  8864. Engine.prototype.removeExternalData = function (key) {
  8865. return this._externalData.remove(key);
  8866. };
  8867. Engine.prototype.releaseInternalTexture = function (texture) {
  8868. if (!texture) {
  8869. return;
  8870. }
  8871. texture.references--;
  8872. // Final reference ?
  8873. if (texture.references === 0) {
  8874. var texturesCache = this.getLoadedTexturesCache();
  8875. var index = texturesCache.indexOf(texture);
  8876. if (index > -1) {
  8877. texturesCache.splice(index, 1);
  8878. }
  8879. this._releaseTexture(texture);
  8880. }
  8881. };
  8882. Engine.prototype.unbindAllAttributes = function () {
  8883. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8884. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8885. continue;
  8886. }
  8887. this._gl.disableVertexAttribArray(i);
  8888. this._vertexAttribArraysEnabled[i] = false;
  8889. }
  8890. };
  8891. // Dispose
  8892. Engine.prototype.dispose = function () {
  8893. this.hideLoadingUI();
  8894. this.stopRenderLoop();
  8895. // Release scenes
  8896. while (this.scenes.length) {
  8897. this.scenes[0].dispose();
  8898. }
  8899. // Release audio engine
  8900. Engine.audioEngine.dispose();
  8901. // Release effects
  8902. for (var name in this._compiledEffects) {
  8903. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8904. }
  8905. // Unbind
  8906. this.unbindAllAttributes();
  8907. this._gl = null;
  8908. //WebVR
  8909. this.disableVR();
  8910. // Events
  8911. window.removeEventListener("blur", this._onBlur);
  8912. window.removeEventListener("focus", this._onFocus);
  8913. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8914. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8915. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8916. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8917. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8918. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8919. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8920. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8921. };
  8922. // Loading screen
  8923. Engine.prototype.displayLoadingUI = function () {
  8924. this._loadingScreen.displayLoadingUI();
  8925. };
  8926. Engine.prototype.hideLoadingUI = function () {
  8927. this._loadingScreen.hideLoadingUI();
  8928. };
  8929. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8930. get: function () {
  8931. return this._loadingScreen;
  8932. },
  8933. set: function (loadingScreen) {
  8934. this._loadingScreen = loadingScreen;
  8935. },
  8936. enumerable: true,
  8937. configurable: true
  8938. });
  8939. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8940. set: function (text) {
  8941. this._loadingScreen.loadingUIText = text;
  8942. },
  8943. enumerable: true,
  8944. configurable: true
  8945. });
  8946. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8947. set: function (color) {
  8948. this._loadingScreen.loadingUIBackgroundColor = color;
  8949. },
  8950. enumerable: true,
  8951. configurable: true
  8952. });
  8953. Engine.prototype.attachContextLostEvent = function (callback) {
  8954. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8955. };
  8956. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8957. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8958. };
  8959. Engine.prototype.getVertexShaderSource = function (program) {
  8960. var shaders = this._gl.getAttachedShaders(program);
  8961. return this._gl.getShaderSource(shaders[0]);
  8962. };
  8963. Engine.prototype.getFragmentShaderSource = function (program) {
  8964. var shaders = this._gl.getAttachedShaders(program);
  8965. return this._gl.getShaderSource(shaders[1]);
  8966. };
  8967. // FPS
  8968. Engine.prototype.getFps = function () {
  8969. return this.fps;
  8970. };
  8971. Engine.prototype.getDeltaTime = function () {
  8972. return this.deltaTime;
  8973. };
  8974. Engine.prototype._measureFps = function () {
  8975. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8976. var length = this.previousFramesDuration.length;
  8977. if (length >= 2) {
  8978. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8979. }
  8980. if (length >= this.fpsRange) {
  8981. if (length > this.fpsRange) {
  8982. this.previousFramesDuration.splice(0, 1);
  8983. length = this.previousFramesDuration.length;
  8984. }
  8985. var sum = 0;
  8986. for (var id = 0; id < length - 1; id++) {
  8987. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8988. }
  8989. this.fps = 1000.0 / (sum / (length - 1));
  8990. }
  8991. };
  8992. Engine.prototype._canRenderToFloatTexture = function () {
  8993. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8994. };
  8995. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8996. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8997. };
  8998. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8999. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  9000. var tempcanvas = document.createElement("canvas");
  9001. tempcanvas.height = 16;
  9002. tempcanvas.width = 16;
  9003. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  9004. // extension.
  9005. var ext = gl.getExtension(extension);
  9006. if (!ext) {
  9007. return false;
  9008. }
  9009. // setup GLSL program
  9010. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  9011. 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 }";
  9012. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  9013. gl.useProgram(program);
  9014. // look up where the vertex data needs to go.
  9015. var positionLocation = gl.getAttribLocation(program, "a_position");
  9016. var colorLoc = gl.getUniformLocation(program, "u_color");
  9017. // provide texture coordinates for the rectangle.
  9018. var positionBuffer = gl.createBuffer();
  9019. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  9020. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  9021. -1.0, -1.0,
  9022. 1.0, -1.0,
  9023. -1.0, 1.0,
  9024. -1.0, 1.0,
  9025. 1.0, -1.0,
  9026. 1.0, 1.0]), gl.STATIC_DRAW);
  9027. gl.enableVertexAttribArray(positionLocation);
  9028. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  9029. var whiteTex = gl.createTexture();
  9030. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9031. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  9032. var tex = gl.createTexture();
  9033. gl.bindTexture(gl.TEXTURE_2D, tex);
  9034. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  9035. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9036. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9037. var fb = gl.createFramebuffer();
  9038. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9039. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  9040. var cleanup = function () {
  9041. gl.deleteProgram(program);
  9042. gl.disableVertexAttribArray(positionLocation);
  9043. gl.deleteBuffer(positionBuffer);
  9044. gl.deleteFramebuffer(fb);
  9045. gl.deleteTexture(whiteTex);
  9046. gl.deleteTexture(tex);
  9047. };
  9048. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9049. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  9050. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  9051. cleanup();
  9052. return false;
  9053. }
  9054. // Draw the rectangle.
  9055. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9056. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  9057. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9058. gl.bindTexture(gl.TEXTURE_2D, tex);
  9059. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9060. gl.clearColor(1, 0, 0, 1);
  9061. gl.clear(gl.COLOR_BUFFER_BIT);
  9062. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  9063. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9064. var pixel = new Uint8Array(4);
  9065. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  9066. if (pixel[0] !== 0 ||
  9067. pixel[1] < 248 ||
  9068. pixel[2] < 248 ||
  9069. pixel[3] < 254) {
  9070. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  9071. cleanup();
  9072. return false;
  9073. }
  9074. // Succesfully rendered to "format" texture.
  9075. cleanup();
  9076. return true;
  9077. };
  9078. // Statics
  9079. Engine.isSupported = function () {
  9080. try {
  9081. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9082. if (navigator.isCocoonJS) {
  9083. return true;
  9084. }
  9085. var tempcanvas = document.createElement("canvas");
  9086. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9087. return gl != null && !!window.WebGLRenderingContext;
  9088. }
  9089. catch (e) {
  9090. return false;
  9091. }
  9092. };
  9093. // Const statics
  9094. Engine._ALPHA_DISABLE = 0;
  9095. Engine._ALPHA_ADD = 1;
  9096. Engine._ALPHA_COMBINE = 2;
  9097. Engine._ALPHA_SUBTRACT = 3;
  9098. Engine._ALPHA_MULTIPLY = 4;
  9099. Engine._ALPHA_MAXIMIZED = 5;
  9100. Engine._ALPHA_ONEONE = 6;
  9101. Engine._DELAYLOADSTATE_NONE = 0;
  9102. Engine._DELAYLOADSTATE_LOADED = 1;
  9103. Engine._DELAYLOADSTATE_LOADING = 2;
  9104. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9105. Engine._TEXTUREFORMAT_ALPHA = 0;
  9106. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9107. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9108. Engine._TEXTUREFORMAT_RGB = 4;
  9109. Engine._TEXTUREFORMAT_RGBA = 5;
  9110. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9111. Engine._TEXTURETYPE_FLOAT = 1;
  9112. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9113. // Depht or Stencil test Constants.
  9114. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9115. 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.
  9116. 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.
  9117. 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.
  9118. 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.
  9119. 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.
  9120. 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.
  9121. 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.
  9122. // Stencil Actions Constants.
  9123. Engine._KEEP = 0x1E00;
  9124. Engine._REPLACE = 0x1E01;
  9125. Engine._INCR = 0x1E02;
  9126. Engine._DECR = 0x1E03;
  9127. Engine._INVERT = 0x150A;
  9128. Engine._INCR_WRAP = 0x8507;
  9129. Engine._DECR_WRAP = 0x8508;
  9130. // Updatable statics so stick with vars here
  9131. Engine.CollisionsEpsilon = 0.001;
  9132. Engine.CodeRepository = "src/";
  9133. Engine.ShadersRepository = "src/Shaders/";
  9134. return Engine;
  9135. }());
  9136. BABYLON.Engine = Engine;
  9137. })(BABYLON || (BABYLON = {}));
  9138. //# sourceMappingURL=babylon.engine.js.map
  9139. var BABYLON;
  9140. (function (BABYLON) {
  9141. /**
  9142. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9143. */
  9144. var Node = (function () {
  9145. /**
  9146. * @constructor
  9147. * @param {string} name - the name and id to be given to this node
  9148. * @param {BABYLON.Scene} the scene this node will be added to
  9149. */
  9150. function Node(name, scene) {
  9151. this.state = "";
  9152. this.metadata = null;
  9153. this.doNotSerialize = false;
  9154. this.animations = new Array();
  9155. this._ranges = {};
  9156. this._childrenFlag = -1;
  9157. this._isEnabled = true;
  9158. this._isReady = true;
  9159. this._currentRenderId = -1;
  9160. this._parentRenderId = -1;
  9161. /**
  9162. * An event triggered when the mesh is disposed.
  9163. * @type {BABYLON.Observable}
  9164. */
  9165. this.onDisposeObservable = new BABYLON.Observable();
  9166. this.name = name;
  9167. this.id = name;
  9168. this._scene = scene;
  9169. this._initCache();
  9170. }
  9171. Object.defineProperty(Node.prototype, "parent", {
  9172. get: function () {
  9173. return this._parentNode;
  9174. },
  9175. set: function (parent) {
  9176. if (this._parentNode === parent) {
  9177. return;
  9178. }
  9179. if (this._parentNode) {
  9180. var index = this._parentNode._children.indexOf(this);
  9181. if (index !== -1) {
  9182. this._parentNode._children.splice(index, 1);
  9183. }
  9184. }
  9185. this._parentNode = parent;
  9186. if (this._parentNode) {
  9187. if (!this._parentNode._children) {
  9188. this._parentNode._children = new Array();
  9189. }
  9190. this._parentNode._children.push(this);
  9191. }
  9192. },
  9193. enumerable: true,
  9194. configurable: true
  9195. });
  9196. Object.defineProperty(Node.prototype, "onDispose", {
  9197. set: function (callback) {
  9198. if (this._onDisposeObserver) {
  9199. this.onDisposeObservable.remove(this._onDisposeObserver);
  9200. }
  9201. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9202. },
  9203. enumerable: true,
  9204. configurable: true
  9205. });
  9206. Node.prototype.getScene = function () {
  9207. return this._scene;
  9208. };
  9209. Node.prototype.getEngine = function () {
  9210. return this._scene.getEngine();
  9211. };
  9212. // override it in derived class
  9213. Node.prototype.getWorldMatrix = function () {
  9214. return BABYLON.Matrix.Identity();
  9215. };
  9216. // override it in derived class if you add new variables to the cache
  9217. // and call the parent class method
  9218. Node.prototype._initCache = function () {
  9219. this._cache = {};
  9220. this._cache.parent = undefined;
  9221. };
  9222. Node.prototype.updateCache = function (force) {
  9223. if (!force && this.isSynchronized())
  9224. return;
  9225. this._cache.parent = this.parent;
  9226. this._updateCache();
  9227. };
  9228. // override it in derived class if you add new variables to the cache
  9229. // and call the parent class method if !ignoreParentClass
  9230. Node.prototype._updateCache = function (ignoreParentClass) {
  9231. };
  9232. // override it in derived class if you add new variables to the cache
  9233. Node.prototype._isSynchronized = function () {
  9234. return true;
  9235. };
  9236. Node.prototype._markSyncedWithParent = function () {
  9237. this._parentRenderId = this.parent._currentRenderId;
  9238. };
  9239. Node.prototype.isSynchronizedWithParent = function () {
  9240. if (!this.parent) {
  9241. return true;
  9242. }
  9243. if (this._parentRenderId !== this.parent._currentRenderId) {
  9244. return false;
  9245. }
  9246. return this.parent.isSynchronized();
  9247. };
  9248. Node.prototype.isSynchronized = function (updateCache) {
  9249. var check = this.hasNewParent();
  9250. check = check || !this.isSynchronizedWithParent();
  9251. check = check || !this._isSynchronized();
  9252. if (updateCache)
  9253. this.updateCache(true);
  9254. return !check;
  9255. };
  9256. Node.prototype.hasNewParent = function (update) {
  9257. if (this._cache.parent === this.parent)
  9258. return false;
  9259. if (update)
  9260. this._cache.parent = this.parent;
  9261. return true;
  9262. };
  9263. /**
  9264. * Is this node ready to be used/rendered
  9265. * @return {boolean} is it ready
  9266. */
  9267. Node.prototype.isReady = function () {
  9268. return this._isReady;
  9269. };
  9270. /**
  9271. * Is this node enabled.
  9272. * If the node has a parent and is enabled, the parent will be inspected as well.
  9273. * @return {boolean} whether this node (and its parent) is enabled.
  9274. * @see setEnabled
  9275. */
  9276. Node.prototype.isEnabled = function () {
  9277. if (!this._isEnabled) {
  9278. return false;
  9279. }
  9280. if (this.parent) {
  9281. return this.parent.isEnabled();
  9282. }
  9283. return true;
  9284. };
  9285. /**
  9286. * Set the enabled state of this node.
  9287. * @param {boolean} value - the new enabled state
  9288. * @see isEnabled
  9289. */
  9290. Node.prototype.setEnabled = function (value) {
  9291. this._isEnabled = value;
  9292. };
  9293. /**
  9294. * Is this node a descendant of the given node.
  9295. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9296. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9297. * @see parent
  9298. */
  9299. Node.prototype.isDescendantOf = function (ancestor) {
  9300. if (this.parent) {
  9301. if (this.parent === ancestor) {
  9302. return true;
  9303. }
  9304. return this.parent.isDescendantOf(ancestor);
  9305. }
  9306. return false;
  9307. };
  9308. /**
  9309. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9310. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9311. * @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.
  9312. * @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.
  9313. */
  9314. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9315. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9316. if (!this._children) {
  9317. return;
  9318. }
  9319. for (var index = 0; index < this._children.length; index++) {
  9320. var item = this._children[index];
  9321. if (!predicate || predicate(item)) {
  9322. results.push(item);
  9323. }
  9324. if (!directDescendantsOnly) {
  9325. item._getDescendants(results, false, predicate);
  9326. }
  9327. }
  9328. };
  9329. /**
  9330. * Will return all nodes that have this node as ascendant.
  9331. * @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.
  9332. * @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.
  9333. * @return {BABYLON.Node[]} all children nodes of all types.
  9334. */
  9335. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9336. var results = [];
  9337. this._getDescendants(results, directDescendantsOnly, predicate);
  9338. return results;
  9339. };
  9340. /**
  9341. * @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.
  9342. * @Deprecated, legacy support.
  9343. * use getDecendants instead.
  9344. */
  9345. Node.prototype.getChildren = function (predicate) {
  9346. return this.getDescendants(true, predicate);
  9347. };
  9348. /**
  9349. * Get all child-meshes of this node.
  9350. */
  9351. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9352. var results = [];
  9353. this._getDescendants(results, directDecendantsOnly, function (node) {
  9354. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9355. });
  9356. return results;
  9357. };
  9358. Node.prototype._setReady = function (state) {
  9359. if (state === this._isReady) {
  9360. return;
  9361. }
  9362. if (!state) {
  9363. this._isReady = false;
  9364. return;
  9365. }
  9366. this._isReady = true;
  9367. if (this.onReady) {
  9368. this.onReady(this);
  9369. }
  9370. };
  9371. Node.prototype.getAnimationByName = function (name) {
  9372. for (var i = 0; i < this.animations.length; i++) {
  9373. var animation = this.animations[i];
  9374. if (animation.name === name) {
  9375. return animation;
  9376. }
  9377. }
  9378. return null;
  9379. };
  9380. Node.prototype.createAnimationRange = function (name, from, to) {
  9381. // check name not already in use
  9382. if (!this._ranges[name]) {
  9383. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9384. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9385. if (this.animations[i]) {
  9386. this.animations[i].createRange(name, from, to);
  9387. }
  9388. }
  9389. }
  9390. };
  9391. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9392. if (deleteFrames === void 0) { deleteFrames = true; }
  9393. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9394. if (this.animations[i]) {
  9395. this.animations[i].deleteRange(name, deleteFrames);
  9396. }
  9397. }
  9398. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9399. };
  9400. Node.prototype.getAnimationRange = function (name) {
  9401. return this._ranges[name];
  9402. };
  9403. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9404. var range = this.getAnimationRange(name);
  9405. if (!range) {
  9406. return null;
  9407. }
  9408. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9409. };
  9410. Node.prototype.serializeAnimationRanges = function () {
  9411. var serializationRanges = [];
  9412. for (var name in this._ranges) {
  9413. var range = {};
  9414. range.name = name;
  9415. range.from = this._ranges[name].from;
  9416. range.to = this._ranges[name].to;
  9417. serializationRanges.push(range);
  9418. }
  9419. return serializationRanges;
  9420. };
  9421. Node.prototype.dispose = function () {
  9422. this.parent = null;
  9423. // Callback
  9424. this.onDisposeObservable.notifyObservers(this);
  9425. this.onDisposeObservable.clear();
  9426. };
  9427. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9428. if (parsedNode.ranges) {
  9429. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9430. var data = parsedNode.ranges[index];
  9431. node.createAnimationRange(data.name, data.from, data.to);
  9432. }
  9433. }
  9434. };
  9435. __decorate([
  9436. BABYLON.serialize()
  9437. ], Node.prototype, "name", void 0);
  9438. __decorate([
  9439. BABYLON.serialize()
  9440. ], Node.prototype, "id", void 0);
  9441. __decorate([
  9442. BABYLON.serialize()
  9443. ], Node.prototype, "uniqueId", void 0);
  9444. __decorate([
  9445. BABYLON.serialize()
  9446. ], Node.prototype, "state", void 0);
  9447. __decorate([
  9448. BABYLON.serialize()
  9449. ], Node.prototype, "metadata", void 0);
  9450. return Node;
  9451. }());
  9452. BABYLON.Node = Node;
  9453. })(BABYLON || (BABYLON = {}));
  9454. //# sourceMappingURL=babylon.node.js.map
  9455. var BABYLON;
  9456. (function (BABYLON) {
  9457. var FilesInput = (function () {
  9458. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9459. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9460. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9461. this._engine = p_engine;
  9462. this._canvas = p_canvas;
  9463. this._currentScene = p_scene;
  9464. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9465. this._progressCallback = p_progressCallback;
  9466. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9467. this._textureLoadingCallback = p_textureLoadingCallback;
  9468. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9469. }
  9470. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9471. var _this = this;
  9472. if (p_elementToMonitor) {
  9473. this._elementToMonitor = p_elementToMonitor;
  9474. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9475. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9476. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9477. }
  9478. };
  9479. FilesInput.prototype.renderFunction = function () {
  9480. if (this._additionnalRenderLoopLogicCallback) {
  9481. this._additionnalRenderLoopLogicCallback();
  9482. }
  9483. if (this._currentScene) {
  9484. if (this._textureLoadingCallback) {
  9485. var remaining = this._currentScene.getWaitingItemsCount();
  9486. if (remaining > 0) {
  9487. this._textureLoadingCallback(remaining);
  9488. }
  9489. }
  9490. this._currentScene.render();
  9491. }
  9492. };
  9493. FilesInput.prototype.drag = function (e) {
  9494. e.stopPropagation();
  9495. e.preventDefault();
  9496. };
  9497. FilesInput.prototype.drop = function (eventDrop) {
  9498. eventDrop.stopPropagation();
  9499. eventDrop.preventDefault();
  9500. this.loadFiles(eventDrop);
  9501. };
  9502. FilesInput.prototype.loadFiles = function (event) {
  9503. if (this._startingProcessingFilesCallback)
  9504. this._startingProcessingFilesCallback();
  9505. // Handling data transfer via drag'n'drop
  9506. if (event && event.dataTransfer && event.dataTransfer.files) {
  9507. this._filesToLoad = event.dataTransfer.files;
  9508. }
  9509. // Handling files from input files
  9510. if (event && event.target && event.target.files) {
  9511. this._filesToLoad = event.target.files;
  9512. }
  9513. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9514. for (var i = 0; i < this._filesToLoad.length; i++) {
  9515. switch (this._filesToLoad[i].type) {
  9516. case "image/jpeg":
  9517. case "image/png":
  9518. case "image/bmp":
  9519. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9520. break;
  9521. case "image/targa":
  9522. case "image/vnd.ms-dds":
  9523. case "audio/wav":
  9524. case "audio/x-wav":
  9525. case "audio/mp3":
  9526. case "audio/mpeg":
  9527. case "audio/mpeg3":
  9528. case "audio/x-mpeg-3":
  9529. case "audio/ogg":
  9530. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9531. break;
  9532. default:
  9533. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9534. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9535. }
  9536. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9537. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9538. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9539. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9540. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9541. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9542. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9543. this._sceneFileToLoad = this._filesToLoad[i];
  9544. }
  9545. break;
  9546. }
  9547. }
  9548. this.reload();
  9549. }
  9550. };
  9551. FilesInput.prototype.reload = function () {
  9552. var _this = this;
  9553. var that = this;
  9554. // If a ".babylon" file has been provided
  9555. if (this._sceneFileToLoad) {
  9556. if (this._currentScene) {
  9557. if (BABYLON.Tools.errorsCount > 0) {
  9558. BABYLON.Tools.ClearLogCache();
  9559. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9560. }
  9561. this._engine.stopRenderLoop();
  9562. this._currentScene.dispose();
  9563. }
  9564. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9565. that._currentScene = newScene;
  9566. // Wait for textures and shaders to be ready
  9567. that._currentScene.executeWhenReady(function () {
  9568. // Attach camera to canvas inputs
  9569. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9570. that._currentScene.createDefaultCameraOrLight();
  9571. }
  9572. that._currentScene.activeCamera.attachControl(that._canvas);
  9573. if (that._sceneLoadedCallback) {
  9574. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9575. }
  9576. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9577. });
  9578. }, function (progress) {
  9579. if (_this._progressCallback) {
  9580. _this._progressCallback(progress);
  9581. }
  9582. });
  9583. }
  9584. else {
  9585. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9586. }
  9587. };
  9588. FilesInput.FilesTextures = new Array();
  9589. FilesInput.FilesToLoad = new Array();
  9590. return FilesInput;
  9591. }());
  9592. BABYLON.FilesInput = FilesInput;
  9593. })(BABYLON || (BABYLON = {}));
  9594. //# sourceMappingURL=babylon.filesInput.js.map
  9595. var BABYLON;
  9596. (function (BABYLON) {
  9597. var IntersectionInfo = (function () {
  9598. function IntersectionInfo(bu, bv, distance) {
  9599. this.bu = bu;
  9600. this.bv = bv;
  9601. this.distance = distance;
  9602. this.faceId = 0;
  9603. this.subMeshId = 0;
  9604. }
  9605. return IntersectionInfo;
  9606. }());
  9607. BABYLON.IntersectionInfo = IntersectionInfo;
  9608. var PickingInfo = (function () {
  9609. function PickingInfo() {
  9610. this.hit = false;
  9611. this.distance = 0;
  9612. this.pickedPoint = null;
  9613. this.pickedMesh = null;
  9614. this.bu = 0;
  9615. this.bv = 0;
  9616. this.faceId = -1;
  9617. this.subMeshId = 0;
  9618. this.pickedSprite = null;
  9619. }
  9620. // Methods
  9621. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9622. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9623. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9624. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9625. return null;
  9626. }
  9627. var indices = this.pickedMesh.getIndices();
  9628. var result;
  9629. if (useVerticesNormals) {
  9630. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9631. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9632. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9633. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9634. normal0 = normal0.scale(this.bu);
  9635. normal1 = normal1.scale(this.bv);
  9636. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9637. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9638. }
  9639. else {
  9640. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9641. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9642. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9643. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9644. var p1p2 = vertex1.subtract(vertex2);
  9645. var p3p2 = vertex3.subtract(vertex2);
  9646. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9647. }
  9648. if (useWorldCoordinates) {
  9649. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9650. }
  9651. return BABYLON.Vector3.Normalize(result);
  9652. };
  9653. PickingInfo.prototype.getTextureCoordinates = function () {
  9654. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9655. return null;
  9656. }
  9657. var indices = this.pickedMesh.getIndices();
  9658. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9659. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9660. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9661. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9662. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9663. uv1 = uv1.scale(this.bu);
  9664. uv2 = uv2.scale(this.bv);
  9665. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9666. };
  9667. return PickingInfo;
  9668. }());
  9669. BABYLON.PickingInfo = PickingInfo;
  9670. })(BABYLON || (BABYLON = {}));
  9671. //# sourceMappingURL=babylon.pickingInfo.js.map
  9672. var BABYLON;
  9673. (function (BABYLON) {
  9674. var BoundingSphere = (function () {
  9675. function BoundingSphere(minimum, maximum) {
  9676. this.minimum = minimum;
  9677. this.maximum = maximum;
  9678. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9679. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9680. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9681. this.radius = distance * 0.5;
  9682. this.centerWorld = BABYLON.Vector3.Zero();
  9683. this._update(BABYLON.Matrix.Identity());
  9684. }
  9685. // Methods
  9686. BoundingSphere.prototype._update = function (world) {
  9687. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9688. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9689. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9690. };
  9691. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9692. for (var i = 0; i < 6; i++) {
  9693. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9694. return false;
  9695. }
  9696. return true;
  9697. };
  9698. BoundingSphere.prototype.intersectsPoint = function (point) {
  9699. var x = this.centerWorld.x - point.x;
  9700. var y = this.centerWorld.y - point.y;
  9701. var z = this.centerWorld.z - point.z;
  9702. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9703. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9704. return false;
  9705. return true;
  9706. };
  9707. // Statics
  9708. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9709. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9710. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9711. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9712. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9713. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9714. return false;
  9715. return true;
  9716. };
  9717. return BoundingSphere;
  9718. }());
  9719. BABYLON.BoundingSphere = BoundingSphere;
  9720. })(BABYLON || (BABYLON = {}));
  9721. //# sourceMappingURL=babylon.boundingSphere.js.map
  9722. var BABYLON;
  9723. (function (BABYLON) {
  9724. var BoundingBox = (function () {
  9725. function BoundingBox(minimum, maximum) {
  9726. this.minimum = minimum;
  9727. this.maximum = maximum;
  9728. this.vectors = new Array();
  9729. this.vectorsWorld = new Array();
  9730. // Bounding vectors
  9731. this.vectors.push(this.minimum.clone());
  9732. this.vectors.push(this.maximum.clone());
  9733. this.vectors.push(this.minimum.clone());
  9734. this.vectors[2].x = this.maximum.x;
  9735. this.vectors.push(this.minimum.clone());
  9736. this.vectors[3].y = this.maximum.y;
  9737. this.vectors.push(this.minimum.clone());
  9738. this.vectors[4].z = this.maximum.z;
  9739. this.vectors.push(this.maximum.clone());
  9740. this.vectors[5].z = this.minimum.z;
  9741. this.vectors.push(this.maximum.clone());
  9742. this.vectors[6].x = this.minimum.x;
  9743. this.vectors.push(this.maximum.clone());
  9744. this.vectors[7].y = this.minimum.y;
  9745. // OBB
  9746. this.center = this.maximum.add(this.minimum).scale(0.5);
  9747. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9748. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9749. // World
  9750. for (var index = 0; index < this.vectors.length; index++) {
  9751. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9752. }
  9753. this.minimumWorld = BABYLON.Vector3.Zero();
  9754. this.maximumWorld = BABYLON.Vector3.Zero();
  9755. this._update(BABYLON.Matrix.Identity());
  9756. }
  9757. // Methods
  9758. BoundingBox.prototype.getWorldMatrix = function () {
  9759. return this._worldMatrix;
  9760. };
  9761. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9762. this._worldMatrix.copyFrom(matrix);
  9763. return this;
  9764. };
  9765. BoundingBox.prototype._update = function (world) {
  9766. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9767. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9768. for (var index = 0; index < this.vectors.length; index++) {
  9769. var v = this.vectorsWorld[index];
  9770. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9771. if (v.x < this.minimumWorld.x)
  9772. this.minimumWorld.x = v.x;
  9773. if (v.y < this.minimumWorld.y)
  9774. this.minimumWorld.y = v.y;
  9775. if (v.z < this.minimumWorld.z)
  9776. this.minimumWorld.z = v.z;
  9777. if (v.x > this.maximumWorld.x)
  9778. this.maximumWorld.x = v.x;
  9779. if (v.y > this.maximumWorld.y)
  9780. this.maximumWorld.y = v.y;
  9781. if (v.z > this.maximumWorld.z)
  9782. this.maximumWorld.z = v.z;
  9783. }
  9784. // OBB
  9785. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9786. this.center.scaleInPlace(0.5);
  9787. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9788. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9789. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9790. this._worldMatrix = world;
  9791. };
  9792. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9793. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9794. };
  9795. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9796. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9797. };
  9798. BoundingBox.prototype.intersectsPoint = function (point) {
  9799. var delta = -BABYLON.Epsilon;
  9800. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9801. return false;
  9802. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9803. return false;
  9804. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9805. return false;
  9806. return true;
  9807. };
  9808. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9809. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9810. };
  9811. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9812. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9813. return false;
  9814. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9815. return false;
  9816. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9817. return false;
  9818. return true;
  9819. };
  9820. // Statics
  9821. BoundingBox.Intersects = function (box0, box1) {
  9822. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9823. return false;
  9824. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9825. return false;
  9826. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9827. return false;
  9828. return true;
  9829. };
  9830. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9831. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9832. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9833. return (num <= (sphereRadius * sphereRadius));
  9834. };
  9835. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9836. for (var p = 0; p < 6; p++) {
  9837. for (var i = 0; i < 8; i++) {
  9838. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9839. return false;
  9840. }
  9841. }
  9842. }
  9843. return true;
  9844. };
  9845. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9846. for (var p = 0; p < 6; p++) {
  9847. var inCount = 8;
  9848. for (var i = 0; i < 8; i++) {
  9849. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9850. --inCount;
  9851. }
  9852. else {
  9853. break;
  9854. }
  9855. }
  9856. if (inCount === 0)
  9857. return false;
  9858. }
  9859. return true;
  9860. };
  9861. return BoundingBox;
  9862. }());
  9863. BABYLON.BoundingBox = BoundingBox;
  9864. })(BABYLON || (BABYLON = {}));
  9865. //# sourceMappingURL=babylon.boundingBox.js.map
  9866. var BABYLON;
  9867. (function (BABYLON) {
  9868. var computeBoxExtents = function (axis, box) {
  9869. var p = BABYLON.Vector3.Dot(box.center, axis);
  9870. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9871. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9872. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9873. var r = r0 + r1 + r2;
  9874. return {
  9875. min: p - r,
  9876. max: p + r
  9877. };
  9878. };
  9879. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9880. var axisOverlap = function (axis, box0, box1) {
  9881. var result0 = computeBoxExtents(axis, box0);
  9882. var result1 = computeBoxExtents(axis, box1);
  9883. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9884. };
  9885. var BoundingInfo = (function () {
  9886. function BoundingInfo(minimum, maximum) {
  9887. this.minimum = minimum;
  9888. this.maximum = maximum;
  9889. this._isLocked = false;
  9890. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9891. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9892. }
  9893. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9894. get: function () {
  9895. return this._isLocked;
  9896. },
  9897. set: function (value) {
  9898. this._isLocked = value;
  9899. },
  9900. enumerable: true,
  9901. configurable: true
  9902. });
  9903. // Methods
  9904. BoundingInfo.prototype.update = function (world) {
  9905. if (this._isLocked) {
  9906. return;
  9907. }
  9908. this.boundingBox._update(world);
  9909. this.boundingSphere._update(world);
  9910. };
  9911. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9912. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9913. return false;
  9914. return this.boundingBox.isInFrustum(frustumPlanes);
  9915. };
  9916. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9917. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9918. };
  9919. BoundingInfo.prototype._checkCollision = function (collider) {
  9920. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9921. };
  9922. BoundingInfo.prototype.intersectsPoint = function (point) {
  9923. if (!this.boundingSphere.centerWorld) {
  9924. return false;
  9925. }
  9926. if (!this.boundingSphere.intersectsPoint(point)) {
  9927. return false;
  9928. }
  9929. if (!this.boundingBox.intersectsPoint(point)) {
  9930. return false;
  9931. }
  9932. return true;
  9933. };
  9934. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9935. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9936. return false;
  9937. }
  9938. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9939. return false;
  9940. }
  9941. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9942. return false;
  9943. }
  9944. if (!precise) {
  9945. return true;
  9946. }
  9947. var box0 = this.boundingBox;
  9948. var box1 = boundingInfo.boundingBox;
  9949. if (!axisOverlap(box0.directions[0], box0, box1))
  9950. return false;
  9951. if (!axisOverlap(box0.directions[1], box0, box1))
  9952. return false;
  9953. if (!axisOverlap(box0.directions[2], box0, box1))
  9954. return false;
  9955. if (!axisOverlap(box1.directions[0], box0, box1))
  9956. return false;
  9957. if (!axisOverlap(box1.directions[1], box0, box1))
  9958. return false;
  9959. if (!axisOverlap(box1.directions[2], box0, box1))
  9960. return false;
  9961. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9962. return false;
  9963. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9964. return false;
  9965. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9966. return false;
  9967. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9968. return false;
  9969. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9970. return false;
  9971. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9972. return false;
  9973. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9974. return false;
  9975. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9976. return false;
  9977. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9978. return false;
  9979. return true;
  9980. };
  9981. return BoundingInfo;
  9982. }());
  9983. BABYLON.BoundingInfo = BoundingInfo;
  9984. })(BABYLON || (BABYLON = {}));
  9985. //# sourceMappingURL=babylon.boundingInfo.js.map
  9986. var BABYLON;
  9987. (function (BABYLON) {
  9988. var Ray = (function () {
  9989. function Ray(origin, direction, length) {
  9990. if (length === void 0) { length = Number.MAX_VALUE; }
  9991. this.origin = origin;
  9992. this.direction = direction;
  9993. this.length = length;
  9994. this._show = false;
  9995. }
  9996. // Methods
  9997. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9998. var d = 0.0;
  9999. var maxValue = Number.MAX_VALUE;
  10000. var inv;
  10001. var min;
  10002. var max;
  10003. var temp;
  10004. if (Math.abs(this.direction.x) < 0.0000001) {
  10005. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10006. return false;
  10007. }
  10008. }
  10009. else {
  10010. inv = 1.0 / this.direction.x;
  10011. min = (minimum.x - this.origin.x) * inv;
  10012. max = (maximum.x - this.origin.x) * inv;
  10013. if (max === -Infinity) {
  10014. max = Infinity;
  10015. }
  10016. if (min > max) {
  10017. temp = min;
  10018. min = max;
  10019. max = temp;
  10020. }
  10021. d = Math.max(min, d);
  10022. maxValue = Math.min(max, maxValue);
  10023. if (d > maxValue) {
  10024. return false;
  10025. }
  10026. }
  10027. if (Math.abs(this.direction.y) < 0.0000001) {
  10028. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10029. return false;
  10030. }
  10031. }
  10032. else {
  10033. inv = 1.0 / this.direction.y;
  10034. min = (minimum.y - this.origin.y) * inv;
  10035. max = (maximum.y - this.origin.y) * inv;
  10036. if (max === -Infinity) {
  10037. max = Infinity;
  10038. }
  10039. if (min > max) {
  10040. temp = min;
  10041. min = max;
  10042. max = temp;
  10043. }
  10044. d = Math.max(min, d);
  10045. maxValue = Math.min(max, maxValue);
  10046. if (d > maxValue) {
  10047. return false;
  10048. }
  10049. }
  10050. if (Math.abs(this.direction.z) < 0.0000001) {
  10051. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10052. return false;
  10053. }
  10054. }
  10055. else {
  10056. inv = 1.0 / this.direction.z;
  10057. min = (minimum.z - this.origin.z) * inv;
  10058. max = (maximum.z - this.origin.z) * inv;
  10059. if (max === -Infinity) {
  10060. max = Infinity;
  10061. }
  10062. if (min > max) {
  10063. temp = min;
  10064. min = max;
  10065. max = temp;
  10066. }
  10067. d = Math.max(min, d);
  10068. maxValue = Math.min(max, maxValue);
  10069. if (d > maxValue) {
  10070. return false;
  10071. }
  10072. }
  10073. return true;
  10074. };
  10075. Ray.prototype.intersectsBox = function (box) {
  10076. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10077. };
  10078. Ray.prototype.intersectsSphere = function (sphere) {
  10079. var x = sphere.center.x - this.origin.x;
  10080. var y = sphere.center.y - this.origin.y;
  10081. var z = sphere.center.z - this.origin.z;
  10082. var pyth = (x * x) + (y * y) + (z * z);
  10083. var rr = sphere.radius * sphere.radius;
  10084. if (pyth <= rr) {
  10085. return true;
  10086. }
  10087. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10088. if (dot < 0.0) {
  10089. return false;
  10090. }
  10091. var temp = pyth - (dot * dot);
  10092. return temp <= rr;
  10093. };
  10094. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10095. if (!this._edge1) {
  10096. this._edge1 = BABYLON.Vector3.Zero();
  10097. this._edge2 = BABYLON.Vector3.Zero();
  10098. this._pvec = BABYLON.Vector3.Zero();
  10099. this._tvec = BABYLON.Vector3.Zero();
  10100. this._qvec = BABYLON.Vector3.Zero();
  10101. }
  10102. vertex1.subtractToRef(vertex0, this._edge1);
  10103. vertex2.subtractToRef(vertex0, this._edge2);
  10104. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10105. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10106. if (det === 0) {
  10107. return null;
  10108. }
  10109. var invdet = 1 / det;
  10110. this.origin.subtractToRef(vertex0, this._tvec);
  10111. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10112. if (bu < 0 || bu > 1.0) {
  10113. return null;
  10114. }
  10115. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10116. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10117. if (bv < 0 || bu + bv > 1.0) {
  10118. return null;
  10119. }
  10120. //check if the distance is longer than the predefined length.
  10121. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10122. if (distance > this.length) {
  10123. return null;
  10124. }
  10125. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10126. };
  10127. Ray.prototype.intersectsPlane = function (plane) {
  10128. var distance;
  10129. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10130. if (Math.abs(result1) < 9.99999997475243E-07) {
  10131. return null;
  10132. }
  10133. else {
  10134. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10135. distance = (-plane.d - result2) / result1;
  10136. if (distance < 0.0) {
  10137. if (distance < -9.99999997475243E-07) {
  10138. return null;
  10139. }
  10140. else {
  10141. return 0;
  10142. }
  10143. }
  10144. return distance;
  10145. }
  10146. };
  10147. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10148. var tm = BABYLON.Tmp.Matrix[0];
  10149. mesh.getWorldMatrix().invertToRef(tm);
  10150. if (this._tmpRay) {
  10151. Ray.TransformToRef(this, tm, this._tmpRay);
  10152. }
  10153. else {
  10154. this._tmpRay = Ray.Transform(this, tm);
  10155. }
  10156. return mesh.intersects(this._tmpRay, fastCheck);
  10157. };
  10158. Ray.prototype.show = function (scene, color) {
  10159. if (!this._show) {
  10160. this._renderFunction = this._render.bind(this);
  10161. this._show = true;
  10162. this._scene = scene;
  10163. this._renderPoints = [this.origin, this.origin.add(this.direction.scale(this.length))];
  10164. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10165. this._scene.registerBeforeRender(this._renderFunction);
  10166. }
  10167. if (color) {
  10168. this._renderLine.color.copyFrom(color);
  10169. }
  10170. };
  10171. Ray.prototype.hide = function () {
  10172. if (this._show) {
  10173. this._show = false;
  10174. this._scene.unregisterBeforeRender(this._renderFunction);
  10175. }
  10176. if (this._renderLine) {
  10177. this._renderLine.dispose();
  10178. this._renderLine = null;
  10179. this._renderPoints = null;
  10180. }
  10181. };
  10182. Ray.prototype._render = function () {
  10183. var point = this._renderPoints[1];
  10184. point.copyFrom(this.direction);
  10185. point.scaleInPlace(this.length);
  10186. point.addInPlace(this.origin);
  10187. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10188. };
  10189. /**
  10190. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10191. * @param sega the first point of the segment to test the intersection against
  10192. * @param segb the second point of the segment to test the intersection against
  10193. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10194. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10195. */
  10196. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10197. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10198. var u = segb.subtract(sega);
  10199. var v = rsegb.subtract(this.origin);
  10200. var w = sega.subtract(this.origin);
  10201. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10202. var b = BABYLON.Vector3.Dot(u, v);
  10203. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10204. var d = BABYLON.Vector3.Dot(u, w);
  10205. var e = BABYLON.Vector3.Dot(v, w);
  10206. var D = a * c - b * b; // always >= 0
  10207. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10208. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10209. // compute the line parameters of the two closest points
  10210. if (D < Ray.smallnum) {
  10211. sN = 0.0; // force using point P0 on segment S1
  10212. sD = 1.0; // to prevent possible division by 0.0 later
  10213. tN = e;
  10214. tD = c;
  10215. }
  10216. else {
  10217. sN = (b * e - c * d);
  10218. tN = (a * e - b * d);
  10219. if (sN < 0.0) {
  10220. sN = 0.0;
  10221. tN = e;
  10222. tD = c;
  10223. }
  10224. else if (sN > sD) {
  10225. sN = sD;
  10226. tN = e + b;
  10227. tD = c;
  10228. }
  10229. }
  10230. if (tN < 0.0) {
  10231. tN = 0.0;
  10232. // recompute sc for this edge
  10233. if (-d < 0.0) {
  10234. sN = 0.0;
  10235. }
  10236. else if (-d > a)
  10237. sN = sD;
  10238. else {
  10239. sN = -d;
  10240. sD = a;
  10241. }
  10242. }
  10243. else if (tN > tD) {
  10244. tN = tD;
  10245. // recompute sc for this edge
  10246. if ((-d + b) < 0.0) {
  10247. sN = 0;
  10248. }
  10249. else if ((-d + b) > a) {
  10250. sN = sD;
  10251. }
  10252. else {
  10253. sN = (-d + b);
  10254. sD = a;
  10255. }
  10256. }
  10257. // finally do the division to get sc and tc
  10258. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10259. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10260. // get the difference of the two closest points
  10261. var qtc = v.multiplyByFloats(tc, tc, tc);
  10262. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10263. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10264. if (isIntersected) {
  10265. return qtc.length();
  10266. }
  10267. return -1;
  10268. };
  10269. // Statics
  10270. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10271. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10272. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10273. var direction = end.subtract(start);
  10274. direction.normalize();
  10275. return new Ray(start, direction);
  10276. };
  10277. /**
  10278. * 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
  10279. * transformed to the given world matrix.
  10280. * @param origin The origin point
  10281. * @param end The end point
  10282. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10283. */
  10284. Ray.CreateNewFromTo = function (origin, end, world) {
  10285. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10286. var direction = end.subtract(origin);
  10287. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10288. direction.normalize();
  10289. return Ray.Transform(new Ray(origin, direction, length), world);
  10290. };
  10291. Ray.Transform = function (ray, matrix) {
  10292. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10293. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10294. newDirection.normalize();
  10295. return new Ray(newOrigin, newDirection, ray.length);
  10296. };
  10297. Ray.TransformToRef = function (ray, matrix, result) {
  10298. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10299. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10300. ray.direction.normalize();
  10301. };
  10302. Ray.smallnum = 0.00000001;
  10303. Ray.rayl = 10e8;
  10304. return Ray;
  10305. }());
  10306. BABYLON.Ray = Ray;
  10307. })(BABYLON || (BABYLON = {}));
  10308. //# sourceMappingURL=babylon.ray.js.map
  10309. var BABYLON;
  10310. (function (BABYLON) {
  10311. var AbstractMesh = (function (_super) {
  10312. __extends(AbstractMesh, _super);
  10313. // Constructor
  10314. function AbstractMesh(name, scene) {
  10315. var _this = this;
  10316. _super.call(this, name, scene);
  10317. // Events
  10318. /**
  10319. * An event triggered when this mesh collides with another one
  10320. * @type {BABYLON.Observable}
  10321. */
  10322. this.onCollideObservable = new BABYLON.Observable();
  10323. /**
  10324. * An event triggered when the collision's position changes
  10325. * @type {BABYLON.Observable}
  10326. */
  10327. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10328. /**
  10329. * An event triggered after the world matrix is updated
  10330. * @type {BABYLON.Observable}
  10331. */
  10332. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10333. // Properties
  10334. this.definedFacingForward = true; // orientation for POV movement & rotation
  10335. this.position = new BABYLON.Vector3(0, 0, 0);
  10336. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10337. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10338. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10339. this.visibility = 1.0;
  10340. this.alphaIndex = Number.MAX_VALUE;
  10341. this.infiniteDistance = false;
  10342. this.isVisible = true;
  10343. this.isPickable = true;
  10344. this.showBoundingBox = false;
  10345. this.showSubMeshesBoundingBox = false;
  10346. this.isBlocker = false;
  10347. this.renderingGroupId = 0;
  10348. this.receiveShadows = false;
  10349. this.renderOutline = false;
  10350. this.outlineColor = BABYLON.Color3.Red();
  10351. this.outlineWidth = 0.02;
  10352. this.renderOverlay = false;
  10353. this.overlayColor = BABYLON.Color3.Red();
  10354. this.overlayAlpha = 0.5;
  10355. this.hasVertexAlpha = false;
  10356. this.useVertexColors = true;
  10357. this.applyFog = true;
  10358. this.computeBonesUsingShaders = true;
  10359. this.scalingDeterminant = 1;
  10360. this.numBoneInfluencers = 4;
  10361. this.useOctreeForRenderingSelection = true;
  10362. this.useOctreeForPicking = true;
  10363. this.useOctreeForCollisions = true;
  10364. this.layerMask = 0x0FFFFFFF;
  10365. this.alwaysSelectAsActiveMesh = false;
  10366. // Collisions
  10367. this._checkCollisions = false;
  10368. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10369. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10370. this._collider = new BABYLON.Collider();
  10371. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10372. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10373. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10374. // Edges
  10375. this.edgesWidth = 1;
  10376. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10377. // Cache
  10378. this._localWorld = BABYLON.Matrix.Zero();
  10379. this._worldMatrix = BABYLON.Matrix.Zero();
  10380. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10381. this._absolutePosition = BABYLON.Vector3.Zero();
  10382. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10383. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10384. this._isDirty = false;
  10385. this._pivotMatrix = BABYLON.Matrix.Identity();
  10386. this._isDisposed = false;
  10387. this._renderId = 0;
  10388. this._intersectionsInProgress = new Array();
  10389. this._isWorldMatrixFrozen = false;
  10390. this._unIndexed = false;
  10391. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10392. if (collidedMesh === void 0) { collidedMesh = null; }
  10393. //TODO move this to the collision coordinator!
  10394. if (_this.getScene().workerCollisions)
  10395. newPosition.multiplyInPlace(_this._collider.radius);
  10396. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10397. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10398. _this.position.addInPlace(_this._diffPositionForCollisions);
  10399. }
  10400. if (collidedMesh) {
  10401. _this.onCollideObservable.notifyObservers(collidedMesh);
  10402. }
  10403. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10404. };
  10405. scene.addMesh(this);
  10406. }
  10407. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10408. get: function () {
  10409. return AbstractMesh._BILLBOARDMODE_NONE;
  10410. },
  10411. enumerable: true,
  10412. configurable: true
  10413. });
  10414. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10415. get: function () {
  10416. return AbstractMesh._BILLBOARDMODE_X;
  10417. },
  10418. enumerable: true,
  10419. configurable: true
  10420. });
  10421. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10422. get: function () {
  10423. return AbstractMesh._BILLBOARDMODE_Y;
  10424. },
  10425. enumerable: true,
  10426. configurable: true
  10427. });
  10428. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10429. get: function () {
  10430. return AbstractMesh._BILLBOARDMODE_Z;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10436. get: function () {
  10437. return AbstractMesh._BILLBOARDMODE_ALL;
  10438. },
  10439. enumerable: true,
  10440. configurable: true
  10441. });
  10442. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10443. set: function (callback) {
  10444. if (this._onCollideObserver) {
  10445. this.onCollideObservable.remove(this._onCollideObserver);
  10446. }
  10447. this._onCollideObserver = this.onCollideObservable.add(callback);
  10448. },
  10449. enumerable: true,
  10450. configurable: true
  10451. });
  10452. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10453. set: function (callback) {
  10454. if (this._onCollisionPositionChangeObserver) {
  10455. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10456. }
  10457. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10458. },
  10459. enumerable: true,
  10460. configurable: true
  10461. });
  10462. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10463. get: function () {
  10464. return this._skeleton;
  10465. },
  10466. set: function (value) {
  10467. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10468. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10469. }
  10470. if (value && value.needInitialSkinMatrix) {
  10471. value._registerMeshWithPoseMatrix(this);
  10472. }
  10473. this._skeleton = value;
  10474. if (!this._skeleton) {
  10475. this._bonesTransformMatrices = null;
  10476. }
  10477. },
  10478. enumerable: true,
  10479. configurable: true
  10480. });
  10481. /**
  10482. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10483. */
  10484. AbstractMesh.prototype.toString = function (fullDetails) {
  10485. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10486. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10487. if (this._skeleton) {
  10488. ret += ", skeleton: " + this._skeleton.name;
  10489. }
  10490. if (fullDetails) {
  10491. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10492. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10493. }
  10494. return ret;
  10495. };
  10496. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10497. /**
  10498. * Getting the rotation object.
  10499. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10500. */
  10501. get: function () {
  10502. return this._rotation;
  10503. },
  10504. set: function (newRotation) {
  10505. this._rotation = newRotation;
  10506. },
  10507. enumerable: true,
  10508. configurable: true
  10509. });
  10510. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10511. get: function () {
  10512. return this._scaling;
  10513. },
  10514. set: function (newScaling) {
  10515. this._scaling = newScaling;
  10516. if (this.physicsImpostor) {
  10517. this.physicsImpostor.forceUpdate();
  10518. }
  10519. },
  10520. enumerable: true,
  10521. configurable: true
  10522. });
  10523. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10524. get: function () {
  10525. return this._rotationQuaternion;
  10526. },
  10527. set: function (quaternion) {
  10528. this._rotationQuaternion = quaternion;
  10529. //reset the rotation vector.
  10530. if (quaternion && this.rotation.length()) {
  10531. this.rotation.copyFromFloats(0, 0, 0);
  10532. }
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. // Methods
  10538. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10539. this._poseMatrix.copyFrom(matrix);
  10540. };
  10541. AbstractMesh.prototype.getPoseMatrix = function () {
  10542. return this._poseMatrix;
  10543. };
  10544. AbstractMesh.prototype.disableEdgesRendering = function () {
  10545. if (this._edgesRenderer !== undefined) {
  10546. this._edgesRenderer.dispose();
  10547. this._edgesRenderer = undefined;
  10548. }
  10549. };
  10550. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10551. if (epsilon === void 0) { epsilon = 0.95; }
  10552. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10553. this.disableEdgesRendering();
  10554. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10555. };
  10556. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10557. get: function () {
  10558. return false;
  10559. },
  10560. enumerable: true,
  10561. configurable: true
  10562. });
  10563. AbstractMesh.prototype.getLOD = function (camera) {
  10564. return this;
  10565. };
  10566. AbstractMesh.prototype.getTotalVertices = function () {
  10567. return 0;
  10568. };
  10569. AbstractMesh.prototype.getIndices = function () {
  10570. return null;
  10571. };
  10572. AbstractMesh.prototype.getVerticesData = function (kind) {
  10573. return null;
  10574. };
  10575. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10576. return false;
  10577. };
  10578. AbstractMesh.prototype.getBoundingInfo = function () {
  10579. if (this._masterMesh) {
  10580. return this._masterMesh.getBoundingInfo();
  10581. }
  10582. if (!this._boundingInfo) {
  10583. this._updateBoundingInfo();
  10584. }
  10585. return this._boundingInfo;
  10586. };
  10587. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10588. this._boundingInfo = boundingInfo;
  10589. };
  10590. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10591. get: function () {
  10592. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10593. },
  10594. enumerable: true,
  10595. configurable: true
  10596. });
  10597. AbstractMesh.prototype._preActivate = function () {
  10598. };
  10599. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10600. };
  10601. AbstractMesh.prototype._activate = function (renderId) {
  10602. this._renderId = renderId;
  10603. };
  10604. AbstractMesh.prototype.getWorldMatrix = function () {
  10605. if (this._masterMesh) {
  10606. return this._masterMesh.getWorldMatrix();
  10607. }
  10608. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10609. this.computeWorldMatrix();
  10610. }
  10611. return this._worldMatrix;
  10612. };
  10613. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10614. get: function () {
  10615. return this._worldMatrix;
  10616. },
  10617. enumerable: true,
  10618. configurable: true
  10619. });
  10620. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10621. get: function () {
  10622. return this._absolutePosition;
  10623. },
  10624. enumerable: true,
  10625. configurable: true
  10626. });
  10627. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10628. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10629. this.computeWorldMatrix(true);
  10630. this._isWorldMatrixFrozen = true;
  10631. };
  10632. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10633. this._isWorldMatrixFrozen = false;
  10634. this.computeWorldMatrix(true);
  10635. };
  10636. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10637. get: function () {
  10638. return this._isWorldMatrixFrozen;
  10639. },
  10640. enumerable: true,
  10641. configurable: true
  10642. });
  10643. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10644. axis.normalize();
  10645. if (!this.rotationQuaternion) {
  10646. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10647. this.rotation = BABYLON.Vector3.Zero();
  10648. }
  10649. var rotationQuaternion;
  10650. if (!space || space === BABYLON.Space.LOCAL) {
  10651. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10652. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10653. }
  10654. else {
  10655. if (this.parent) {
  10656. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10657. invertParentWorldMatrix.invert();
  10658. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10659. }
  10660. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10661. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10662. }
  10663. };
  10664. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10665. var displacementVector = axis.scale(distance);
  10666. if (!space || space === BABYLON.Space.LOCAL) {
  10667. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10668. this.setPositionWithLocalVector(tempV3);
  10669. }
  10670. else {
  10671. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10672. }
  10673. };
  10674. AbstractMesh.prototype.getAbsolutePosition = function () {
  10675. this.computeWorldMatrix();
  10676. return this._absolutePosition;
  10677. };
  10678. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10679. if (!absolutePosition) {
  10680. return;
  10681. }
  10682. var absolutePositionX;
  10683. var absolutePositionY;
  10684. var absolutePositionZ;
  10685. if (absolutePosition.x === undefined) {
  10686. if (arguments.length < 3) {
  10687. return;
  10688. }
  10689. absolutePositionX = arguments[0];
  10690. absolutePositionY = arguments[1];
  10691. absolutePositionZ = arguments[2];
  10692. }
  10693. else {
  10694. absolutePositionX = absolutePosition.x;
  10695. absolutePositionY = absolutePosition.y;
  10696. absolutePositionZ = absolutePosition.z;
  10697. }
  10698. if (this.parent) {
  10699. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10700. invertParentWorldMatrix.invert();
  10701. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10702. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10703. }
  10704. else {
  10705. this.position.x = absolutePositionX;
  10706. this.position.y = absolutePositionY;
  10707. this.position.z = absolutePositionZ;
  10708. }
  10709. };
  10710. // ================================== Point of View Movement =================================
  10711. /**
  10712. * Perform relative position change from the point of view of behind the front of the mesh.
  10713. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10714. * Supports definition of mesh facing forward or backward.
  10715. * @param {number} amountRight
  10716. * @param {number} amountUp
  10717. * @param {number} amountForward
  10718. */
  10719. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10720. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10721. };
  10722. /**
  10723. * Calculate relative position change from the point of view of behind the front of the mesh.
  10724. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10725. * Supports definition of mesh facing forward or backward.
  10726. * @param {number} amountRight
  10727. * @param {number} amountUp
  10728. * @param {number} amountForward
  10729. */
  10730. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10731. var rotMatrix = new BABYLON.Matrix();
  10732. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10733. rotQuaternion.toRotationMatrix(rotMatrix);
  10734. var translationDelta = BABYLON.Vector3.Zero();
  10735. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10736. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10737. return translationDelta;
  10738. };
  10739. // ================================== Point of View Rotation =================================
  10740. /**
  10741. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10742. * Supports definition of mesh facing forward or backward.
  10743. * @param {number} flipBack
  10744. * @param {number} twirlClockwise
  10745. * @param {number} tiltRight
  10746. */
  10747. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10748. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10749. };
  10750. /**
  10751. * Calculate 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.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10758. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10759. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10760. };
  10761. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10762. this._pivotMatrix = matrix;
  10763. this._cache.pivotMatrixUpdated = true;
  10764. };
  10765. AbstractMesh.prototype.getPivotMatrix = function () {
  10766. return this._pivotMatrix;
  10767. };
  10768. AbstractMesh.prototype._isSynchronized = function () {
  10769. if (this._isDirty) {
  10770. return false;
  10771. }
  10772. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10773. return false;
  10774. if (this._cache.pivotMatrixUpdated) {
  10775. return false;
  10776. }
  10777. if (this.infiniteDistance) {
  10778. return false;
  10779. }
  10780. if (!this._cache.position.equals(this.position))
  10781. return false;
  10782. if (this.rotationQuaternion) {
  10783. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10784. return false;
  10785. }
  10786. if (!this._cache.rotation.equals(this.rotation))
  10787. return false;
  10788. if (!this._cache.scaling.equals(this.scaling))
  10789. return false;
  10790. return true;
  10791. };
  10792. AbstractMesh.prototype._initCache = function () {
  10793. _super.prototype._initCache.call(this);
  10794. this._cache.localMatrixUpdated = false;
  10795. this._cache.position = BABYLON.Vector3.Zero();
  10796. this._cache.scaling = BABYLON.Vector3.Zero();
  10797. this._cache.rotation = BABYLON.Vector3.Zero();
  10798. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10799. this._cache.billboardMode = -1;
  10800. };
  10801. AbstractMesh.prototype.markAsDirty = function (property) {
  10802. if (property === "rotation") {
  10803. this.rotationQuaternion = null;
  10804. }
  10805. this._currentRenderId = Number.MAX_VALUE;
  10806. this._isDirty = true;
  10807. };
  10808. AbstractMesh.prototype._updateBoundingInfo = function () {
  10809. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10810. this._boundingInfo.update(this.worldMatrixFromCache);
  10811. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10812. };
  10813. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10814. if (!this.subMeshes) {
  10815. return;
  10816. }
  10817. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10818. var subMesh = this.subMeshes[subIndex];
  10819. if (!subMesh.IsGlobal) {
  10820. subMesh.updateBoundingInfo(matrix);
  10821. }
  10822. }
  10823. };
  10824. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10825. if (this._isWorldMatrixFrozen) {
  10826. return this._worldMatrix;
  10827. }
  10828. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10829. this._currentRenderId = this.getScene().getRenderId();
  10830. return this._worldMatrix;
  10831. }
  10832. this._cache.position.copyFrom(this.position);
  10833. this._cache.scaling.copyFrom(this.scaling);
  10834. this._cache.pivotMatrixUpdated = false;
  10835. this._cache.billboardMode = this.billboardMode;
  10836. this._currentRenderId = this.getScene().getRenderId();
  10837. this._isDirty = false;
  10838. // Scaling
  10839. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10840. // Rotation
  10841. //rotate, if quaternion is set and rotation was used
  10842. if (this.rotationQuaternion) {
  10843. var len = this.rotation.length();
  10844. if (len) {
  10845. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10846. this.rotation.copyFromFloats(0, 0, 0);
  10847. }
  10848. }
  10849. if (this.rotationQuaternion) {
  10850. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10851. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10852. }
  10853. else {
  10854. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10855. this._cache.rotation.copyFrom(this.rotation);
  10856. }
  10857. // Translation
  10858. if (this.infiniteDistance && !this.parent) {
  10859. var camera = this.getScene().activeCamera;
  10860. if (camera) {
  10861. var cameraWorldMatrix = camera.getWorldMatrix();
  10862. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10863. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10864. }
  10865. }
  10866. else {
  10867. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10868. }
  10869. // Composing transformations
  10870. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10871. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10872. // Billboarding
  10873. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10874. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10875. var localPosition = BABYLON.Tmp.Vector3[0];
  10876. if (this.parent && this.parent.getWorldMatrix) {
  10877. this._markSyncedWithParent();
  10878. var parentMatrix;
  10879. if (this._meshToBoneReferal) {
  10880. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10881. parentMatrix = BABYLON.Tmp.Matrix[6];
  10882. }
  10883. else {
  10884. parentMatrix = this.parent.getWorldMatrix();
  10885. }
  10886. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10887. localPosition = BABYLON.Tmp.Vector3[1];
  10888. }
  10889. var zero = this.getScene().activeCamera.globalPosition.clone();
  10890. if (this.parent && this.parent.position) {
  10891. localPosition.addInPlace(this.parent.position);
  10892. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10893. }
  10894. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10895. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10896. zero.x = localPosition.x + BABYLON.Epsilon;
  10897. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10898. zero.y = localPosition.y + BABYLON.Epsilon;
  10899. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10900. zero.z = localPosition.z + BABYLON.Epsilon;
  10901. }
  10902. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10903. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10904. BABYLON.Tmp.Matrix[3].invert();
  10905. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10906. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10907. }
  10908. // Local world
  10909. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10910. // Parent
  10911. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10912. this._markSyncedWithParent();
  10913. if (this._meshToBoneReferal) {
  10914. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10915. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10916. }
  10917. else {
  10918. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10919. }
  10920. }
  10921. else {
  10922. this._worldMatrix.copyFrom(this._localWorld);
  10923. }
  10924. // Bounding info
  10925. this._updateBoundingInfo();
  10926. // Absolute position
  10927. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10928. // Callbacks
  10929. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10930. if (!this._poseMatrix) {
  10931. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10932. }
  10933. return this._worldMatrix;
  10934. };
  10935. /**
  10936. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10937. * @param func: callback function to add
  10938. */
  10939. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10940. this.onAfterWorldMatrixUpdateObservable.add(func);
  10941. };
  10942. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10943. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10944. };
  10945. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10946. this.computeWorldMatrix();
  10947. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10948. };
  10949. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10950. this.computeWorldMatrix();
  10951. var invLocalWorldMatrix = this._localWorld.clone();
  10952. invLocalWorldMatrix.invert();
  10953. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10954. };
  10955. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10956. this.computeWorldMatrix(true);
  10957. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10958. };
  10959. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10960. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10961. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10962. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10963. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10964. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10965. /// <returns>Mesh oriented towards targetMesh</returns>
  10966. if (yawCor === void 0) { yawCor = 0; }
  10967. if (pitchCor === void 0) { pitchCor = 0; }
  10968. if (rollCor === void 0) { rollCor = 0; }
  10969. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10970. var dv = AbstractMesh._lookAtVectorCache;
  10971. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10972. targetPoint.subtractToRef(pos, dv);
  10973. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10974. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10975. var pitch = Math.atan2(dv.y, len);
  10976. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10977. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10978. };
  10979. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10980. this._meshToBoneReferal = affectedMesh;
  10981. this.parent = bone;
  10982. if (bone.getWorldMatrix().determinant() < 0) {
  10983. this.scalingDeterminant *= -1;
  10984. }
  10985. };
  10986. AbstractMesh.prototype.detachFromBone = function () {
  10987. if (this.parent.getWorldMatrix().determinant() < 0) {
  10988. this.scalingDeterminant *= -1;
  10989. }
  10990. this._meshToBoneReferal = null;
  10991. this.parent = null;
  10992. };
  10993. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10994. return this._boundingInfo.isInFrustum(frustumPlanes);
  10995. };
  10996. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10997. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10998. ;
  10999. };
  11000. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11001. if (!this._boundingInfo || !mesh._boundingInfo) {
  11002. return false;
  11003. }
  11004. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11005. };
  11006. AbstractMesh.prototype.intersectsPoint = function (point) {
  11007. if (!this._boundingInfo) {
  11008. return false;
  11009. }
  11010. return this._boundingInfo.intersectsPoint(point);
  11011. };
  11012. // Physics
  11013. /**
  11014. * @Deprecated. Use new PhysicsImpostor instead.
  11015. * */
  11016. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11017. //legacy support
  11018. if (impostor.impostor) {
  11019. options = impostor;
  11020. impostor = impostor.impostor;
  11021. }
  11022. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11023. return this.physicsImpostor.physicsBody;
  11024. };
  11025. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11026. return this.physicsImpostor;
  11027. };
  11028. /**
  11029. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11030. */
  11031. AbstractMesh.prototype.getPhysicsMass = function () {
  11032. return this.physicsImpostor.getParam("mass");
  11033. };
  11034. /**
  11035. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11036. */
  11037. AbstractMesh.prototype.getPhysicsFriction = function () {
  11038. return this.physicsImpostor.getParam("friction");
  11039. };
  11040. /**
  11041. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11042. */
  11043. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11044. return this.physicsImpostor.getParam("restitution");
  11045. };
  11046. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11047. if (!camera) {
  11048. camera = this.getScene().activeCamera;
  11049. }
  11050. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11051. };
  11052. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11053. if (!camera) {
  11054. camera = this.getScene().activeCamera;
  11055. }
  11056. return this.absolutePosition.subtract(camera.position).length();
  11057. };
  11058. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11059. if (!this.physicsImpostor) {
  11060. return;
  11061. }
  11062. this.physicsImpostor.applyImpulse(force, contactPoint);
  11063. };
  11064. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11065. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11066. return;
  11067. }
  11068. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11069. mainPivot: pivot1,
  11070. connectedPivot: pivot2,
  11071. nativeParams: options
  11072. });
  11073. };
  11074. /**
  11075. * @Deprecated
  11076. */
  11077. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11078. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11079. this.updatePhysicsBody();
  11080. };
  11081. /**
  11082. * @Deprecated
  11083. * Calling this function is not needed anymore.
  11084. * The physics engine takes care of transofmration automatically.
  11085. */
  11086. AbstractMesh.prototype.updatePhysicsBody = function () {
  11087. //Unneeded
  11088. };
  11089. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11090. // Collisions
  11091. get: function () {
  11092. return this._checkCollisions;
  11093. },
  11094. set: function (collisionEnabled) {
  11095. this._checkCollisions = collisionEnabled;
  11096. if (this.getScene().workerCollisions) {
  11097. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11098. }
  11099. },
  11100. enumerable: true,
  11101. configurable: true
  11102. });
  11103. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11104. var globalPosition = this.getAbsolutePosition();
  11105. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11106. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11107. this._collider.radius = this.ellipsoid;
  11108. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11109. };
  11110. // Submeshes octree
  11111. /**
  11112. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11113. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11114. */
  11115. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11116. if (maxCapacity === void 0) { maxCapacity = 64; }
  11117. if (maxDepth === void 0) { maxDepth = 2; }
  11118. if (!this._submeshesOctree) {
  11119. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11120. }
  11121. this.computeWorldMatrix(true);
  11122. // Update octree
  11123. var bbox = this.getBoundingInfo().boundingBox;
  11124. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11125. return this._submeshesOctree;
  11126. };
  11127. // Collisions
  11128. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11129. this._generatePointsArray();
  11130. // Transformation
  11131. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11132. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11133. subMesh._lastColliderWorldVertices = [];
  11134. subMesh._trianglePlanes = [];
  11135. var start = subMesh.verticesStart;
  11136. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11137. for (var i = start; i < end; i++) {
  11138. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11139. }
  11140. }
  11141. // Collide
  11142. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11143. if (collider.collisionFound) {
  11144. collider.collidedMesh = this;
  11145. }
  11146. };
  11147. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11148. var subMeshes;
  11149. var len;
  11150. // Octrees
  11151. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11152. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11153. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11154. len = intersections.length;
  11155. subMeshes = intersections.data;
  11156. }
  11157. else {
  11158. subMeshes = this.subMeshes;
  11159. len = subMeshes.length;
  11160. }
  11161. for (var index = 0; index < len; index++) {
  11162. var subMesh = subMeshes[index];
  11163. // Bounding test
  11164. if (len > 1 && !subMesh._checkCollision(collider))
  11165. continue;
  11166. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11167. }
  11168. };
  11169. AbstractMesh.prototype._checkCollision = function (collider) {
  11170. // Bounding box test
  11171. if (!this._boundingInfo._checkCollision(collider))
  11172. return;
  11173. // Transformation matrix
  11174. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11175. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11176. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11177. };
  11178. // Picking
  11179. AbstractMesh.prototype._generatePointsArray = function () {
  11180. return false;
  11181. };
  11182. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11183. var pickingInfo = new BABYLON.PickingInfo();
  11184. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11185. return pickingInfo;
  11186. }
  11187. if (!this._generatePointsArray()) {
  11188. return pickingInfo;
  11189. }
  11190. var intersectInfo = null;
  11191. // Octrees
  11192. var subMeshes;
  11193. var len;
  11194. if (this._submeshesOctree && this.useOctreeForPicking) {
  11195. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11196. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11197. len = intersections.length;
  11198. subMeshes = intersections.data;
  11199. }
  11200. else {
  11201. subMeshes = this.subMeshes;
  11202. len = subMeshes.length;
  11203. }
  11204. for (var index = 0; index < len; index++) {
  11205. var subMesh = subMeshes[index];
  11206. // Bounding test
  11207. if (len > 1 && !subMesh.canIntersects(ray))
  11208. continue;
  11209. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11210. if (currentIntersectInfo) {
  11211. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11212. intersectInfo = currentIntersectInfo;
  11213. intersectInfo.subMeshId = index;
  11214. if (fastCheck) {
  11215. break;
  11216. }
  11217. }
  11218. }
  11219. }
  11220. if (intersectInfo) {
  11221. // Get picked point
  11222. var world = this.getWorldMatrix();
  11223. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11224. var direction = ray.direction.clone();
  11225. direction = direction.scale(intersectInfo.distance);
  11226. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11227. var pickedPoint = worldOrigin.add(worldDirection);
  11228. // Return result
  11229. pickingInfo.hit = true;
  11230. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11231. pickingInfo.pickedPoint = pickedPoint;
  11232. pickingInfo.pickedMesh = this;
  11233. pickingInfo.bu = intersectInfo.bu;
  11234. pickingInfo.bv = intersectInfo.bv;
  11235. pickingInfo.faceId = intersectInfo.faceId;
  11236. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11237. return pickingInfo;
  11238. }
  11239. return pickingInfo;
  11240. };
  11241. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11242. return null;
  11243. };
  11244. AbstractMesh.prototype.releaseSubMeshes = function () {
  11245. if (this.subMeshes) {
  11246. while (this.subMeshes.length) {
  11247. this.subMeshes[0].dispose();
  11248. }
  11249. }
  11250. else {
  11251. this.subMeshes = new Array();
  11252. }
  11253. };
  11254. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11255. var _this = this;
  11256. var index;
  11257. // Action manager
  11258. if (this.actionManager) {
  11259. this.actionManager.dispose();
  11260. this.actionManager = null;
  11261. }
  11262. // Skeleton
  11263. this.skeleton = null;
  11264. // Animations
  11265. this.getScene().stopAnimation(this);
  11266. // Physics
  11267. if (this.physicsImpostor) {
  11268. this.physicsImpostor.dispose();
  11269. }
  11270. // Intersections in progress
  11271. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11272. var other = this._intersectionsInProgress[index];
  11273. var pos = other._intersectionsInProgress.indexOf(this);
  11274. other._intersectionsInProgress.splice(pos, 1);
  11275. }
  11276. this._intersectionsInProgress = [];
  11277. // Lights
  11278. var lights = this.getScene().lights;
  11279. lights.forEach(function (light) {
  11280. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11281. if (meshIndex !== -1) {
  11282. light.includedOnlyMeshes.splice(meshIndex, 1);
  11283. }
  11284. meshIndex = light.excludedMeshes.indexOf(_this);
  11285. if (meshIndex !== -1) {
  11286. light.excludedMeshes.splice(meshIndex, 1);
  11287. }
  11288. // Shadow generators
  11289. var generator = light.getShadowGenerator();
  11290. if (generator) {
  11291. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11292. if (meshIndex !== -1) {
  11293. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11294. }
  11295. }
  11296. });
  11297. // Edges
  11298. if (this._edgesRenderer) {
  11299. this._edgesRenderer.dispose();
  11300. this._edgesRenderer = null;
  11301. }
  11302. // SubMeshes
  11303. this.releaseSubMeshes();
  11304. // Engine
  11305. this.getScene().getEngine().unbindAllAttributes();
  11306. // Remove from scene
  11307. this.getScene().removeMesh(this);
  11308. if (!doNotRecurse) {
  11309. // Particles
  11310. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11311. if (this.getScene().particleSystems[index].emitter === this) {
  11312. this.getScene().particleSystems[index].dispose();
  11313. index--;
  11314. }
  11315. }
  11316. // Children
  11317. var objects = this.getDescendants(true);
  11318. for (index = 0; index < objects.length; index++) {
  11319. objects[index].dispose();
  11320. }
  11321. }
  11322. else {
  11323. var childMeshes = this.getChildMeshes(true);
  11324. for (index = 0; index < childMeshes.length; index++) {
  11325. var child = childMeshes[index];
  11326. child.parent = null;
  11327. child.computeWorldMatrix(true);
  11328. }
  11329. }
  11330. this.onAfterWorldMatrixUpdateObservable.clear();
  11331. this.onCollideObservable.clear();
  11332. this.onCollisionPositionChangeObservable.clear();
  11333. this._isDisposed = true;
  11334. _super.prototype.dispose.call(this);
  11335. };
  11336. AbstractMesh.prototype.getDirection = function (localAxis) {
  11337. var result = BABYLON.Vector3.Zero();
  11338. this.getDirectionToRef(localAxis, result);
  11339. return result;
  11340. };
  11341. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11342. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11343. };
  11344. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11345. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11346. if (this.getScene().getRenderId() == 0) {
  11347. this.computeWorldMatrix(true);
  11348. }
  11349. var wm = this.getWorldMatrix();
  11350. if (space == BABYLON.Space.WORLD) {
  11351. var tmat = BABYLON.Tmp.Matrix[0];
  11352. wm.invertToRef(tmat);
  11353. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11354. }
  11355. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11356. this._pivotMatrix.m[12] = -point.x;
  11357. this._pivotMatrix.m[13] = -point.y;
  11358. this._pivotMatrix.m[14] = -point.z;
  11359. this._cache.pivotMatrixUpdated = true;
  11360. };
  11361. AbstractMesh.prototype.getPivotPoint = function () {
  11362. var point = BABYLON.Vector3.Zero();
  11363. this.getPivotPointToRef(point);
  11364. return point;
  11365. };
  11366. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11367. result.x = -this._pivotMatrix.m[12];
  11368. result.y = -this._pivotMatrix.m[13];
  11369. result.z = -this._pivotMatrix.m[14];
  11370. };
  11371. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11372. var point = BABYLON.Vector3.Zero();
  11373. this.getAbsolutePivotPointToRef(point);
  11374. return point;
  11375. };
  11376. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11377. result.x = this._pivotMatrix.m[12];
  11378. result.y = this._pivotMatrix.m[13];
  11379. result.z = this._pivotMatrix.m[14];
  11380. this.getPivotPointToRef(result);
  11381. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11382. };
  11383. // Statics
  11384. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11385. AbstractMesh._BILLBOARDMODE_X = 1;
  11386. AbstractMesh._BILLBOARDMODE_Y = 2;
  11387. AbstractMesh._BILLBOARDMODE_Z = 4;
  11388. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11389. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11390. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11391. return AbstractMesh;
  11392. }(BABYLON.Node));
  11393. BABYLON.AbstractMesh = AbstractMesh;
  11394. })(BABYLON || (BABYLON = {}));
  11395. //# sourceMappingURL=babylon.abstractMesh.js.map
  11396. var BABYLON;
  11397. (function (BABYLON) {
  11398. var Light = (function (_super) {
  11399. __extends(Light, _super);
  11400. function Light(name, scene) {
  11401. _super.call(this, name, scene);
  11402. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11403. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11404. this.intensity = 1.0;
  11405. this.range = Number.MAX_VALUE;
  11406. this.includeOnlyWithLayerMask = 0;
  11407. this.includedOnlyMeshes = new Array();
  11408. this.excludedMeshes = new Array();
  11409. this.excludeWithLayerMask = 0;
  11410. this.lightmapMode = 0;
  11411. // PBR Properties.
  11412. this.radius = 0.00001;
  11413. this._excludedMeshesIds = new Array();
  11414. this._includedOnlyMeshesIds = new Array();
  11415. scene.addLight(this);
  11416. }
  11417. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11418. /**
  11419. * If every light affecting the material is in this lightmapMode,
  11420. * material.lightmapTexture adds or multiplies
  11421. * (depends on material.useLightmapAsShadowmap)
  11422. * after every other light calculations.
  11423. */
  11424. get: function () {
  11425. return Light._LIGHTMAP_DEFAULT;
  11426. },
  11427. enumerable: true,
  11428. configurable: true
  11429. });
  11430. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11431. /**
  11432. * material.lightmapTexture as only diffuse lighting from this light
  11433. * adds pnly specular lighting from this light
  11434. * adds dynamic shadows
  11435. */
  11436. get: function () {
  11437. return Light._LIGHTMAP_SPECULAR;
  11438. },
  11439. enumerable: true,
  11440. configurable: true
  11441. });
  11442. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11443. /**
  11444. * material.lightmapTexture as only lighting
  11445. * no light calculation from this light
  11446. * only adds dynamic shadows from this light
  11447. */
  11448. get: function () {
  11449. return Light._LIGHTMAP_SHADOWSONLY;
  11450. },
  11451. enumerable: true,
  11452. configurable: true
  11453. });
  11454. /**
  11455. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11456. */
  11457. Light.prototype.toString = function (fullDetails) {
  11458. var ret = "Name: " + this.name;
  11459. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11460. if (this.animations) {
  11461. for (var i = 0; i < this.animations.length; i++) {
  11462. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11463. }
  11464. }
  11465. if (fullDetails) {
  11466. }
  11467. return ret;
  11468. };
  11469. Light.prototype.getShadowGenerator = function () {
  11470. return this._shadowGenerator;
  11471. };
  11472. Light.prototype.getAbsolutePosition = function () {
  11473. return BABYLON.Vector3.Zero();
  11474. };
  11475. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11476. };
  11477. Light.prototype._getWorldMatrix = function () {
  11478. return BABYLON.Matrix.Identity();
  11479. };
  11480. Light.prototype.canAffectMesh = function (mesh) {
  11481. if (!mesh) {
  11482. return true;
  11483. }
  11484. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11485. return false;
  11486. }
  11487. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11488. return false;
  11489. }
  11490. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11491. return false;
  11492. }
  11493. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11494. return false;
  11495. }
  11496. return true;
  11497. };
  11498. Light.prototype.getWorldMatrix = function () {
  11499. this._currentRenderId = this.getScene().getRenderId();
  11500. var worldMatrix = this._getWorldMatrix();
  11501. if (this.parent && this.parent.getWorldMatrix) {
  11502. if (!this._parentedWorldMatrix) {
  11503. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11504. }
  11505. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11506. this._markSyncedWithParent();
  11507. return this._parentedWorldMatrix;
  11508. }
  11509. return worldMatrix;
  11510. };
  11511. Light.prototype.dispose = function () {
  11512. if (this._shadowGenerator) {
  11513. this._shadowGenerator.dispose();
  11514. this._shadowGenerator = null;
  11515. }
  11516. // Animations
  11517. this.getScene().stopAnimation(this);
  11518. // Remove from scene
  11519. this.getScene().removeLight(this);
  11520. _super.prototype.dispose.call(this);
  11521. };
  11522. Light.prototype.getTypeID = function () {
  11523. return 0;
  11524. };
  11525. Light.prototype.clone = function (name) {
  11526. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11527. };
  11528. Light.prototype.serialize = function () {
  11529. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11530. // Type
  11531. serializationObject.type = this.getTypeID();
  11532. // Parent
  11533. if (this.parent) {
  11534. serializationObject.parentId = this.parent.id;
  11535. }
  11536. // Inclusion / exclusions
  11537. if (this.excludedMeshes.length > 0) {
  11538. serializationObject.excludedMeshesIds = [];
  11539. this.excludedMeshes.forEach(function (mesh) {
  11540. serializationObject.excludedMeshesIds.push(mesh.id);
  11541. });
  11542. }
  11543. if (this.includedOnlyMeshes.length > 0) {
  11544. serializationObject.includedOnlyMeshesIds = [];
  11545. this.includedOnlyMeshes.forEach(function (mesh) {
  11546. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11547. });
  11548. }
  11549. // Animations
  11550. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11551. serializationObject.ranges = this.serializeAnimationRanges();
  11552. return serializationObject;
  11553. };
  11554. Light.GetConstructorFromName = function (type, name, scene) {
  11555. switch (type) {
  11556. case 0:
  11557. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11558. case 1:
  11559. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11560. case 2:
  11561. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11562. case 3:
  11563. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11564. }
  11565. };
  11566. Light.Parse = function (parsedLight, scene) {
  11567. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11568. // Inclusion / exclusions
  11569. if (parsedLight.excludedMeshesIds) {
  11570. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11571. }
  11572. if (parsedLight.includedOnlyMeshesIds) {
  11573. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11574. }
  11575. // Parent
  11576. if (parsedLight.parentId) {
  11577. light._waitingParentId = parsedLight.parentId;
  11578. }
  11579. // Animations
  11580. if (parsedLight.animations) {
  11581. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11582. var parsedAnimation = parsedLight.animations[animationIndex];
  11583. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11584. }
  11585. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11586. }
  11587. if (parsedLight.autoAnimate) {
  11588. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11589. }
  11590. return light;
  11591. };
  11592. //lightmapMode Consts
  11593. Light._LIGHTMAP_DEFAULT = 0;
  11594. Light._LIGHTMAP_SPECULAR = 1;
  11595. Light._LIGHTMAP_SHADOWSONLY = 2;
  11596. __decorate([
  11597. BABYLON.serializeAsColor3()
  11598. ], Light.prototype, "diffuse", void 0);
  11599. __decorate([
  11600. BABYLON.serializeAsColor3()
  11601. ], Light.prototype, "specular", void 0);
  11602. __decorate([
  11603. BABYLON.serialize()
  11604. ], Light.prototype, "intensity", void 0);
  11605. __decorate([
  11606. BABYLON.serialize()
  11607. ], Light.prototype, "range", void 0);
  11608. __decorate([
  11609. BABYLON.serialize()
  11610. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11611. __decorate([
  11612. BABYLON.serialize()
  11613. ], Light.prototype, "excludeWithLayerMask", void 0);
  11614. __decorate([
  11615. BABYLON.serialize()
  11616. ], Light.prototype, "lightmapMode", void 0);
  11617. __decorate([
  11618. BABYLON.serialize()
  11619. ], Light.prototype, "radius", void 0);
  11620. return Light;
  11621. }(BABYLON.Node));
  11622. BABYLON.Light = Light;
  11623. })(BABYLON || (BABYLON = {}));
  11624. //# sourceMappingURL=babylon.light.js.map
  11625. var BABYLON;
  11626. (function (BABYLON) {
  11627. var PointLight = (function (_super) {
  11628. __extends(PointLight, _super);
  11629. function PointLight(name, position, scene) {
  11630. _super.call(this, name, scene);
  11631. this.position = position;
  11632. }
  11633. PointLight.prototype.getAbsolutePosition = function () {
  11634. return this.transformedPosition ? this.transformedPosition : this.position;
  11635. };
  11636. PointLight.prototype.computeTransformedPosition = function () {
  11637. if (this.parent && this.parent.getWorldMatrix) {
  11638. if (!this.transformedPosition) {
  11639. this.transformedPosition = BABYLON.Vector3.Zero();
  11640. }
  11641. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11642. return true;
  11643. }
  11644. return false;
  11645. };
  11646. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11647. if (this.parent && this.parent.getWorldMatrix) {
  11648. this.computeTransformedPosition();
  11649. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11650. return;
  11651. }
  11652. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11653. };
  11654. PointLight.prototype.needCube = function () {
  11655. return true;
  11656. };
  11657. PointLight.prototype.supportsVSM = function () {
  11658. return false;
  11659. };
  11660. PointLight.prototype.needRefreshPerFrame = function () {
  11661. return false;
  11662. };
  11663. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11664. switch (faceIndex) {
  11665. case 0:
  11666. return new BABYLON.Vector3(1, 0, 0);
  11667. case 1:
  11668. return new BABYLON.Vector3(-1, 0, 0);
  11669. case 2:
  11670. return new BABYLON.Vector3(0, -1, 0);
  11671. case 3:
  11672. return new BABYLON.Vector3(0, 1, 0);
  11673. case 4:
  11674. return new BABYLON.Vector3(0, 0, 1);
  11675. case 5:
  11676. return new BABYLON.Vector3(0, 0, -1);
  11677. }
  11678. return BABYLON.Vector3.Zero();
  11679. };
  11680. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11681. var activeCamera = this.getScene().activeCamera;
  11682. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11683. };
  11684. PointLight.prototype._getWorldMatrix = function () {
  11685. if (!this._worldMatrix) {
  11686. this._worldMatrix = BABYLON.Matrix.Identity();
  11687. }
  11688. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11689. return this._worldMatrix;
  11690. };
  11691. PointLight.prototype.getTypeID = function () {
  11692. return 0;
  11693. };
  11694. __decorate([
  11695. BABYLON.serializeAsVector3()
  11696. ], PointLight.prototype, "position", void 0);
  11697. return PointLight;
  11698. }(BABYLON.Light));
  11699. BABYLON.PointLight = PointLight;
  11700. })(BABYLON || (BABYLON = {}));
  11701. //# sourceMappingURL=babylon.pointLight.js.map
  11702. var BABYLON;
  11703. (function (BABYLON) {
  11704. var SpotLight = (function (_super) {
  11705. __extends(SpotLight, _super);
  11706. function SpotLight(name, position, direction, angle, exponent, scene) {
  11707. _super.call(this, name, scene);
  11708. this.position = position;
  11709. this.direction = direction;
  11710. this.angle = angle;
  11711. this.exponent = exponent;
  11712. }
  11713. SpotLight.prototype.getAbsolutePosition = function () {
  11714. return this.transformedPosition ? this.transformedPosition : this.position;
  11715. };
  11716. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11717. var activeCamera = this.getScene().activeCamera;
  11718. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11719. };
  11720. SpotLight.prototype.needCube = function () {
  11721. return false;
  11722. };
  11723. SpotLight.prototype.supportsVSM = function () {
  11724. return true;
  11725. };
  11726. SpotLight.prototype.needRefreshPerFrame = function () {
  11727. return false;
  11728. };
  11729. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11730. return this.direction;
  11731. };
  11732. SpotLight.prototype.setDirectionToTarget = function (target) {
  11733. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11734. return this.direction;
  11735. };
  11736. SpotLight.prototype.computeTransformedPosition = function () {
  11737. if (this.parent && this.parent.getWorldMatrix) {
  11738. if (!this.transformedPosition) {
  11739. this.transformedPosition = BABYLON.Vector3.Zero();
  11740. }
  11741. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11742. return true;
  11743. }
  11744. return false;
  11745. };
  11746. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11747. var normalizeDirection;
  11748. if (this.parent && this.parent.getWorldMatrix) {
  11749. if (!this._transformedDirection) {
  11750. this._transformedDirection = BABYLON.Vector3.Zero();
  11751. }
  11752. this.computeTransformedPosition();
  11753. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11754. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11755. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11756. }
  11757. else {
  11758. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11759. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11760. }
  11761. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11762. };
  11763. SpotLight.prototype._getWorldMatrix = function () {
  11764. if (!this._worldMatrix) {
  11765. this._worldMatrix = BABYLON.Matrix.Identity();
  11766. }
  11767. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11768. return this._worldMatrix;
  11769. };
  11770. SpotLight.prototype.getTypeID = function () {
  11771. return 2;
  11772. };
  11773. SpotLight.prototype.getRotation = function () {
  11774. this.direction.normalize();
  11775. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  11776. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  11777. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  11778. };
  11779. __decorate([
  11780. BABYLON.serializeAsVector3()
  11781. ], SpotLight.prototype, "position", void 0);
  11782. __decorate([
  11783. BABYLON.serializeAsVector3()
  11784. ], SpotLight.prototype, "direction", void 0);
  11785. __decorate([
  11786. BABYLON.serialize()
  11787. ], SpotLight.prototype, "angle", void 0);
  11788. __decorate([
  11789. BABYLON.serialize()
  11790. ], SpotLight.prototype, "exponent", void 0);
  11791. return SpotLight;
  11792. }(BABYLON.Light));
  11793. BABYLON.SpotLight = SpotLight;
  11794. })(BABYLON || (BABYLON = {}));
  11795. //# sourceMappingURL=babylon.spotLight.js.map
  11796. var BABYLON;
  11797. (function (BABYLON) {
  11798. var HemisphericLight = (function (_super) {
  11799. __extends(HemisphericLight, _super);
  11800. function HemisphericLight(name, direction, scene) {
  11801. _super.call(this, name, scene);
  11802. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11803. this.direction = direction;
  11804. }
  11805. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11806. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11807. return this.direction;
  11808. };
  11809. HemisphericLight.prototype.getShadowGenerator = function () {
  11810. return null;
  11811. };
  11812. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11813. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11814. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11815. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11816. };
  11817. HemisphericLight.prototype._getWorldMatrix = function () {
  11818. if (!this._worldMatrix) {
  11819. this._worldMatrix = BABYLON.Matrix.Identity();
  11820. }
  11821. return this._worldMatrix;
  11822. };
  11823. HemisphericLight.prototype.getTypeID = function () {
  11824. return 3;
  11825. };
  11826. __decorate([
  11827. BABYLON.serializeAsColor3()
  11828. ], HemisphericLight.prototype, "groundColor", void 0);
  11829. __decorate([
  11830. BABYLON.serializeAsVector3()
  11831. ], HemisphericLight.prototype, "direction", void 0);
  11832. return HemisphericLight;
  11833. }(BABYLON.Light));
  11834. BABYLON.HemisphericLight = HemisphericLight;
  11835. })(BABYLON || (BABYLON = {}));
  11836. //# sourceMappingURL=babylon.hemisphericLight.js.map
  11837. var BABYLON;
  11838. (function (BABYLON) {
  11839. var DirectionalLight = (function (_super) {
  11840. __extends(DirectionalLight, _super);
  11841. function DirectionalLight(name, direction, scene) {
  11842. _super.call(this, name, scene);
  11843. this.shadowOrthoScale = 0.5;
  11844. this.autoUpdateExtends = true;
  11845. // Cache
  11846. this._orthoLeft = Number.MAX_VALUE;
  11847. this._orthoRight = Number.MIN_VALUE;
  11848. this._orthoTop = Number.MIN_VALUE;
  11849. this._orthoBottom = Number.MAX_VALUE;
  11850. this.position = direction.scale(-1);
  11851. this.direction = direction;
  11852. }
  11853. DirectionalLight.prototype.getAbsolutePosition = function () {
  11854. return this.transformedPosition ? this.transformedPosition : this.position;
  11855. };
  11856. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11857. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11858. return this.direction;
  11859. };
  11860. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11861. var activeCamera = this.getScene().activeCamera;
  11862. // Check extends
  11863. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11864. var tempVector3 = BABYLON.Vector3.Zero();
  11865. this._orthoLeft = Number.MAX_VALUE;
  11866. this._orthoRight = Number.MIN_VALUE;
  11867. this._orthoTop = Number.MIN_VALUE;
  11868. this._orthoBottom = Number.MAX_VALUE;
  11869. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11870. var mesh = renderList[meshIndex];
  11871. if (!mesh) {
  11872. continue;
  11873. }
  11874. var boundingInfo = mesh.getBoundingInfo();
  11875. if (!boundingInfo) {
  11876. continue;
  11877. }
  11878. var boundingBox = boundingInfo.boundingBox;
  11879. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11880. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11881. if (tempVector3.x < this._orthoLeft)
  11882. this._orthoLeft = tempVector3.x;
  11883. if (tempVector3.y < this._orthoBottom)
  11884. this._orthoBottom = tempVector3.y;
  11885. if (tempVector3.x > this._orthoRight)
  11886. this._orthoRight = tempVector3.x;
  11887. if (tempVector3.y > this._orthoTop)
  11888. this._orthoTop = tempVector3.y;
  11889. }
  11890. }
  11891. }
  11892. var xOffset = this._orthoRight - this._orthoLeft;
  11893. var yOffset = this._orthoTop - this._orthoBottom;
  11894. 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);
  11895. };
  11896. DirectionalLight.prototype.supportsVSM = function () {
  11897. return true;
  11898. };
  11899. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11900. return true;
  11901. };
  11902. DirectionalLight.prototype.needCube = function () {
  11903. return false;
  11904. };
  11905. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11906. return this.direction;
  11907. };
  11908. DirectionalLight.prototype.computeTransformedPosition = function () {
  11909. if (this.parent && this.parent.getWorldMatrix) {
  11910. if (!this.transformedPosition) {
  11911. this.transformedPosition = BABYLON.Vector3.Zero();
  11912. }
  11913. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11914. return true;
  11915. }
  11916. return false;
  11917. };
  11918. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11919. if (this.parent && this.parent.getWorldMatrix) {
  11920. if (!this._transformedDirection) {
  11921. this._transformedDirection = BABYLON.Vector3.Zero();
  11922. }
  11923. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11924. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11925. return;
  11926. }
  11927. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11928. };
  11929. DirectionalLight.prototype._getWorldMatrix = function () {
  11930. if (!this._worldMatrix) {
  11931. this._worldMatrix = BABYLON.Matrix.Identity();
  11932. }
  11933. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11934. return this._worldMatrix;
  11935. };
  11936. DirectionalLight.prototype.getTypeID = function () {
  11937. return 1;
  11938. };
  11939. __decorate([
  11940. BABYLON.serializeAsVector3()
  11941. ], DirectionalLight.prototype, "position", void 0);
  11942. __decorate([
  11943. BABYLON.serializeAsVector3()
  11944. ], DirectionalLight.prototype, "direction", void 0);
  11945. __decorate([
  11946. BABYLON.serialize()
  11947. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11948. __decorate([
  11949. BABYLON.serialize()
  11950. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11951. return DirectionalLight;
  11952. }(BABYLON.Light));
  11953. BABYLON.DirectionalLight = DirectionalLight;
  11954. })(BABYLON || (BABYLON = {}));
  11955. //# sourceMappingURL=babylon.directionalLight.js.map
  11956. var BABYLON;
  11957. (function (BABYLON) {
  11958. var ShadowGenerator = (function () {
  11959. function ShadowGenerator(mapSize, light) {
  11960. var _this = this;
  11961. // Members
  11962. this._filter = ShadowGenerator.FILTER_NONE;
  11963. this.blurScale = 2;
  11964. this._blurBoxOffset = 0;
  11965. this._bias = 0.00005;
  11966. this._lightDirection = BABYLON.Vector3.Zero();
  11967. this.forceBackFacesOnly = false;
  11968. this._darkness = 0;
  11969. this._transparencyShadow = false;
  11970. this._viewMatrix = BABYLON.Matrix.Zero();
  11971. this._projectionMatrix = BABYLON.Matrix.Zero();
  11972. this._transformMatrix = BABYLON.Matrix.Zero();
  11973. this._worldViewProjection = BABYLON.Matrix.Zero();
  11974. this._currentFaceIndex = 0;
  11975. this._currentFaceIndexCache = 0;
  11976. this._useFullFloat = true;
  11977. this._light = light;
  11978. this._scene = light.getScene();
  11979. this._mapSize = mapSize;
  11980. light._shadowGenerator = this;
  11981. // Texture type fallback from float to int if not supported.
  11982. var textureType;
  11983. var caps = this._scene.getEngine().getCaps();
  11984. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11985. this._useFullFloat = true;
  11986. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11987. }
  11988. else {
  11989. this._useFullFloat = false;
  11990. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11991. }
  11992. // Render target
  11993. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11994. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11995. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11996. this._shadowMap.anisotropicFilteringLevel = 1;
  11997. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11998. this._shadowMap.renderParticles = false;
  11999. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12000. _this._currentFaceIndex = faceIndex;
  12001. });
  12002. this._shadowMap.onAfterUnbindObservable.add(function () {
  12003. if (!_this.useBlurVarianceShadowMap) {
  12004. return;
  12005. }
  12006. if (!_this._shadowMap2) {
  12007. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12008. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12009. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12010. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12011. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12012. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12013. effect.setTexture("textureSampler", _this._shadowMap);
  12014. });
  12015. _this.blurBoxOffset = 1;
  12016. }
  12017. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12018. });
  12019. // Custom render function
  12020. var renderSubMesh = function (subMesh) {
  12021. var mesh = subMesh.getRenderingMesh();
  12022. var scene = _this._scene;
  12023. var engine = scene.getEngine();
  12024. // Culling
  12025. engine.setState(subMesh.getMaterial().backFaceCulling);
  12026. // Managing instances
  12027. var batch = mesh._getInstancesRenderList(subMesh._id);
  12028. if (batch.mustReturn) {
  12029. return;
  12030. }
  12031. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12032. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12033. engine.enableEffect(_this._effect);
  12034. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12035. var material = subMesh.getMaterial();
  12036. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12037. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12038. if (_this.getLight().needCube()) {
  12039. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12040. }
  12041. // Alpha test
  12042. if (material && material.needAlphaTesting()) {
  12043. var alphaTexture = material.getAlphaTestTexture();
  12044. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12045. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12046. }
  12047. // Bones
  12048. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12049. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12050. }
  12051. if (_this.forceBackFacesOnly) {
  12052. engine.setState(true, 0, false, true);
  12053. }
  12054. // Draw
  12055. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12056. if (_this.forceBackFacesOnly) {
  12057. engine.setState(true, 0, false, false);
  12058. }
  12059. }
  12060. else {
  12061. // Need to reset refresh rate of the shadowMap
  12062. _this._shadowMap.resetRefreshCounter();
  12063. }
  12064. };
  12065. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12066. var index;
  12067. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12068. renderSubMesh(opaqueSubMeshes.data[index]);
  12069. }
  12070. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12071. renderSubMesh(alphaTestSubMeshes.data[index]);
  12072. }
  12073. if (_this._transparencyShadow) {
  12074. for (index = 0; index < transparentSubMeshes.length; index++) {
  12075. renderSubMesh(transparentSubMeshes.data[index]);
  12076. }
  12077. }
  12078. };
  12079. this._shadowMap.onClearObservable.add(function (engine) {
  12080. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12081. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12082. }
  12083. else {
  12084. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12085. }
  12086. });
  12087. }
  12088. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12089. // Static
  12090. get: function () {
  12091. return ShadowGenerator._FILTER_NONE;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12097. get: function () {
  12098. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12104. get: function () {
  12105. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12111. get: function () {
  12112. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12118. get: function () {
  12119. return this._bias;
  12120. },
  12121. set: function (bias) {
  12122. this._bias = bias;
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12128. get: function () {
  12129. return this._blurBoxOffset;
  12130. },
  12131. set: function (value) {
  12132. var _this = this;
  12133. if (this._blurBoxOffset === value) {
  12134. return;
  12135. }
  12136. this._blurBoxOffset = value;
  12137. if (this._boxBlurPostprocess) {
  12138. this._boxBlurPostprocess.dispose();
  12139. }
  12140. 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);
  12141. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12142. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12143. });
  12144. },
  12145. enumerable: true,
  12146. configurable: true
  12147. });
  12148. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12149. get: function () {
  12150. return this._filter;
  12151. },
  12152. set: function (value) {
  12153. if (this._filter === value) {
  12154. return;
  12155. }
  12156. this._filter = value;
  12157. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12158. this._shadowMap.anisotropicFilteringLevel = 16;
  12159. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12160. }
  12161. else {
  12162. this._shadowMap.anisotropicFilteringLevel = 1;
  12163. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12164. }
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12170. get: function () {
  12171. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12172. },
  12173. set: function (value) {
  12174. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12175. },
  12176. enumerable: true,
  12177. configurable: true
  12178. });
  12179. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12180. get: function () {
  12181. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12182. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12183. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12184. },
  12185. set: function (value) {
  12186. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12187. },
  12188. enumerable: true,
  12189. configurable: true
  12190. });
  12191. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12192. get: function () {
  12193. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12194. },
  12195. set: function (value) {
  12196. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12202. var defines = [];
  12203. if (this._useFullFloat) {
  12204. defines.push("#define FULLFLOAT");
  12205. }
  12206. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12207. defines.push("#define VSM");
  12208. }
  12209. if (this.getLight().needCube()) {
  12210. defines.push("#define CUBEMAP");
  12211. }
  12212. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12213. var mesh = subMesh.getMesh();
  12214. var material = subMesh.getMaterial();
  12215. // Alpha test
  12216. if (material && material.needAlphaTesting()) {
  12217. defines.push("#define ALPHATEST");
  12218. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12219. attribs.push(BABYLON.VertexBuffer.UVKind);
  12220. defines.push("#define UV1");
  12221. }
  12222. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12223. var alphaTexture = material.getAlphaTestTexture();
  12224. if (alphaTexture.coordinatesIndex === 1) {
  12225. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12226. defines.push("#define UV2");
  12227. }
  12228. }
  12229. }
  12230. // Bones
  12231. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12232. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12233. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12234. if (mesh.numBoneInfluencers > 4) {
  12235. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12236. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12237. }
  12238. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12239. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12240. }
  12241. else {
  12242. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12243. }
  12244. // Instances
  12245. if (useInstances) {
  12246. defines.push("#define INSTANCES");
  12247. attribs.push("world0");
  12248. attribs.push("world1");
  12249. attribs.push("world2");
  12250. attribs.push("world3");
  12251. }
  12252. // Get correct effect
  12253. var join = defines.join("\n");
  12254. if (this._cachedDefines !== join) {
  12255. this._cachedDefines = join;
  12256. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12257. }
  12258. return this._effect.isReady();
  12259. };
  12260. ShadowGenerator.prototype.getShadowMap = function () {
  12261. return this._shadowMap;
  12262. };
  12263. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12264. if (this._shadowMap2) {
  12265. return this._shadowMap2;
  12266. }
  12267. return this._shadowMap;
  12268. };
  12269. ShadowGenerator.prototype.getLight = function () {
  12270. return this._light;
  12271. };
  12272. // Methods
  12273. ShadowGenerator.prototype.getTransformMatrix = function () {
  12274. var scene = this._scene;
  12275. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12276. return this._transformMatrix;
  12277. }
  12278. this._currentRenderID = scene.getRenderId();
  12279. this._currentFaceIndexCache = this._currentFaceIndex;
  12280. var lightPosition = this._light.position;
  12281. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12282. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12283. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12284. }
  12285. if (this._light.computeTransformedPosition()) {
  12286. lightPosition = this._light.transformedPosition;
  12287. }
  12288. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12289. this._cachedPosition = lightPosition.clone();
  12290. this._cachedDirection = this._lightDirection.clone();
  12291. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12292. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12293. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12294. }
  12295. return this._transformMatrix;
  12296. };
  12297. ShadowGenerator.prototype.getDarkness = function () {
  12298. return this._darkness;
  12299. };
  12300. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12301. if (darkness >= 1.0)
  12302. this._darkness = 1.0;
  12303. else if (darkness <= 0.0)
  12304. this._darkness = 0.0;
  12305. else
  12306. this._darkness = darkness;
  12307. };
  12308. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12309. this._transparencyShadow = hasShadow;
  12310. };
  12311. ShadowGenerator.prototype._packHalf = function (depth) {
  12312. var scale = depth * 255.0;
  12313. var fract = scale - Math.floor(scale);
  12314. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12315. };
  12316. ShadowGenerator.prototype.dispose = function () {
  12317. this._shadowMap.dispose();
  12318. if (this._shadowMap2) {
  12319. this._shadowMap2.dispose();
  12320. }
  12321. if (this._downSamplePostprocess) {
  12322. this._downSamplePostprocess.dispose();
  12323. }
  12324. if (this._boxBlurPostprocess) {
  12325. this._boxBlurPostprocess.dispose();
  12326. }
  12327. };
  12328. ShadowGenerator.prototype.serialize = function () {
  12329. var serializationObject = {};
  12330. serializationObject.lightId = this._light.id;
  12331. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12332. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12333. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12334. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12335. serializationObject.renderList = [];
  12336. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12337. var mesh = this.getShadowMap().renderList[meshIndex];
  12338. serializationObject.renderList.push(mesh.id);
  12339. }
  12340. return serializationObject;
  12341. };
  12342. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12343. //casting to point light, as light is missing the position attr and typescript complains.
  12344. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12345. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12346. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12347. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12348. meshes.forEach(function (mesh) {
  12349. shadowGenerator.getShadowMap().renderList.push(mesh);
  12350. });
  12351. }
  12352. if (parsedShadowGenerator.usePoissonSampling) {
  12353. shadowGenerator.usePoissonSampling = true;
  12354. }
  12355. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12356. shadowGenerator.useVarianceShadowMap = true;
  12357. }
  12358. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12359. shadowGenerator.useBlurVarianceShadowMap = true;
  12360. if (parsedShadowGenerator.blurScale) {
  12361. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12362. }
  12363. if (parsedShadowGenerator.blurBoxOffset) {
  12364. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12365. }
  12366. }
  12367. if (parsedShadowGenerator.bias !== undefined) {
  12368. shadowGenerator.bias = parsedShadowGenerator.bias;
  12369. }
  12370. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12371. return shadowGenerator;
  12372. };
  12373. ShadowGenerator._FILTER_NONE = 0;
  12374. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12375. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12376. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12377. return ShadowGenerator;
  12378. }());
  12379. BABYLON.ShadowGenerator = ShadowGenerator;
  12380. })(BABYLON || (BABYLON = {}));
  12381. //# sourceMappingURL=babylon.shadowGenerator.js.map
  12382. var BABYLON;
  12383. (function (BABYLON) {
  12384. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12385. if (boxMin.x > sphereCenter.x + sphereRadius)
  12386. return false;
  12387. if (sphereCenter.x - sphereRadius > boxMax.x)
  12388. return false;
  12389. if (boxMin.y > sphereCenter.y + sphereRadius)
  12390. return false;
  12391. if (sphereCenter.y - sphereRadius > boxMax.y)
  12392. return false;
  12393. if (boxMin.z > sphereCenter.z + sphereRadius)
  12394. return false;
  12395. if (sphereCenter.z - sphereRadius > boxMax.z)
  12396. return false;
  12397. return true;
  12398. };
  12399. var getLowestRoot = (function () {
  12400. var result = { root: 0, found: false };
  12401. return function (a, b, c, maxR) {
  12402. result.root = 0;
  12403. result.found = false;
  12404. var determinant = b * b - 4.0 * a * c;
  12405. if (determinant < 0)
  12406. return result;
  12407. var sqrtD = Math.sqrt(determinant);
  12408. var r1 = (-b - sqrtD) / (2.0 * a);
  12409. var r2 = (-b + sqrtD) / (2.0 * a);
  12410. if (r1 > r2) {
  12411. var temp = r2;
  12412. r2 = r1;
  12413. r1 = temp;
  12414. }
  12415. if (r1 > 0 && r1 < maxR) {
  12416. result.root = r1;
  12417. result.found = true;
  12418. return result;
  12419. }
  12420. if (r2 > 0 && r2 < maxR) {
  12421. result.root = r2;
  12422. result.found = true;
  12423. return result;
  12424. }
  12425. return result;
  12426. };
  12427. })();
  12428. var Collider = (function () {
  12429. function Collider() {
  12430. this.radius = new BABYLON.Vector3(1, 1, 1);
  12431. this.retry = 0;
  12432. this.basePointWorld = BABYLON.Vector3.Zero();
  12433. this.velocityWorld = BABYLON.Vector3.Zero();
  12434. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12435. this._collisionPoint = BABYLON.Vector3.Zero();
  12436. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12437. this._tempVector = BABYLON.Vector3.Zero();
  12438. this._tempVector2 = BABYLON.Vector3.Zero();
  12439. this._tempVector3 = BABYLON.Vector3.Zero();
  12440. this._tempVector4 = BABYLON.Vector3.Zero();
  12441. this._edge = BABYLON.Vector3.Zero();
  12442. this._baseToVertex = BABYLON.Vector3.Zero();
  12443. this._destinationPoint = BABYLON.Vector3.Zero();
  12444. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12445. this._displacementVector = BABYLON.Vector3.Zero();
  12446. }
  12447. // Methods
  12448. Collider.prototype._initialize = function (source, dir, e) {
  12449. this.velocity = dir;
  12450. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12451. this.basePoint = source;
  12452. source.multiplyToRef(this.radius, this.basePointWorld);
  12453. dir.multiplyToRef(this.radius, this.velocityWorld);
  12454. this.velocityWorldLength = this.velocityWorld.length();
  12455. this.epsilon = e;
  12456. this.collisionFound = false;
  12457. };
  12458. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12459. pa.subtractToRef(point, this._tempVector);
  12460. pb.subtractToRef(point, this._tempVector2);
  12461. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12462. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12463. if (d < 0)
  12464. return false;
  12465. pc.subtractToRef(point, this._tempVector3);
  12466. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12467. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12468. if (d < 0)
  12469. return false;
  12470. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12471. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12472. return d >= 0;
  12473. };
  12474. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12475. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12476. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12477. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12478. return false;
  12479. }
  12480. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12481. return false;
  12482. return true;
  12483. };
  12484. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12485. var t0;
  12486. var embeddedInPlane = false;
  12487. //defensive programming, actually not needed.
  12488. if (!trianglePlaneArray) {
  12489. trianglePlaneArray = [];
  12490. }
  12491. if (!trianglePlaneArray[faceIndex]) {
  12492. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12493. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12494. }
  12495. var trianglePlane = trianglePlaneArray[faceIndex];
  12496. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12497. return;
  12498. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12499. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12500. if (normalDotVelocity == 0) {
  12501. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12502. return;
  12503. embeddedInPlane = true;
  12504. t0 = 0;
  12505. }
  12506. else {
  12507. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12508. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12509. if (t0 > t1) {
  12510. var temp = t1;
  12511. t1 = t0;
  12512. t0 = temp;
  12513. }
  12514. if (t0 > 1.0 || t1 < 0.0)
  12515. return;
  12516. if (t0 < 0)
  12517. t0 = 0;
  12518. if (t0 > 1.0)
  12519. t0 = 1.0;
  12520. }
  12521. this._collisionPoint.copyFromFloats(0, 0, 0);
  12522. var found = false;
  12523. var t = 1.0;
  12524. if (!embeddedInPlane) {
  12525. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12526. this.velocity.scaleToRef(t0, this._tempVector);
  12527. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12528. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12529. found = true;
  12530. t = t0;
  12531. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12532. }
  12533. }
  12534. if (!found) {
  12535. var velocitySquaredLength = this.velocity.lengthSquared();
  12536. var a = velocitySquaredLength;
  12537. this.basePoint.subtractToRef(p1, this._tempVector);
  12538. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12539. var c = this._tempVector.lengthSquared() - 1.0;
  12540. var lowestRoot = getLowestRoot(a, b, c, t);
  12541. if (lowestRoot.found) {
  12542. t = lowestRoot.root;
  12543. found = true;
  12544. this._collisionPoint.copyFrom(p1);
  12545. }
  12546. this.basePoint.subtractToRef(p2, this._tempVector);
  12547. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12548. c = this._tempVector.lengthSquared() - 1.0;
  12549. lowestRoot = getLowestRoot(a, b, c, t);
  12550. if (lowestRoot.found) {
  12551. t = lowestRoot.root;
  12552. found = true;
  12553. this._collisionPoint.copyFrom(p2);
  12554. }
  12555. this.basePoint.subtractToRef(p3, this._tempVector);
  12556. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12557. c = this._tempVector.lengthSquared() - 1.0;
  12558. lowestRoot = getLowestRoot(a, b, c, t);
  12559. if (lowestRoot.found) {
  12560. t = lowestRoot.root;
  12561. found = true;
  12562. this._collisionPoint.copyFrom(p3);
  12563. }
  12564. p2.subtractToRef(p1, this._edge);
  12565. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12566. var edgeSquaredLength = this._edge.lengthSquared();
  12567. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12568. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12569. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12570. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12571. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12572. lowestRoot = getLowestRoot(a, b, c, t);
  12573. if (lowestRoot.found) {
  12574. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12575. if (f >= 0.0 && f <= 1.0) {
  12576. t = lowestRoot.root;
  12577. found = true;
  12578. this._edge.scaleInPlace(f);
  12579. p1.addToRef(this._edge, this._collisionPoint);
  12580. }
  12581. }
  12582. p3.subtractToRef(p2, this._edge);
  12583. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12584. edgeSquaredLength = this._edge.lengthSquared();
  12585. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12586. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12587. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12588. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12589. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12590. lowestRoot = getLowestRoot(a, b, c, t);
  12591. if (lowestRoot.found) {
  12592. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12593. if (f >= 0.0 && f <= 1.0) {
  12594. t = lowestRoot.root;
  12595. found = true;
  12596. this._edge.scaleInPlace(f);
  12597. p2.addToRef(this._edge, this._collisionPoint);
  12598. }
  12599. }
  12600. p1.subtractToRef(p3, this._edge);
  12601. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12602. edgeSquaredLength = this._edge.lengthSquared();
  12603. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12604. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12605. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12606. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12607. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12608. lowestRoot = getLowestRoot(a, b, c, t);
  12609. if (lowestRoot.found) {
  12610. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12611. if (f >= 0.0 && f <= 1.0) {
  12612. t = lowestRoot.root;
  12613. found = true;
  12614. this._edge.scaleInPlace(f);
  12615. p3.addToRef(this._edge, this._collisionPoint);
  12616. }
  12617. }
  12618. }
  12619. if (found) {
  12620. var distToCollision = t * this.velocity.length();
  12621. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12622. if (!this.intersectionPoint) {
  12623. this.intersectionPoint = this._collisionPoint.clone();
  12624. }
  12625. else {
  12626. this.intersectionPoint.copyFrom(this._collisionPoint);
  12627. }
  12628. this.nearestDistance = distToCollision;
  12629. this.collisionFound = true;
  12630. }
  12631. }
  12632. };
  12633. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12634. for (var i = indexStart; i < indexEnd; i += 3) {
  12635. var p1 = pts[indices[i] - decal];
  12636. var p2 = pts[indices[i + 1] - decal];
  12637. var p3 = pts[indices[i + 2] - decal];
  12638. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12639. }
  12640. };
  12641. Collider.prototype._getResponse = function (pos, vel) {
  12642. pos.addToRef(vel, this._destinationPoint);
  12643. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12644. this.basePoint.addToRef(vel, pos);
  12645. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12646. this._slidePlaneNormal.normalize();
  12647. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12648. pos.addInPlace(this._displacementVector);
  12649. this.intersectionPoint.addInPlace(this._displacementVector);
  12650. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12651. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12652. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12653. };
  12654. return Collider;
  12655. }());
  12656. BABYLON.Collider = Collider;
  12657. })(BABYLON || (BABYLON = {}));
  12658. //# sourceMappingURL=babylon.collider.js.map
  12659. var BABYLON;
  12660. (function (BABYLON) {
  12661. //WebWorker code will be inserted to this variable.
  12662. BABYLON.CollisionWorker = "";
  12663. (function (WorkerTaskType) {
  12664. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12665. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12666. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12667. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12668. var WorkerTaskType = BABYLON.WorkerTaskType;
  12669. (function (WorkerReplyType) {
  12670. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12671. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12672. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12673. var WorkerReplyType = BABYLON.WorkerReplyType;
  12674. var CollisionCoordinatorWorker = (function () {
  12675. function CollisionCoordinatorWorker() {
  12676. var _this = this;
  12677. this._scaledPosition = BABYLON.Vector3.Zero();
  12678. this._scaledVelocity = BABYLON.Vector3.Zero();
  12679. this.onMeshUpdated = function (mesh) {
  12680. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12681. };
  12682. this.onGeometryUpdated = function (geometry) {
  12683. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12684. };
  12685. this._afterRender = function () {
  12686. if (!_this._init)
  12687. return;
  12688. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12689. return;
  12690. }
  12691. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12692. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12693. if (_this._runningUpdated > 4) {
  12694. return;
  12695. }
  12696. ++_this._runningUpdated;
  12697. var payload = {
  12698. updatedMeshes: _this._addUpdateMeshesList,
  12699. updatedGeometries: _this._addUpdateGeometriesList,
  12700. removedGeometries: _this._toRemoveGeometryArray,
  12701. removedMeshes: _this._toRemoveMeshesArray
  12702. };
  12703. var message = {
  12704. payload: payload,
  12705. taskType: WorkerTaskType.UPDATE
  12706. };
  12707. var serializable = [];
  12708. for (var id in payload.updatedGeometries) {
  12709. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12710. //prepare transferables
  12711. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12712. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12713. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12714. }
  12715. }
  12716. _this._worker.postMessage(message, serializable);
  12717. _this._addUpdateMeshesList = {};
  12718. _this._addUpdateGeometriesList = {};
  12719. _this._toRemoveGeometryArray = [];
  12720. _this._toRemoveMeshesArray = [];
  12721. };
  12722. this._onMessageFromWorker = function (e) {
  12723. var returnData = e.data;
  12724. if (returnData.error != WorkerReplyType.SUCCESS) {
  12725. //TODO what errors can be returned from the worker?
  12726. BABYLON.Tools.Warn("error returned from worker!");
  12727. return;
  12728. }
  12729. switch (returnData.taskType) {
  12730. case WorkerTaskType.INIT:
  12731. _this._init = true;
  12732. //Update the worked with ALL of the scene's current state
  12733. _this._scene.meshes.forEach(function (mesh) {
  12734. _this.onMeshAdded(mesh);
  12735. });
  12736. _this._scene.getGeometries().forEach(function (geometry) {
  12737. _this.onGeometryAdded(geometry);
  12738. });
  12739. break;
  12740. case WorkerTaskType.UPDATE:
  12741. _this._runningUpdated--;
  12742. break;
  12743. case WorkerTaskType.COLLIDE:
  12744. _this._runningCollisionTask = false;
  12745. var returnPayload = returnData.payload;
  12746. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12747. return;
  12748. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12749. //cleanup
  12750. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12751. break;
  12752. }
  12753. };
  12754. this._collisionsCallbackArray = [];
  12755. this._init = false;
  12756. this._runningUpdated = 0;
  12757. this._runningCollisionTask = false;
  12758. this._addUpdateMeshesList = {};
  12759. this._addUpdateGeometriesList = {};
  12760. this._toRemoveGeometryArray = [];
  12761. this._toRemoveMeshesArray = [];
  12762. }
  12763. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12764. if (!this._init)
  12765. return;
  12766. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12767. return;
  12768. position.divideToRef(collider.radius, this._scaledPosition);
  12769. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12770. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12771. var payload = {
  12772. collider: {
  12773. position: this._scaledPosition.asArray(),
  12774. velocity: this._scaledVelocity.asArray(),
  12775. radius: collider.radius.asArray()
  12776. },
  12777. collisionId: collisionIndex,
  12778. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12779. maximumRetry: maximumRetry
  12780. };
  12781. var message = {
  12782. payload: payload,
  12783. taskType: WorkerTaskType.COLLIDE
  12784. };
  12785. this._worker.postMessage(message);
  12786. };
  12787. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12788. this._scene = scene;
  12789. this._scene.registerAfterRender(this._afterRender);
  12790. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12791. this._worker = new Worker(workerUrl);
  12792. this._worker.onmessage = this._onMessageFromWorker;
  12793. var message = {
  12794. payload: {},
  12795. taskType: WorkerTaskType.INIT
  12796. };
  12797. this._worker.postMessage(message);
  12798. };
  12799. CollisionCoordinatorWorker.prototype.destroy = function () {
  12800. this._scene.unregisterAfterRender(this._afterRender);
  12801. this._worker.terminate();
  12802. };
  12803. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12804. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12805. this.onMeshUpdated(mesh);
  12806. };
  12807. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12808. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12809. };
  12810. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12811. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12812. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12813. this.onGeometryUpdated(geometry);
  12814. };
  12815. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12816. this._toRemoveGeometryArray.push(geometry.id);
  12817. };
  12818. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12819. var submeshes = [];
  12820. if (mesh.subMeshes) {
  12821. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12822. return {
  12823. position: idx,
  12824. verticesStart: sm.verticesStart,
  12825. verticesCount: sm.verticesCount,
  12826. indexStart: sm.indexStart,
  12827. indexCount: sm.indexCount,
  12828. hasMaterial: !!sm.getMaterial(),
  12829. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12830. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12831. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12832. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12833. };
  12834. });
  12835. }
  12836. var geometryId = null;
  12837. if (mesh instanceof BABYLON.Mesh) {
  12838. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12839. }
  12840. else if (mesh instanceof BABYLON.InstancedMesh) {
  12841. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12842. }
  12843. return {
  12844. uniqueId: mesh.uniqueId,
  12845. id: mesh.id,
  12846. name: mesh.name,
  12847. geometryId: geometryId,
  12848. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12849. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12850. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12851. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12852. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12853. subMeshes: submeshes,
  12854. checkCollisions: mesh.checkCollisions
  12855. };
  12856. };
  12857. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12858. return {
  12859. id: geometry.id,
  12860. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12861. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12862. indices: new Int32Array(geometry.getIndices() || []),
  12863. };
  12864. };
  12865. return CollisionCoordinatorWorker;
  12866. }());
  12867. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12868. var CollisionCoordinatorLegacy = (function () {
  12869. function CollisionCoordinatorLegacy() {
  12870. this._scaledPosition = BABYLON.Vector3.Zero();
  12871. this._scaledVelocity = BABYLON.Vector3.Zero();
  12872. this._finalPosition = BABYLON.Vector3.Zero();
  12873. }
  12874. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12875. position.divideToRef(collider.radius, this._scaledPosition);
  12876. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12877. collider.collidedMesh = null;
  12878. collider.retry = 0;
  12879. collider.initialVelocity = this._scaledVelocity;
  12880. collider.initialPosition = this._scaledPosition;
  12881. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12882. this._finalPosition.multiplyInPlace(collider.radius);
  12883. //run the callback
  12884. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12885. };
  12886. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12887. this._scene = scene;
  12888. };
  12889. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12890. //Legacy need no destruction method.
  12891. };
  12892. //No update in legacy mode
  12893. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12894. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12895. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12896. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12897. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12898. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12899. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12900. if (excludedMesh === void 0) { excludedMesh = null; }
  12901. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12902. if (collider.retry >= maximumRetry) {
  12903. finalPosition.copyFrom(position);
  12904. return;
  12905. }
  12906. collider._initialize(position, velocity, closeDistance);
  12907. // Check all meshes
  12908. for (var index = 0; index < this._scene.meshes.length; index++) {
  12909. var mesh = this._scene.meshes[index];
  12910. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12911. mesh._checkCollision(collider);
  12912. }
  12913. }
  12914. if (!collider.collisionFound) {
  12915. position.addToRef(velocity, finalPosition);
  12916. return;
  12917. }
  12918. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12919. collider._getResponse(position, velocity);
  12920. }
  12921. if (velocity.length() <= closeDistance) {
  12922. finalPosition.copyFrom(position);
  12923. return;
  12924. }
  12925. collider.retry++;
  12926. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12927. };
  12928. return CollisionCoordinatorLegacy;
  12929. }());
  12930. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12931. })(BABYLON || (BABYLON = {}));
  12932. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  12933. var BABYLON;
  12934. (function (BABYLON) {
  12935. var Camera = (function (_super) {
  12936. __extends(Camera, _super);
  12937. function Camera(name, position, scene) {
  12938. _super.call(this, name, scene);
  12939. this.upVector = BABYLON.Vector3.Up();
  12940. this.orthoLeft = null;
  12941. this.orthoRight = null;
  12942. this.orthoBottom = null;
  12943. this.orthoTop = null;
  12944. this.fov = 0.8;
  12945. this.minZ = 1.0;
  12946. this.maxZ = 10000.0;
  12947. this.inertia = 0.9;
  12948. this.mode = Camera.PERSPECTIVE_CAMERA;
  12949. this.isIntermediate = false;
  12950. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12951. this.layerMask = 0x0FFFFFFF;
  12952. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12953. // Camera rig members
  12954. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12955. this._rigCameras = new Array();
  12956. // Cache
  12957. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12958. this._projectionMatrix = new BABYLON.Matrix();
  12959. this._doNotComputeProjectionMatrix = false;
  12960. this._postProcesses = new Array();
  12961. this._transformMatrix = BABYLON.Matrix.Zero();
  12962. this._webvrViewMatrix = BABYLON.Matrix.Identity();
  12963. this._activeMeshes = new BABYLON.SmartArray(256);
  12964. this._globalPosition = BABYLON.Vector3.Zero();
  12965. this._refreshFrustumPlanes = true;
  12966. scene.addCamera(this);
  12967. if (!scene.activeCamera) {
  12968. scene.activeCamera = this;
  12969. }
  12970. this.position = position;
  12971. }
  12972. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12973. get: function () {
  12974. return Camera._PERSPECTIVE_CAMERA;
  12975. },
  12976. enumerable: true,
  12977. configurable: true
  12978. });
  12979. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12980. get: function () {
  12981. return Camera._ORTHOGRAPHIC_CAMERA;
  12982. },
  12983. enumerable: true,
  12984. configurable: true
  12985. });
  12986. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12987. get: function () {
  12988. return Camera._FOVMODE_VERTICAL_FIXED;
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12994. get: function () {
  12995. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12996. },
  12997. enumerable: true,
  12998. configurable: true
  12999. });
  13000. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13001. get: function () {
  13002. return Camera._RIG_MODE_NONE;
  13003. },
  13004. enumerable: true,
  13005. configurable: true
  13006. });
  13007. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13008. get: function () {
  13009. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13010. },
  13011. enumerable: true,
  13012. configurable: true
  13013. });
  13014. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13015. get: function () {
  13016. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13017. },
  13018. enumerable: true,
  13019. configurable: true
  13020. });
  13021. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13022. get: function () {
  13023. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13024. },
  13025. enumerable: true,
  13026. configurable: true
  13027. });
  13028. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13029. get: function () {
  13030. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13031. },
  13032. enumerable: true,
  13033. configurable: true
  13034. });
  13035. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13036. get: function () {
  13037. return Camera._RIG_MODE_VR;
  13038. },
  13039. enumerable: true,
  13040. configurable: true
  13041. });
  13042. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13043. get: function () {
  13044. return Camera._RIG_MODE_WEBVR;
  13045. },
  13046. enumerable: true,
  13047. configurable: true
  13048. });
  13049. /**
  13050. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13051. */
  13052. Camera.prototype.toString = function (fullDetails) {
  13053. var ret = "Name: " + this.name;
  13054. ret += ", type: " + this.getTypeName();
  13055. if (this.animations) {
  13056. for (var i = 0; i < this.animations.length; i++) {
  13057. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13058. }
  13059. }
  13060. if (fullDetails) {
  13061. }
  13062. return ret;
  13063. };
  13064. Object.defineProperty(Camera.prototype, "globalPosition", {
  13065. get: function () {
  13066. return this._globalPosition;
  13067. },
  13068. enumerable: true,
  13069. configurable: true
  13070. });
  13071. Camera.prototype.getActiveMeshes = function () {
  13072. return this._activeMeshes;
  13073. };
  13074. Camera.prototype.isActiveMesh = function (mesh) {
  13075. return (this._activeMeshes.indexOf(mesh) !== -1);
  13076. };
  13077. //Cache
  13078. Camera.prototype._initCache = function () {
  13079. _super.prototype._initCache.call(this);
  13080. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13081. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13082. this._cache.mode = undefined;
  13083. this._cache.minZ = undefined;
  13084. this._cache.maxZ = undefined;
  13085. this._cache.fov = undefined;
  13086. this._cache.fovMode = undefined;
  13087. this._cache.aspectRatio = undefined;
  13088. this._cache.orthoLeft = undefined;
  13089. this._cache.orthoRight = undefined;
  13090. this._cache.orthoBottom = undefined;
  13091. this._cache.orthoTop = undefined;
  13092. this._cache.renderWidth = undefined;
  13093. this._cache.renderHeight = undefined;
  13094. };
  13095. Camera.prototype._updateCache = function (ignoreParentClass) {
  13096. if (!ignoreParentClass) {
  13097. _super.prototype._updateCache.call(this);
  13098. }
  13099. var engine = this.getEngine();
  13100. this._cache.position.copyFrom(this.position);
  13101. this._cache.upVector.copyFrom(this.upVector);
  13102. this._cache.mode = this.mode;
  13103. this._cache.minZ = this.minZ;
  13104. this._cache.maxZ = this.maxZ;
  13105. this._cache.fov = this.fov;
  13106. this._cache.fovMode = this.fovMode;
  13107. this._cache.aspectRatio = engine.getAspectRatio(this);
  13108. this._cache.orthoLeft = this.orthoLeft;
  13109. this._cache.orthoRight = this.orthoRight;
  13110. this._cache.orthoBottom = this.orthoBottom;
  13111. this._cache.orthoTop = this.orthoTop;
  13112. this._cache.renderWidth = engine.getRenderWidth();
  13113. this._cache.renderHeight = engine.getRenderHeight();
  13114. };
  13115. Camera.prototype._updateFromScene = function () {
  13116. this.updateCache();
  13117. this.update();
  13118. };
  13119. // Synchronized
  13120. Camera.prototype._isSynchronized = function () {
  13121. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13122. };
  13123. Camera.prototype._isSynchronizedViewMatrix = function () {
  13124. if (!_super.prototype._isSynchronized.call(this))
  13125. return false;
  13126. return this._cache.position.equals(this.position)
  13127. && this._cache.upVector.equals(this.upVector)
  13128. && this.isSynchronizedWithParent();
  13129. };
  13130. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13131. var check = this._cache.mode === this.mode
  13132. && this._cache.minZ === this.minZ
  13133. && this._cache.maxZ === this.maxZ;
  13134. if (!check) {
  13135. return false;
  13136. }
  13137. var engine = this.getEngine();
  13138. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13139. check = this._cache.fov === this.fov
  13140. && this._cache.fovMode === this.fovMode
  13141. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13142. }
  13143. else {
  13144. check = this._cache.orthoLeft === this.orthoLeft
  13145. && this._cache.orthoRight === this.orthoRight
  13146. && this._cache.orthoBottom === this.orthoBottom
  13147. && this._cache.orthoTop === this.orthoTop
  13148. && this._cache.renderWidth === engine.getRenderWidth()
  13149. && this._cache.renderHeight === engine.getRenderHeight();
  13150. }
  13151. return check;
  13152. };
  13153. // Controls
  13154. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13155. };
  13156. Camera.prototype.detachControl = function (element) {
  13157. };
  13158. Camera.prototype.update = function () {
  13159. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13160. this._updateRigCameras();
  13161. }
  13162. this._checkInputs();
  13163. };
  13164. Camera.prototype._checkInputs = function () {
  13165. };
  13166. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13167. // invalidate framebuffer
  13168. if (this._postProcesses.length > 0) {
  13169. this._postProcesses[0].markTextureDirty();
  13170. }
  13171. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13172. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13173. var cam = this._rigCameras[i];
  13174. var rigPostProcess = cam._rigPostProcess;
  13175. // for VR rig, there does not have to be a post process
  13176. if (rigPostProcess) {
  13177. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13178. if (isPass) {
  13179. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13180. cam.isIntermediate = this._postProcesses.length === 0;
  13181. }
  13182. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13183. rigPostProcess.markTextureDirty();
  13184. }
  13185. else {
  13186. cam._postProcesses = this._postProcesses.slice(0);
  13187. }
  13188. }
  13189. };
  13190. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13191. if (insertAt === void 0) { insertAt = null; }
  13192. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13193. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13194. return 0;
  13195. }
  13196. if (insertAt == null || insertAt < 0) {
  13197. this._postProcesses.push(postProcess);
  13198. }
  13199. else {
  13200. this._postProcesses.splice(insertAt, 0, postProcess);
  13201. }
  13202. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13203. return this._postProcesses.indexOf(postProcess);
  13204. };
  13205. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13206. if (atIndices === void 0) { atIndices = null; }
  13207. var result = [];
  13208. var i;
  13209. var index;
  13210. if (!atIndices) {
  13211. var idx = this._postProcesses.indexOf(postProcess);
  13212. if (idx !== -1) {
  13213. this._postProcesses.splice(idx, 1);
  13214. }
  13215. }
  13216. else {
  13217. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13218. // iterate descending, so can just splice as we go
  13219. for (i = atIndices.length - 1; i >= 0; i--) {
  13220. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13221. result.push(i);
  13222. continue;
  13223. }
  13224. this._postProcesses.splice(index, 1);
  13225. }
  13226. }
  13227. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13228. return result;
  13229. };
  13230. Camera.prototype.getWorldMatrix = function () {
  13231. if (!this._worldMatrix) {
  13232. this._worldMatrix = BABYLON.Matrix.Identity();
  13233. }
  13234. var viewMatrix = this.getViewMatrix();
  13235. viewMatrix.invertToRef(this._worldMatrix);
  13236. return this._worldMatrix;
  13237. };
  13238. Camera.prototype._getViewMatrix = function () {
  13239. return BABYLON.Matrix.Identity();
  13240. };
  13241. Camera.prototype.getViewMatrix = function (force) {
  13242. this._computedViewMatrix = this._computeViewMatrix(force);
  13243. if (!force && this._isSynchronizedViewMatrix()) {
  13244. return this._computedViewMatrix;
  13245. }
  13246. this._refreshFrustumPlanes = true;
  13247. if (!this.parent || !this.parent.getWorldMatrix) {
  13248. this._globalPosition.copyFrom(this.position);
  13249. }
  13250. else {
  13251. if (!this._worldMatrix) {
  13252. this._worldMatrix = BABYLON.Matrix.Identity();
  13253. }
  13254. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13255. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13256. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13257. this._computedViewMatrix.invert();
  13258. this._markSyncedWithParent();
  13259. }
  13260. this._currentRenderId = this.getScene().getRenderId();
  13261. return this._computedViewMatrix;
  13262. };
  13263. Camera.prototype._computeViewMatrix = function (force) {
  13264. if (!force && this._isSynchronizedViewMatrix()) {
  13265. return this._computedViewMatrix;
  13266. }
  13267. this._computedViewMatrix = this._getViewMatrix();
  13268. this._currentRenderId = this.getScene().getRenderId();
  13269. return this._computedViewMatrix;
  13270. };
  13271. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13272. this._doNotComputeProjectionMatrix = true;
  13273. if (projection !== undefined) {
  13274. this._projectionMatrix = projection;
  13275. }
  13276. };
  13277. ;
  13278. Camera.prototype.unfreezeProjectionMatrix = function () {
  13279. this._doNotComputeProjectionMatrix = false;
  13280. };
  13281. ;
  13282. Camera.prototype.getProjectionMatrix = function (force) {
  13283. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13284. return this._projectionMatrix;
  13285. }
  13286. this._refreshFrustumPlanes = true;
  13287. var engine = this.getEngine();
  13288. var scene = this.getScene();
  13289. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13290. if (this.minZ <= 0) {
  13291. this.minZ = 0.1;
  13292. }
  13293. if (scene.useRightHandedSystem) {
  13294. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13295. }
  13296. else {
  13297. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13298. }
  13299. return this._projectionMatrix;
  13300. }
  13301. var halfWidth = engine.getRenderWidth() / 2.0;
  13302. var halfHeight = engine.getRenderHeight() / 2.0;
  13303. if (scene.useRightHandedSystem) {
  13304. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13305. }
  13306. else {
  13307. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13308. }
  13309. return this._projectionMatrix;
  13310. };
  13311. Camera.prototype.getTranformationMatrix = function () {
  13312. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13313. return this._transformMatrix;
  13314. };
  13315. Camera.prototype.updateFrustumPlanes = function () {
  13316. if (!this._refreshFrustumPlanes) {
  13317. return;
  13318. }
  13319. this.getTranformationMatrix();
  13320. if (!this._frustumPlanes) {
  13321. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13322. }
  13323. else {
  13324. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13325. }
  13326. this._refreshFrustumPlanes = false;
  13327. };
  13328. Camera.prototype.isInFrustum = function (target) {
  13329. this.updateFrustumPlanes();
  13330. return target.isInFrustum(this._frustumPlanes);
  13331. };
  13332. Camera.prototype.isCompletelyInFrustum = function (target) {
  13333. this.updateFrustumPlanes();
  13334. return target.isCompletelyInFrustum(this._frustumPlanes);
  13335. };
  13336. Camera.prototype.dispose = function () {
  13337. // Animations
  13338. this.getScene().stopAnimation(this);
  13339. // Remove from scene
  13340. this.getScene().removeCamera(this);
  13341. while (this._rigCameras.length > 0) {
  13342. this._rigCameras.pop().dispose();
  13343. }
  13344. // Postprocesses
  13345. for (var i = 0; i < this._postProcesses.length; ++i) {
  13346. this._postProcesses[i].dispose(this);
  13347. }
  13348. _super.prototype.dispose.call(this);
  13349. };
  13350. // ---- Camera rigs section ----
  13351. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13352. while (this._rigCameras.length > 0) {
  13353. this._rigCameras.pop().dispose();
  13354. }
  13355. this.cameraRigMode = mode;
  13356. this._cameraRigParams = {};
  13357. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13358. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13359. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13360. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13361. // create the rig cameras, unless none
  13362. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13363. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13364. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13365. }
  13366. switch (this.cameraRigMode) {
  13367. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13368. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13369. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13370. break;
  13371. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13372. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13373. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13374. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13375. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13376. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13377. break;
  13378. case Camera.RIG_MODE_VR:
  13379. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13380. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13381. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13382. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13383. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13384. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13385. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13386. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13387. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13388. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13389. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13390. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13391. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13392. if (metrics.compensateDistortion) {
  13393. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13394. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13395. }
  13396. break;
  13397. case Camera.RIG_MODE_WEBVR:
  13398. if (rigParams.vrDisplay) {
  13399. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13400. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13401. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13402. this._rigCameras[0].setCameraRigParameter("left", true);
  13403. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13404. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13405. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13406. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13407. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13408. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13409. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13410. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13411. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13412. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13413. }
  13414. break;
  13415. }
  13416. this._cascadePostProcessesToRigCams();
  13417. this.
  13418. update();
  13419. };
  13420. Camera.prototype._getVRProjectionMatrix = function () {
  13421. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13422. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13423. return this._projectionMatrix;
  13424. };
  13425. Camera.prototype._getWebVRProjectionMatrix = function () {
  13426. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13427. //babylon compatible matrix
  13428. [8, 9, 10, 11].forEach(function (num) {
  13429. projectionArray[num] *= -1;
  13430. });
  13431. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13432. return this._projectionMatrix;
  13433. };
  13434. //Can be used, but we'll use the free camera's view matrix calculation
  13435. Camera.prototype._getWebVRViewMatrix = function () {
  13436. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13437. //babylon compatible matrix
  13438. [8, 9, 10, 11].forEach(function (num) {
  13439. projectionArray[num] *= -1;
  13440. });
  13441. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13442. return this._webvrViewMatrix;
  13443. };
  13444. Camera.prototype.setCameraRigParameter = function (name, value) {
  13445. if (!this._cameraRigParams) {
  13446. this._cameraRigParams = {};
  13447. }
  13448. this._cameraRigParams[name] = value;
  13449. //provisionnally:
  13450. if (name === "interaxialDistance") {
  13451. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13452. }
  13453. };
  13454. /**
  13455. * needs to be overridden by children so sub has required properties to be copied
  13456. */
  13457. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13458. return null;
  13459. };
  13460. /**
  13461. * May need to be overridden by children
  13462. */
  13463. Camera.prototype._updateRigCameras = function () {
  13464. for (var i = 0; i < this._rigCameras.length; i++) {
  13465. this._rigCameras[i].minZ = this.minZ;
  13466. this._rigCameras[i].maxZ = this.maxZ;
  13467. this._rigCameras[i].fov = this.fov;
  13468. }
  13469. // only update viewport when ANAGLYPH
  13470. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13471. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13472. }
  13473. };
  13474. Camera.prototype._setupInputs = function () {
  13475. };
  13476. Camera.prototype.serialize = function () {
  13477. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13478. // Type
  13479. serializationObject.type = this.getTypeName();
  13480. // Parent
  13481. if (this.parent) {
  13482. serializationObject.parentId = this.parent.id;
  13483. }
  13484. if (this.inputs) {
  13485. this.inputs.serialize(serializationObject);
  13486. }
  13487. // Animations
  13488. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13489. serializationObject.ranges = this.serializeAnimationRanges();
  13490. return serializationObject;
  13491. };
  13492. Camera.prototype.getTypeName = function () {
  13493. return "Camera";
  13494. };
  13495. Camera.prototype.clone = function (name) {
  13496. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13497. };
  13498. Camera.prototype.getDirection = function (localAxis) {
  13499. var result = BABYLON.Vector3.Zero();
  13500. this.getDirectionToRef(localAxis, result);
  13501. return result;
  13502. };
  13503. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13504. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13505. };
  13506. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13507. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13508. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13509. switch (type) {
  13510. case "ArcRotateCamera":
  13511. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13512. case "DeviceOrientationCamera":
  13513. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13514. case "FollowCamera":
  13515. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13516. case "ArcFollowCamera":
  13517. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13518. case "GamepadCamera":
  13519. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13520. case "TouchCamera":
  13521. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13522. case "VirtualJoysticksCamera":
  13523. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13524. case "WebVRFreeCamera":
  13525. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13526. case "VRDeviceOrientationFreeCamera":
  13527. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13528. case "AnaglyphArcRotateCamera":
  13529. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13530. case "AnaglyphFreeCamera":
  13531. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13532. case "AnaglyphGamepadCamera":
  13533. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13534. case "AnaglyphUniversalCamera":
  13535. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13536. case "StereoscopicArcRotateCamera":
  13537. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13538. case "StereoscopicFreeCamera":
  13539. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13540. case "StereoscopicGamepadCamera":
  13541. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13542. case "StereoscopicUniversalCamera":
  13543. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13544. case "FreeCamera":
  13545. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13546. default:
  13547. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13548. }
  13549. };
  13550. Camera.Parse = function (parsedCamera, scene) {
  13551. var type = parsedCamera.type;
  13552. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13553. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13554. // Parent
  13555. if (parsedCamera.parentId) {
  13556. camera._waitingParentId = parsedCamera.parentId;
  13557. }
  13558. //If camera has an input manager, let it parse inputs settings
  13559. if (camera.inputs) {
  13560. camera.inputs.parse(parsedCamera);
  13561. camera._setupInputs();
  13562. }
  13563. // Target
  13564. if (parsedCamera.target) {
  13565. if (camera.setTarget) {
  13566. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13567. }
  13568. }
  13569. // Apply 3d rig, when found
  13570. if (parsedCamera.cameraRigMode) {
  13571. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13572. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13573. }
  13574. // Animations
  13575. if (parsedCamera.animations) {
  13576. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13577. var parsedAnimation = parsedCamera.animations[animationIndex];
  13578. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13579. }
  13580. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13581. }
  13582. if (parsedCamera.autoAnimate) {
  13583. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13584. }
  13585. return camera;
  13586. };
  13587. // Statics
  13588. Camera._PERSPECTIVE_CAMERA = 0;
  13589. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13590. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13591. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13592. Camera._RIG_MODE_NONE = 0;
  13593. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13594. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13595. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13596. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13597. Camera._RIG_MODE_VR = 20;
  13598. Camera._RIG_MODE_WEBVR = 21;
  13599. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13600. __decorate([
  13601. BABYLON.serializeAsVector3()
  13602. ], Camera.prototype, "position", void 0);
  13603. __decorate([
  13604. BABYLON.serializeAsVector3()
  13605. ], Camera.prototype, "upVector", void 0);
  13606. __decorate([
  13607. BABYLON.serialize()
  13608. ], Camera.prototype, "orthoLeft", void 0);
  13609. __decorate([
  13610. BABYLON.serialize()
  13611. ], Camera.prototype, "orthoRight", void 0);
  13612. __decorate([
  13613. BABYLON.serialize()
  13614. ], Camera.prototype, "orthoBottom", void 0);
  13615. __decorate([
  13616. BABYLON.serialize()
  13617. ], Camera.prototype, "orthoTop", void 0);
  13618. __decorate([
  13619. BABYLON.serialize()
  13620. ], Camera.prototype, "fov", void 0);
  13621. __decorate([
  13622. BABYLON.serialize()
  13623. ], Camera.prototype, "minZ", void 0);
  13624. __decorate([
  13625. BABYLON.serialize()
  13626. ], Camera.prototype, "maxZ", void 0);
  13627. __decorate([
  13628. BABYLON.serialize()
  13629. ], Camera.prototype, "inertia", void 0);
  13630. __decorate([
  13631. BABYLON.serialize()
  13632. ], Camera.prototype, "mode", void 0);
  13633. __decorate([
  13634. BABYLON.serialize()
  13635. ], Camera.prototype, "layerMask", void 0);
  13636. __decorate([
  13637. BABYLON.serialize()
  13638. ], Camera.prototype, "fovMode", void 0);
  13639. __decorate([
  13640. BABYLON.serialize()
  13641. ], Camera.prototype, "cameraRigMode", void 0);
  13642. __decorate([
  13643. BABYLON.serialize()
  13644. ], Camera.prototype, "interaxialDistance", void 0);
  13645. __decorate([
  13646. BABYLON.serialize()
  13647. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13648. return Camera;
  13649. }(BABYLON.Node));
  13650. BABYLON.Camera = Camera;
  13651. })(BABYLON || (BABYLON = {}));
  13652. //# sourceMappingURL=babylon.camera.js.map
  13653. var BABYLON;
  13654. (function (BABYLON) {
  13655. BABYLON.CameraInputTypes = {};
  13656. var CameraInputsManager = (function () {
  13657. function CameraInputsManager(camera) {
  13658. this.attached = {};
  13659. this.camera = camera;
  13660. this.checkInputs = function () { };
  13661. }
  13662. CameraInputsManager.prototype.add = function (input) {
  13663. var type = input.getSimpleName();
  13664. if (this.attached[type]) {
  13665. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13666. return;
  13667. }
  13668. this.attached[type] = input;
  13669. input.camera = this.camera;
  13670. //for checkInputs, we are dynamically creating a function
  13671. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13672. if (input.checkInputs) {
  13673. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13674. }
  13675. if (this.attachedElement) {
  13676. input.attachControl(this.attachedElement);
  13677. }
  13678. };
  13679. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13680. for (var cam in this.attached) {
  13681. var input = this.attached[cam];
  13682. if (input === inputToRemove) {
  13683. input.detachControl(this.attachedElement);
  13684. delete this.attached[cam];
  13685. this.rebuildInputCheck();
  13686. }
  13687. }
  13688. };
  13689. CameraInputsManager.prototype.removeByType = function (inputType) {
  13690. for (var cam in this.attached) {
  13691. var input = this.attached[cam];
  13692. if (input.getTypeName() === inputType) {
  13693. input.detachControl(this.attachedElement);
  13694. delete this.attached[cam];
  13695. this.rebuildInputCheck();
  13696. }
  13697. }
  13698. };
  13699. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13700. var current = this.checkInputs;
  13701. return function () {
  13702. current();
  13703. fn();
  13704. };
  13705. };
  13706. CameraInputsManager.prototype.attachInput = function (input) {
  13707. input.attachControl(this.attachedElement, this.noPreventDefault);
  13708. };
  13709. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13710. if (this.attachedElement) {
  13711. return;
  13712. }
  13713. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13714. this.attachedElement = element;
  13715. this.noPreventDefault = noPreventDefault;
  13716. for (var cam in this.attached) {
  13717. var input = this.attached[cam];
  13718. this.attached[cam].attachControl(element, noPreventDefault);
  13719. }
  13720. };
  13721. CameraInputsManager.prototype.detachElement = function (element) {
  13722. if (this.attachedElement !== element) {
  13723. return;
  13724. }
  13725. for (var cam in this.attached) {
  13726. var input = this.attached[cam];
  13727. this.attached[cam].detachControl(element);
  13728. }
  13729. this.attachedElement = null;
  13730. };
  13731. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13732. this.checkInputs = function () { };
  13733. for (var cam in this.attached) {
  13734. var input = this.attached[cam];
  13735. if (input.checkInputs) {
  13736. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13737. }
  13738. }
  13739. };
  13740. CameraInputsManager.prototype.clear = function () {
  13741. if (this.attachedElement) {
  13742. this.detachElement(this.attachedElement);
  13743. }
  13744. this.attached = {};
  13745. this.attachedElement = null;
  13746. this.checkInputs = function () { };
  13747. };
  13748. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13749. var inputs = {};
  13750. for (var cam in this.attached) {
  13751. var input = this.attached[cam];
  13752. var res = BABYLON.SerializationHelper.Serialize(input);
  13753. inputs[input.getTypeName()] = res;
  13754. }
  13755. serializedCamera.inputsmgr = inputs;
  13756. };
  13757. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13758. var parsedInputs = parsedCamera.inputsmgr;
  13759. if (parsedInputs) {
  13760. this.clear();
  13761. for (var n in parsedInputs) {
  13762. var construct = BABYLON.CameraInputTypes[n];
  13763. if (construct) {
  13764. var parsedinput = parsedInputs[n];
  13765. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13766. this.add(input);
  13767. }
  13768. }
  13769. }
  13770. else {
  13771. //2016-03-08 this part is for managing backward compatibility
  13772. for (var n in this.attached) {
  13773. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13774. if (construct) {
  13775. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13776. this.remove(this.attached[n]);
  13777. this.add(input);
  13778. }
  13779. }
  13780. }
  13781. };
  13782. return CameraInputsManager;
  13783. }());
  13784. BABYLON.CameraInputsManager = CameraInputsManager;
  13785. })(BABYLON || (BABYLON = {}));
  13786. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  13787. var BABYLON;
  13788. (function (BABYLON) {
  13789. var FreeCameraMouseInput = (function () {
  13790. function FreeCameraMouseInput(touchEnabled) {
  13791. if (touchEnabled === void 0) { touchEnabled = true; }
  13792. this.touchEnabled = touchEnabled;
  13793. this.buttons = [0, 1, 2];
  13794. this.angularSensibility = 2000.0;
  13795. }
  13796. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13797. var _this = this;
  13798. var engine = this.camera.getEngine();
  13799. if (!this._pointerInput) {
  13800. this._pointerInput = function (p, s) {
  13801. var evt = p.event;
  13802. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13803. return;
  13804. }
  13805. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  13806. return;
  13807. }
  13808. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13809. try {
  13810. evt.srcElement.setPointerCapture(evt.pointerId);
  13811. }
  13812. catch (e) {
  13813. }
  13814. _this.previousPosition = {
  13815. x: evt.clientX,
  13816. y: evt.clientY
  13817. };
  13818. if (!noPreventDefault) {
  13819. evt.preventDefault();
  13820. element.focus();
  13821. }
  13822. }
  13823. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13824. try {
  13825. evt.srcElement.releasePointerCapture(evt.pointerId);
  13826. }
  13827. catch (e) {
  13828. }
  13829. _this.previousPosition = null;
  13830. if (!noPreventDefault) {
  13831. evt.preventDefault();
  13832. }
  13833. }
  13834. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13835. if (!_this.previousPosition || engine.isPointerLock) {
  13836. return;
  13837. }
  13838. var offsetX = evt.clientX - _this.previousPosition.x;
  13839. var offsetY = evt.clientY - _this.previousPosition.y;
  13840. if (_this.camera.getScene().useRightHandedSystem) {
  13841. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13842. }
  13843. else {
  13844. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13845. }
  13846. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13847. _this.previousPosition = {
  13848. x: evt.clientX,
  13849. y: evt.clientY
  13850. };
  13851. if (!noPreventDefault) {
  13852. evt.preventDefault();
  13853. }
  13854. }
  13855. };
  13856. }
  13857. this._onMouseMove = function (evt) {
  13858. if (!engine.isPointerLock) {
  13859. return;
  13860. }
  13861. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13862. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13863. if (_this.camera.getScene().useRightHandedSystem) {
  13864. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13865. }
  13866. else {
  13867. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13868. }
  13869. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13870. _this.previousPosition = null;
  13871. if (!noPreventDefault) {
  13872. evt.preventDefault();
  13873. }
  13874. };
  13875. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13876. element.addEventListener("mousemove", this._onMouseMove, false);
  13877. };
  13878. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13879. if (this._observer && element) {
  13880. this.camera.getScene().onPointerObservable.remove(this._observer);
  13881. element.removeEventListener("mousemove", this._onMouseMove);
  13882. this._observer = null;
  13883. this._onMouseMove = null;
  13884. this.previousPosition = null;
  13885. }
  13886. };
  13887. FreeCameraMouseInput.prototype.getTypeName = function () {
  13888. return "FreeCameraMouseInput";
  13889. };
  13890. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13891. return "mouse";
  13892. };
  13893. __decorate([
  13894. BABYLON.serialize()
  13895. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  13896. __decorate([
  13897. BABYLON.serialize()
  13898. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13899. return FreeCameraMouseInput;
  13900. }());
  13901. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13902. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13903. })(BABYLON || (BABYLON = {}));
  13904. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  13905. var BABYLON;
  13906. (function (BABYLON) {
  13907. var FreeCameraKeyboardMoveInput = (function () {
  13908. function FreeCameraKeyboardMoveInput() {
  13909. this._keys = [];
  13910. this.keysUp = [38];
  13911. this.keysDown = [40];
  13912. this.keysLeft = [37];
  13913. this.keysRight = [39];
  13914. }
  13915. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13916. var _this = this;
  13917. if (!this._onKeyDown) {
  13918. element.tabIndex = 1;
  13919. this._onKeyDown = function (evt) {
  13920. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13921. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13922. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13923. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13924. var index = _this._keys.indexOf(evt.keyCode);
  13925. if (index === -1) {
  13926. _this._keys.push(evt.keyCode);
  13927. }
  13928. if (!noPreventDefault) {
  13929. evt.preventDefault();
  13930. }
  13931. }
  13932. };
  13933. this._onKeyUp = function (evt) {
  13934. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13935. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13936. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13937. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13938. var index = _this._keys.indexOf(evt.keyCode);
  13939. if (index >= 0) {
  13940. _this._keys.splice(index, 1);
  13941. }
  13942. if (!noPreventDefault) {
  13943. evt.preventDefault();
  13944. }
  13945. }
  13946. };
  13947. element.addEventListener("keydown", this._onKeyDown, false);
  13948. element.addEventListener("keyup", this._onKeyUp, false);
  13949. BABYLON.Tools.RegisterTopRootEvents([
  13950. { name: "blur", handler: this._onLostFocus }
  13951. ]);
  13952. }
  13953. };
  13954. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13955. if (this._onKeyDown) {
  13956. element.removeEventListener("keydown", this._onKeyDown);
  13957. element.removeEventListener("keyup", this._onKeyUp);
  13958. BABYLON.Tools.UnregisterTopRootEvents([
  13959. { name: "blur", handler: this._onLostFocus }
  13960. ]);
  13961. this._keys = [];
  13962. this._onKeyDown = null;
  13963. this._onKeyUp = null;
  13964. }
  13965. };
  13966. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13967. if (this._onKeyDown) {
  13968. var camera = this.camera;
  13969. // Keyboard
  13970. for (var index = 0; index < this._keys.length; index++) {
  13971. var keyCode = this._keys[index];
  13972. var speed = camera._computeLocalCameraSpeed();
  13973. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13974. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13975. }
  13976. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13977. camera._localDirection.copyFromFloats(0, 0, speed);
  13978. }
  13979. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13980. camera._localDirection.copyFromFloats(speed, 0, 0);
  13981. }
  13982. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13983. camera._localDirection.copyFromFloats(0, 0, -speed);
  13984. }
  13985. if (camera.getScene().useRightHandedSystem) {
  13986. camera._localDirection.z *= -1;
  13987. }
  13988. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13989. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13990. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13991. }
  13992. }
  13993. };
  13994. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13995. return "FreeCameraKeyboardMoveInput";
  13996. };
  13997. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13998. this._keys = [];
  13999. };
  14000. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14001. return "keyboard";
  14002. };
  14003. __decorate([
  14004. BABYLON.serialize()
  14005. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14006. __decorate([
  14007. BABYLON.serialize()
  14008. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14009. __decorate([
  14010. BABYLON.serialize()
  14011. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14012. __decorate([
  14013. BABYLON.serialize()
  14014. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14015. return FreeCameraKeyboardMoveInput;
  14016. }());
  14017. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14018. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14019. })(BABYLON || (BABYLON = {}));
  14020. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14021. var BABYLON;
  14022. (function (BABYLON) {
  14023. var FreeCameraTouchInput = (function () {
  14024. function FreeCameraTouchInput() {
  14025. this._offsetX = null;
  14026. this._offsetY = null;
  14027. this._pointerCount = 0;
  14028. this._pointerPressed = [];
  14029. this.touchAngularSensibility = 200000.0;
  14030. this.touchMoveSensibility = 250.0;
  14031. }
  14032. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14033. var _this = this;
  14034. var previousPosition;
  14035. if (this._pointerInput === undefined) {
  14036. this._onLostFocus = function (evt) {
  14037. _this._offsetX = null;
  14038. _this._offsetY = null;
  14039. };
  14040. this._pointerInput = function (p, s) {
  14041. var evt = p.event;
  14042. if (evt.pointerType === "mouse") {
  14043. return;
  14044. }
  14045. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14046. if (!noPreventDefault) {
  14047. evt.preventDefault();
  14048. }
  14049. _this._pointerPressed.push(evt.pointerId);
  14050. if (_this._pointerPressed.length !== 1) {
  14051. return;
  14052. }
  14053. previousPosition = {
  14054. x: evt.clientX,
  14055. y: evt.clientY
  14056. };
  14057. }
  14058. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14059. if (!noPreventDefault) {
  14060. evt.preventDefault();
  14061. }
  14062. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14063. if (index === -1) {
  14064. return;
  14065. }
  14066. _this._pointerPressed.splice(index, 1);
  14067. if (index != 0) {
  14068. return;
  14069. }
  14070. previousPosition = null;
  14071. _this._offsetX = null;
  14072. _this._offsetY = null;
  14073. }
  14074. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14075. if (!noPreventDefault) {
  14076. evt.preventDefault();
  14077. }
  14078. if (!previousPosition) {
  14079. return;
  14080. }
  14081. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14082. if (index != 0) {
  14083. return;
  14084. }
  14085. _this._offsetX = evt.clientX - previousPosition.x;
  14086. _this._offsetY = -(evt.clientY - previousPosition.y);
  14087. }
  14088. };
  14089. }
  14090. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14091. element.addEventListener("blur", this._onLostFocus);
  14092. };
  14093. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14094. if (this._pointerInput && element) {
  14095. this.camera.getScene().onPointerObservable.remove(this._observer);
  14096. this._observer = null;
  14097. element.removeEventListener("blur", this._onLostFocus);
  14098. this._onLostFocus = null;
  14099. this._pointerPressed = [];
  14100. this._offsetX = null;
  14101. this._offsetY = null;
  14102. this._pointerCount = 0;
  14103. }
  14104. };
  14105. FreeCameraTouchInput.prototype.checkInputs = function () {
  14106. if (this._offsetX) {
  14107. var camera = this.camera;
  14108. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14109. if (this._pointerPressed.length > 1) {
  14110. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14111. }
  14112. else {
  14113. var speed = camera._computeLocalCameraSpeed();
  14114. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14115. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14116. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14117. }
  14118. }
  14119. };
  14120. FreeCameraTouchInput.prototype.getTypeName = function () {
  14121. return "FreeCameraTouchInput";
  14122. };
  14123. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14124. return "touch";
  14125. };
  14126. __decorate([
  14127. BABYLON.serialize()
  14128. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14129. __decorate([
  14130. BABYLON.serialize()
  14131. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14132. return FreeCameraTouchInput;
  14133. }());
  14134. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14135. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14136. })(BABYLON || (BABYLON = {}));
  14137. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14138. var BABYLON;
  14139. (function (BABYLON) {
  14140. var FreeCameraDeviceOrientationInput = (function () {
  14141. function FreeCameraDeviceOrientationInput() {
  14142. var _this = this;
  14143. this._screenOrientationAngle = 0;
  14144. this._screenQuaternion = new BABYLON.Quaternion();
  14145. this._alpha = 0;
  14146. this._beta = 0;
  14147. this._gamma = 0;
  14148. this._orientationChanged = function () {
  14149. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14150. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14151. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14152. };
  14153. this._deviceOrientation = function (evt) {
  14154. _this._alpha = evt.alpha;
  14155. _this._beta = evt.beta;
  14156. _this._gamma = evt.gamma;
  14157. };
  14158. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14159. this._orientationChanged();
  14160. }
  14161. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14162. get: function () {
  14163. return this._camera;
  14164. },
  14165. set: function (camera) {
  14166. this._camera = camera;
  14167. if (!this._camera.rotationQuaternion)
  14168. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14169. },
  14170. enumerable: true,
  14171. configurable: true
  14172. });
  14173. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14174. window.addEventListener("orientationchange", this._orientationChanged);
  14175. window.addEventListener("deviceorientation", this._deviceOrientation);
  14176. //In certain cases, the attach control is called AFTER orientation was changed,
  14177. //So this is needed.
  14178. this._orientationChanged();
  14179. };
  14180. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14181. window.removeEventListener("orientationchange", this._orientationChanged);
  14182. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14183. };
  14184. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14185. //if no device orientation provided, don't update the rotation.
  14186. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14187. if (!this._alpha)
  14188. return;
  14189. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14190. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14191. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14192. //Mirror on XY Plane
  14193. this._camera.rotationQuaternion.z *= -1;
  14194. this._camera.rotationQuaternion.w *= -1;
  14195. };
  14196. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14197. return "FreeCameraDeviceOrientationInput";
  14198. };
  14199. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14200. return "deviceOrientation";
  14201. };
  14202. return FreeCameraDeviceOrientationInput;
  14203. }());
  14204. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14205. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14206. })(BABYLON || (BABYLON = {}));
  14207. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14208. var BABYLON;
  14209. (function (BABYLON) {
  14210. var FreeCameraGamepadInput = (function () {
  14211. function FreeCameraGamepadInput() {
  14212. this.gamepadAngularSensibility = 200;
  14213. this.gamepadMoveSensibility = 40;
  14214. }
  14215. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14216. var _this = this;
  14217. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14218. };
  14219. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14220. if (this._gamepads) {
  14221. this._gamepads.dispose();
  14222. }
  14223. this.gamepad = null;
  14224. };
  14225. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14226. if (this.gamepad) {
  14227. var camera = this.camera;
  14228. var LSValues = this.gamepad.leftStick;
  14229. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14230. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14231. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14232. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14233. var RSValues = this.gamepad.rightStick;
  14234. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14235. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14236. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14237. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14238. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14239. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14240. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14241. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14242. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14243. }
  14244. };
  14245. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14246. // Only the first gamepad can control the camera
  14247. if (gamepad.index === 0) {
  14248. this.gamepad = gamepad;
  14249. }
  14250. };
  14251. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14252. return "FreeCameraGamepadInput";
  14253. };
  14254. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14255. return "gamepad";
  14256. };
  14257. __decorate([
  14258. BABYLON.serialize()
  14259. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14260. __decorate([
  14261. BABYLON.serialize()
  14262. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14263. return FreeCameraGamepadInput;
  14264. }());
  14265. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14266. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14267. })(BABYLON || (BABYLON = {}));
  14268. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  14269. var BABYLON;
  14270. (function (BABYLON) {
  14271. var ArcRotateCameraKeyboardMoveInput = (function () {
  14272. function ArcRotateCameraKeyboardMoveInput() {
  14273. this._keys = [];
  14274. this.keysUp = [38];
  14275. this.keysDown = [40];
  14276. this.keysLeft = [37];
  14277. this.keysRight = [39];
  14278. }
  14279. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14280. var _this = this;
  14281. element.tabIndex = 1;
  14282. this._onKeyDown = function (evt) {
  14283. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14284. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14285. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14286. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14287. var index = _this._keys.indexOf(evt.keyCode);
  14288. if (index === -1) {
  14289. _this._keys.push(evt.keyCode);
  14290. }
  14291. if (evt.preventDefault) {
  14292. if (!noPreventDefault) {
  14293. evt.preventDefault();
  14294. }
  14295. }
  14296. }
  14297. };
  14298. this._onKeyUp = function (evt) {
  14299. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14300. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14301. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14302. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14303. var index = _this._keys.indexOf(evt.keyCode);
  14304. if (index >= 0) {
  14305. _this._keys.splice(index, 1);
  14306. }
  14307. if (evt.preventDefault) {
  14308. if (!noPreventDefault) {
  14309. evt.preventDefault();
  14310. }
  14311. }
  14312. }
  14313. };
  14314. this._onLostFocus = function () {
  14315. _this._keys = [];
  14316. };
  14317. element.addEventListener("keydown", this._onKeyDown, false);
  14318. element.addEventListener("keyup", this._onKeyUp, false);
  14319. BABYLON.Tools.RegisterTopRootEvents([
  14320. { name: "blur", handler: this._onLostFocus }
  14321. ]);
  14322. };
  14323. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14324. if (element) {
  14325. element.removeEventListener("keydown", this._onKeyDown);
  14326. element.removeEventListener("keyup", this._onKeyUp);
  14327. }
  14328. BABYLON.Tools.UnregisterTopRootEvents([
  14329. { name: "blur", handler: this._onLostFocus }
  14330. ]);
  14331. this._keys = [];
  14332. this._onKeyDown = null;
  14333. this._onKeyUp = null;
  14334. this._onLostFocus = null;
  14335. };
  14336. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14337. if (this._onKeyDown) {
  14338. var camera = this.camera;
  14339. for (var index = 0; index < this._keys.length; index++) {
  14340. var keyCode = this._keys[index];
  14341. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14342. camera.inertialAlphaOffset -= 0.01;
  14343. }
  14344. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14345. camera.inertialBetaOffset -= 0.01;
  14346. }
  14347. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14348. camera.inertialAlphaOffset += 0.01;
  14349. }
  14350. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14351. camera.inertialBetaOffset += 0.01;
  14352. }
  14353. }
  14354. }
  14355. };
  14356. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14357. return "ArcRotateCameraKeyboardMoveInput";
  14358. };
  14359. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14360. return "keyboard";
  14361. };
  14362. __decorate([
  14363. BABYLON.serialize()
  14364. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14365. __decorate([
  14366. BABYLON.serialize()
  14367. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14368. __decorate([
  14369. BABYLON.serialize()
  14370. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14371. __decorate([
  14372. BABYLON.serialize()
  14373. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14374. return ArcRotateCameraKeyboardMoveInput;
  14375. }());
  14376. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14377. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14378. })(BABYLON || (BABYLON = {}));
  14379. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  14380. var BABYLON;
  14381. (function (BABYLON) {
  14382. var ArcRotateCameraMouseWheelInput = (function () {
  14383. function ArcRotateCameraMouseWheelInput() {
  14384. this.wheelPrecision = 3.0;
  14385. }
  14386. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14387. var _this = this;
  14388. this._wheel = function (p, s) {
  14389. //sanity check - this should be a PointerWheel event.
  14390. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14391. return;
  14392. var event = p.event;
  14393. var delta = 0;
  14394. if (event.wheelDelta) {
  14395. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14396. }
  14397. else if (event.detail) {
  14398. delta = -event.detail / _this.wheelPrecision;
  14399. }
  14400. if (delta)
  14401. _this.camera.inertialRadiusOffset += delta;
  14402. if (event.preventDefault) {
  14403. if (!noPreventDefault) {
  14404. event.preventDefault();
  14405. }
  14406. }
  14407. };
  14408. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14409. };
  14410. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14411. if (this._observer && element) {
  14412. this.camera.getScene().onPointerObservable.remove(this._observer);
  14413. this._observer = null;
  14414. this._wheel = null;
  14415. }
  14416. };
  14417. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14418. return "ArcRotateCameraMouseWheelInput";
  14419. };
  14420. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14421. return "mousewheel";
  14422. };
  14423. __decorate([
  14424. BABYLON.serialize()
  14425. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14426. return ArcRotateCameraMouseWheelInput;
  14427. }());
  14428. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14429. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14430. })(BABYLON || (BABYLON = {}));
  14431. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  14432. var BABYLON;
  14433. (function (BABYLON) {
  14434. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14435. var ArcRotateCameraPointersInput = (function () {
  14436. function ArcRotateCameraPointersInput() {
  14437. this.buttons = [0, 1, 2];
  14438. this.angularSensibilityX = 1000.0;
  14439. this.angularSensibilityY = 1000.0;
  14440. this.pinchPrecision = 6.0;
  14441. this.panningSensibility = 50.0;
  14442. this._isPanClick = false;
  14443. this.pinchInwards = true;
  14444. }
  14445. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14446. var _this = this;
  14447. var engine = this.camera.getEngine();
  14448. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14449. var pointA, pointB;
  14450. var previousPinchDistance = 0;
  14451. this._pointerInput = function (p, s) {
  14452. var evt = p.event;
  14453. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14454. return;
  14455. }
  14456. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14457. try {
  14458. evt.srcElement.setPointerCapture(evt.pointerId);
  14459. }
  14460. catch (e) {
  14461. }
  14462. // Manage panning with pan button click
  14463. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14464. // manage pointers
  14465. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14466. if (pointA === undefined) {
  14467. pointA = cacheSoloPointer;
  14468. }
  14469. else if (pointB === undefined) {
  14470. pointB = cacheSoloPointer;
  14471. }
  14472. if (!noPreventDefault) {
  14473. evt.preventDefault();
  14474. element.focus();
  14475. }
  14476. }
  14477. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14478. try {
  14479. evt.srcElement.releasePointerCapture(evt.pointerId);
  14480. }
  14481. catch (e) {
  14482. }
  14483. cacheSoloPointer = null;
  14484. previousPinchDistance = 0;
  14485. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14486. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14487. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14488. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14489. pointA = pointB = undefined;
  14490. if (!noPreventDefault) {
  14491. evt.preventDefault();
  14492. }
  14493. }
  14494. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14495. if (!noPreventDefault) {
  14496. evt.preventDefault();
  14497. }
  14498. // One button down
  14499. if (pointA && pointB === undefined) {
  14500. if (_this.panningSensibility !== 0 &&
  14501. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14502. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14503. _this.camera
  14504. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14505. _this.camera
  14506. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14507. }
  14508. else {
  14509. var offsetX = evt.clientX - cacheSoloPointer.x;
  14510. var offsetY = evt.clientY - cacheSoloPointer.y;
  14511. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14512. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14513. }
  14514. cacheSoloPointer.x = evt.clientX;
  14515. cacheSoloPointer.y = evt.clientY;
  14516. }
  14517. else if (pointA && pointB) {
  14518. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14519. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14520. ed.x = evt.clientX;
  14521. ed.y = evt.clientY;
  14522. var direction = _this.pinchInwards ? 1 : -1;
  14523. var distX = pointA.x - pointB.x;
  14524. var distY = pointA.y - pointB.y;
  14525. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14526. if (previousPinchDistance === 0) {
  14527. previousPinchDistance = pinchSquaredDistance;
  14528. return;
  14529. }
  14530. if (pinchSquaredDistance !== previousPinchDistance) {
  14531. _this.camera
  14532. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14533. (_this.pinchPrecision *
  14534. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14535. direction);
  14536. previousPinchDistance = pinchSquaredDistance;
  14537. }
  14538. }
  14539. }
  14540. };
  14541. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14542. this._onContextMenu = function (evt) {
  14543. evt.preventDefault();
  14544. };
  14545. if (!this.camera._useCtrlForPanning) {
  14546. element.addEventListener("contextmenu", this._onContextMenu, false);
  14547. }
  14548. this._onLostFocus = function () {
  14549. //this._keys = [];
  14550. pointA = pointB = undefined;
  14551. previousPinchDistance = 0;
  14552. cacheSoloPointer = null;
  14553. };
  14554. this._onMouseMove = function (evt) {
  14555. if (!engine.isPointerLock) {
  14556. return;
  14557. }
  14558. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14559. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14560. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14561. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14562. if (!noPreventDefault) {
  14563. evt.preventDefault();
  14564. }
  14565. };
  14566. this._onGestureStart = function (e) {
  14567. if (window.MSGesture === undefined) {
  14568. return;
  14569. }
  14570. if (!_this._MSGestureHandler) {
  14571. _this._MSGestureHandler = new MSGesture();
  14572. _this._MSGestureHandler.target = element;
  14573. }
  14574. _this._MSGestureHandler.addPointer(e.pointerId);
  14575. };
  14576. this._onGesture = function (e) {
  14577. _this.camera.radius *= e.scale;
  14578. if (e.preventDefault) {
  14579. if (!noPreventDefault) {
  14580. e.stopPropagation();
  14581. e.preventDefault();
  14582. }
  14583. }
  14584. };
  14585. element.addEventListener("mousemove", this._onMouseMove, false);
  14586. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14587. element.addEventListener("MSGestureChange", this._onGesture, false);
  14588. element.addEventListener("keydown", this._onKeyDown, false);
  14589. element.addEventListener("keyup", this._onKeyUp, false);
  14590. BABYLON.Tools.RegisterTopRootEvents([
  14591. { name: "blur", handler: this._onLostFocus }
  14592. ]);
  14593. };
  14594. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14595. if (element && this._observer) {
  14596. this.camera.getScene().onPointerObservable.remove(this._observer);
  14597. this._observer = null;
  14598. element.removeEventListener("contextmenu", this._onContextMenu);
  14599. element.removeEventListener("mousemove", this._onMouseMove);
  14600. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14601. element.removeEventListener("MSGestureChange", this._onGesture);
  14602. element.removeEventListener("keydown", this._onKeyDown);
  14603. element.removeEventListener("keyup", this._onKeyUp);
  14604. this._isPanClick = false;
  14605. this.pinchInwards = true;
  14606. this._onKeyDown = null;
  14607. this._onKeyUp = null;
  14608. this._onMouseMove = null;
  14609. this._onGestureStart = null;
  14610. this._onGesture = null;
  14611. this._MSGestureHandler = null;
  14612. this._onLostFocus = null;
  14613. this._onContextMenu = null;
  14614. }
  14615. BABYLON.Tools.UnregisterTopRootEvents([
  14616. { name: "blur", handler: this._onLostFocus }
  14617. ]);
  14618. };
  14619. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14620. return "ArcRotateCameraPointersInput";
  14621. };
  14622. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14623. return "pointers";
  14624. };
  14625. __decorate([
  14626. BABYLON.serialize()
  14627. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14628. __decorate([
  14629. BABYLON.serialize()
  14630. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14631. __decorate([
  14632. BABYLON.serialize()
  14633. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14634. __decorate([
  14635. BABYLON.serialize()
  14636. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14637. __decorate([
  14638. BABYLON.serialize()
  14639. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14640. return ArcRotateCameraPointersInput;
  14641. }());
  14642. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14643. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14644. })(BABYLON || (BABYLON = {}));
  14645. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  14646. var BABYLON;
  14647. (function (BABYLON) {
  14648. var ArcRotateCameraGamepadInput = (function () {
  14649. function ArcRotateCameraGamepadInput() {
  14650. this.gamepadRotationSensibility = 80;
  14651. this.gamepadMoveSensibility = 40;
  14652. }
  14653. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14654. var _this = this;
  14655. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14656. };
  14657. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14658. if (this._gamepads) {
  14659. this._gamepads.dispose();
  14660. }
  14661. this.gamepad = null;
  14662. };
  14663. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14664. if (this.gamepad) {
  14665. var camera = this.camera;
  14666. var RSValues = this.gamepad.rightStick;
  14667. if (RSValues.x != 0) {
  14668. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14669. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14670. camera.inertialAlphaOffset += normalizedRX;
  14671. }
  14672. }
  14673. if (RSValues.y != 0) {
  14674. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14675. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14676. camera.inertialBetaOffset += normalizedRY;
  14677. }
  14678. }
  14679. var LSValues = this.gamepad.leftStick;
  14680. if (LSValues.y != 0) {
  14681. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14682. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14683. this.camera.inertialRadiusOffset -= normalizedLY;
  14684. }
  14685. }
  14686. }
  14687. };
  14688. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14689. // Only the first gamepad can control the camera
  14690. if (gamepad.index === 0) {
  14691. this.gamepad = gamepad;
  14692. }
  14693. };
  14694. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14695. return "ArcRotateCameraGamepadInput";
  14696. };
  14697. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14698. return "gamepad";
  14699. };
  14700. __decorate([
  14701. BABYLON.serialize()
  14702. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14703. __decorate([
  14704. BABYLON.serialize()
  14705. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14706. return ArcRotateCameraGamepadInput;
  14707. }());
  14708. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14709. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14710. })(BABYLON || (BABYLON = {}));
  14711. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  14712. var BABYLON;
  14713. (function (BABYLON) {
  14714. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14715. function ArcRotateCameraVRDeviceOrientationInput() {
  14716. this.alphaCorrection = 1;
  14717. this.betaCorrection = 1;
  14718. this.gammaCorrection = 1;
  14719. this._alpha = 0;
  14720. this._beta = 0;
  14721. this._gamma = 0;
  14722. this._dirty = false;
  14723. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14724. }
  14725. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14726. this.camera.attachControl(element, noPreventDefault);
  14727. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14728. };
  14729. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14730. var camera = this.camera;
  14731. this._alpha = +evt.alpha | 0;
  14732. this._beta = +evt.beta | 0;
  14733. this._gamma = +evt.gamma | 0;
  14734. this._dirty = true;
  14735. };
  14736. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14737. if (this._dirty) {
  14738. this._dirty = false;
  14739. if (this._gamma < 0) {
  14740. this._gamma = 180 + this._gamma;
  14741. }
  14742. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14743. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14744. }
  14745. };
  14746. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14747. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14748. };
  14749. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14750. return "ArcRotateCameraVRDeviceOrientationInput";
  14751. };
  14752. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14753. return "VRDeviceOrientation";
  14754. };
  14755. return ArcRotateCameraVRDeviceOrientationInput;
  14756. }());
  14757. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14758. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14759. })(BABYLON || (BABYLON = {}));
  14760. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  14761. var BABYLON;
  14762. (function (BABYLON) {
  14763. var TargetCamera = (function (_super) {
  14764. __extends(TargetCamera, _super);
  14765. function TargetCamera(name, position, scene) {
  14766. _super.call(this, name, position, scene);
  14767. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14768. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14769. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14770. this.speed = 2.0;
  14771. this.noRotationConstraint = false;
  14772. this.lockedTarget = null;
  14773. this._currentTarget = BABYLON.Vector3.Zero();
  14774. this._viewMatrix = BABYLON.Matrix.Zero();
  14775. this._camMatrix = BABYLON.Matrix.Zero();
  14776. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14777. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14778. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14779. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14780. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14781. this._lookAtTemp = BABYLON.Matrix.Zero();
  14782. this._tempMatrix = BABYLON.Matrix.Zero();
  14783. }
  14784. TargetCamera.prototype.getFrontPosition = function (distance) {
  14785. var direction = this.getTarget().subtract(this.position);
  14786. direction.normalize();
  14787. direction.scaleInPlace(distance);
  14788. return this.globalPosition.add(direction);
  14789. };
  14790. TargetCamera.prototype._getLockedTargetPosition = function () {
  14791. if (!this.lockedTarget) {
  14792. return null;
  14793. }
  14794. if (this.lockedTarget.absolutePosition) {
  14795. this.lockedTarget.computeWorldMatrix();
  14796. }
  14797. return this.lockedTarget.absolutePosition || this.lockedTarget;
  14798. };
  14799. // Cache
  14800. TargetCamera.prototype._initCache = function () {
  14801. _super.prototype._initCache.call(this);
  14802. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14803. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14804. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14805. };
  14806. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14807. if (!ignoreParentClass) {
  14808. _super.prototype._updateCache.call(this);
  14809. }
  14810. var lockedTargetPosition = this._getLockedTargetPosition();
  14811. if (!lockedTargetPosition) {
  14812. this._cache.lockedTarget = null;
  14813. }
  14814. else {
  14815. if (!this._cache.lockedTarget) {
  14816. this._cache.lockedTarget = lockedTargetPosition.clone();
  14817. }
  14818. else {
  14819. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14820. }
  14821. }
  14822. this._cache.rotation.copyFrom(this.rotation);
  14823. if (this.rotationQuaternion)
  14824. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14825. };
  14826. // Synchronized
  14827. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14828. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14829. return false;
  14830. }
  14831. var lockedTargetPosition = this._getLockedTargetPosition();
  14832. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14833. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14834. };
  14835. // Methods
  14836. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14837. var engine = this.getEngine();
  14838. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14839. };
  14840. // Target
  14841. TargetCamera.prototype.setTarget = function (target) {
  14842. this.upVector.normalize();
  14843. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14844. this._camMatrix.invert();
  14845. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14846. var vDir = target.subtract(this.position);
  14847. if (vDir.x >= 0.0) {
  14848. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14849. }
  14850. else {
  14851. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14852. }
  14853. this.rotation.z = 0;
  14854. if (isNaN(this.rotation.x)) {
  14855. this.rotation.x = 0;
  14856. }
  14857. if (isNaN(this.rotation.y)) {
  14858. this.rotation.y = 0;
  14859. }
  14860. if (isNaN(this.rotation.z)) {
  14861. this.rotation.z = 0;
  14862. }
  14863. if (this.rotationQuaternion) {
  14864. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14865. }
  14866. };
  14867. TargetCamera.prototype.getTarget = function () {
  14868. return this._currentTarget;
  14869. };
  14870. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14871. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14872. };
  14873. TargetCamera.prototype._updatePosition = function () {
  14874. this.position.addInPlace(this.cameraDirection);
  14875. };
  14876. TargetCamera.prototype._checkInputs = function () {
  14877. var needToMove = this._decideIfNeedsToMove();
  14878. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14879. // Move
  14880. if (needToMove) {
  14881. this._updatePosition();
  14882. }
  14883. // Rotate
  14884. if (needToRotate) {
  14885. this.rotation.x += this.cameraRotation.x;
  14886. this.rotation.y += this.cameraRotation.y;
  14887. if (!this.noRotationConstraint) {
  14888. var limit = (Math.PI / 2) * 0.95;
  14889. if (this.rotation.x > limit)
  14890. this.rotation.x = limit;
  14891. if (this.rotation.x < -limit)
  14892. this.rotation.x = -limit;
  14893. }
  14894. }
  14895. // Inertia
  14896. if (needToMove) {
  14897. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14898. this.cameraDirection.x = 0;
  14899. }
  14900. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14901. this.cameraDirection.y = 0;
  14902. }
  14903. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14904. this.cameraDirection.z = 0;
  14905. }
  14906. this.cameraDirection.scaleInPlace(this.inertia);
  14907. }
  14908. if (needToRotate) {
  14909. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14910. this.cameraRotation.x = 0;
  14911. }
  14912. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14913. this.cameraRotation.y = 0;
  14914. }
  14915. this.cameraRotation.scaleInPlace(this.inertia);
  14916. }
  14917. _super.prototype._checkInputs.call(this);
  14918. };
  14919. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14920. if (this.rotationQuaternion) {
  14921. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14922. //update the up vector!
  14923. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14924. }
  14925. else {
  14926. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14927. }
  14928. };
  14929. TargetCamera.prototype._getViewMatrix = function () {
  14930. if (!this.lockedTarget) {
  14931. // Compute
  14932. this._updateCameraRotationMatrix();
  14933. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14934. // Computing target and final matrix
  14935. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14936. }
  14937. else {
  14938. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14939. }
  14940. if (this.getScene().useRightHandedSystem) {
  14941. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14942. }
  14943. else {
  14944. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14945. }
  14946. return this._viewMatrix;
  14947. };
  14948. /**
  14949. * @override
  14950. * Override Camera.createRigCamera
  14951. */
  14952. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14953. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14954. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14955. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14956. if (!this.rotationQuaternion) {
  14957. this.rotationQuaternion = new BABYLON.Quaternion();
  14958. }
  14959. rigCamera._cameraRigParams = {};
  14960. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14961. }
  14962. return rigCamera;
  14963. }
  14964. return null;
  14965. };
  14966. /**
  14967. * @override
  14968. * Override Camera._updateRigCameras
  14969. */
  14970. TargetCamera.prototype._updateRigCameras = function () {
  14971. var camLeft = this._rigCameras[0];
  14972. var camRight = this._rigCameras[1];
  14973. switch (this.cameraRigMode) {
  14974. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14975. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14976. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14977. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14978. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14979. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14980. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14981. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14982. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14983. camLeft.setTarget(this.getTarget());
  14984. camRight.setTarget(this.getTarget());
  14985. break;
  14986. case BABYLON.Camera.RIG_MODE_VR:
  14987. case BABYLON.Camera.RIG_MODE_WEBVR:
  14988. if (camLeft.rotationQuaternion) {
  14989. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14990. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14991. }
  14992. else {
  14993. camLeft.rotation.copyFrom(this.rotation);
  14994. camRight.rotation.copyFrom(this.rotation);
  14995. }
  14996. camLeft.position.copyFrom(this.position);
  14997. camRight.position.copyFrom(this.position);
  14998. break;
  14999. }
  15000. _super.prototype._updateRigCameras.call(this);
  15001. };
  15002. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15003. if (!this._rigCamTransformMatrix) {
  15004. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15005. }
  15006. var target = this.getTarget();
  15007. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15008. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15009. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15010. };
  15011. TargetCamera.prototype.getTypeName = function () {
  15012. return "TargetCamera";
  15013. };
  15014. __decorate([
  15015. BABYLON.serializeAsVector3()
  15016. ], TargetCamera.prototype, "rotation", void 0);
  15017. __decorate([
  15018. BABYLON.serialize()
  15019. ], TargetCamera.prototype, "speed", void 0);
  15020. __decorate([
  15021. BABYLON.serializeAsMeshReference("lockedTargetId")
  15022. ], TargetCamera.prototype, "lockedTarget", void 0);
  15023. return TargetCamera;
  15024. }(BABYLON.Camera));
  15025. BABYLON.TargetCamera = TargetCamera;
  15026. })(BABYLON || (BABYLON = {}));
  15027. //# sourceMappingURL=babylon.targetCamera.js.map
  15028. var BABYLON;
  15029. (function (BABYLON) {
  15030. var FreeCamera = (function (_super) {
  15031. __extends(FreeCamera, _super);
  15032. function FreeCamera(name, position, scene) {
  15033. var _this = this;
  15034. _super.call(this, name, position, scene);
  15035. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15036. this.checkCollisions = false;
  15037. this.applyGravity = false;
  15038. this._collider = new BABYLON.Collider();
  15039. this._needMoveForGravity = false;
  15040. this._oldPosition = BABYLON.Vector3.Zero();
  15041. this._diffPosition = BABYLON.Vector3.Zero();
  15042. this._newPosition = BABYLON.Vector3.Zero();
  15043. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15044. if (collidedMesh === void 0) { collidedMesh = null; }
  15045. //TODO move this to the collision coordinator!
  15046. if (_this.getScene().workerCollisions)
  15047. newPosition.multiplyInPlace(_this._collider.radius);
  15048. var updatePosition = function (newPos) {
  15049. _this._newPosition.copyFrom(newPos);
  15050. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15051. var oldPosition = _this.position.clone();
  15052. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15053. _this.position.addInPlace(_this._diffPosition);
  15054. if (_this.onCollide && collidedMesh) {
  15055. _this.onCollide(collidedMesh);
  15056. }
  15057. }
  15058. };
  15059. updatePosition(newPosition);
  15060. };
  15061. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  15062. this.inputs.addKeyboard().addMouse();
  15063. }
  15064. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15065. //-- begin properties for backward compatibility for inputs
  15066. get: function () {
  15067. var mouse = this.inputs.attached["mouse"];
  15068. if (mouse)
  15069. return mouse.angularSensibility;
  15070. },
  15071. set: function (value) {
  15072. var mouse = this.inputs.attached["mouse"];
  15073. if (mouse)
  15074. mouse.angularSensibility = value;
  15075. },
  15076. enumerable: true,
  15077. configurable: true
  15078. });
  15079. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15080. get: function () {
  15081. var keyboard = this.inputs.attached["keyboard"];
  15082. if (keyboard)
  15083. return keyboard.keysUp;
  15084. },
  15085. set: function (value) {
  15086. var keyboard = this.inputs.attached["keyboard"];
  15087. if (keyboard)
  15088. keyboard.keysUp = value;
  15089. },
  15090. enumerable: true,
  15091. configurable: true
  15092. });
  15093. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15094. get: function () {
  15095. var keyboard = this.inputs.attached["keyboard"];
  15096. if (keyboard)
  15097. return keyboard.keysDown;
  15098. },
  15099. set: function (value) {
  15100. var keyboard = this.inputs.attached["keyboard"];
  15101. if (keyboard)
  15102. keyboard.keysDown = value;
  15103. },
  15104. enumerable: true,
  15105. configurable: true
  15106. });
  15107. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15108. get: function () {
  15109. var keyboard = this.inputs.attached["keyboard"];
  15110. if (keyboard)
  15111. return keyboard.keysLeft;
  15112. },
  15113. set: function (value) {
  15114. var keyboard = this.inputs.attached["keyboard"];
  15115. if (keyboard)
  15116. keyboard.keysLeft = value;
  15117. },
  15118. enumerable: true,
  15119. configurable: true
  15120. });
  15121. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15122. get: function () {
  15123. var keyboard = this.inputs.attached["keyboard"];
  15124. if (keyboard)
  15125. return keyboard.keysRight;
  15126. },
  15127. set: function (value) {
  15128. var keyboard = this.inputs.attached["keyboard"];
  15129. if (keyboard)
  15130. keyboard.keysRight = value;
  15131. },
  15132. enumerable: true,
  15133. configurable: true
  15134. });
  15135. // Controls
  15136. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15137. this.inputs.attachElement(element, noPreventDefault);
  15138. };
  15139. FreeCamera.prototype.detachControl = function (element) {
  15140. this.inputs.detachElement(element);
  15141. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15142. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15143. };
  15144. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15145. var globalPosition;
  15146. if (this.parent) {
  15147. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15148. }
  15149. else {
  15150. globalPosition = this.position;
  15151. }
  15152. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15153. this._collider.radius = this.ellipsoid;
  15154. //no need for clone, as long as gravity is not on.
  15155. var actualVelocity = velocity;
  15156. //add gravity to the velocity to prevent the dual-collision checking
  15157. if (this.applyGravity) {
  15158. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15159. actualVelocity = velocity.add(this.getScene().gravity);
  15160. }
  15161. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15162. };
  15163. FreeCamera.prototype._checkInputs = function () {
  15164. if (!this._localDirection) {
  15165. this._localDirection = BABYLON.Vector3.Zero();
  15166. this._transformedDirection = BABYLON.Vector3.Zero();
  15167. }
  15168. this.inputs.checkInputs();
  15169. _super.prototype._checkInputs.call(this);
  15170. };
  15171. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15172. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15173. };
  15174. FreeCamera.prototype._updatePosition = function () {
  15175. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15176. this._collideWithWorld(this.cameraDirection);
  15177. }
  15178. else {
  15179. this.position.addInPlace(this.cameraDirection);
  15180. }
  15181. };
  15182. FreeCamera.prototype.dispose = function () {
  15183. this.inputs.clear();
  15184. _super.prototype.dispose.call(this);
  15185. };
  15186. FreeCamera.prototype.getTypeName = function () {
  15187. return "FreeCamera";
  15188. };
  15189. __decorate([
  15190. BABYLON.serializeAsVector3()
  15191. ], FreeCamera.prototype, "ellipsoid", void 0);
  15192. __decorate([
  15193. BABYLON.serialize()
  15194. ], FreeCamera.prototype, "checkCollisions", void 0);
  15195. __decorate([
  15196. BABYLON.serialize()
  15197. ], FreeCamera.prototype, "applyGravity", void 0);
  15198. return FreeCamera;
  15199. }(BABYLON.TargetCamera));
  15200. BABYLON.FreeCamera = FreeCamera;
  15201. })(BABYLON || (BABYLON = {}));
  15202. //# sourceMappingURL=babylon.freeCamera.js.map
  15203. var BABYLON;
  15204. (function (BABYLON) {
  15205. var FreeCameraInputsManager = (function (_super) {
  15206. __extends(FreeCameraInputsManager, _super);
  15207. function FreeCameraInputsManager(camera) {
  15208. _super.call(this, camera);
  15209. }
  15210. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15211. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15212. return this;
  15213. };
  15214. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15215. if (touchEnabled === void 0) { touchEnabled = true; }
  15216. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15217. return this;
  15218. };
  15219. FreeCameraInputsManager.prototype.addGamepad = function () {
  15220. this.add(new BABYLON.FreeCameraGamepadInput());
  15221. return this;
  15222. };
  15223. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15224. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15225. return this;
  15226. };
  15227. FreeCameraInputsManager.prototype.addTouch = function () {
  15228. this.add(new BABYLON.FreeCameraTouchInput());
  15229. return this;
  15230. };
  15231. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15232. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15233. return this;
  15234. };
  15235. return FreeCameraInputsManager;
  15236. }(BABYLON.CameraInputsManager));
  15237. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15238. })(BABYLON || (BABYLON = {}));
  15239. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  15240. var BABYLON;
  15241. (function (BABYLON) {
  15242. var FollowCamera = (function (_super) {
  15243. __extends(FollowCamera, _super);
  15244. function FollowCamera(name, position, scene, lockedTarget) {
  15245. _super.call(this, name, position, scene);
  15246. this.radius = 12;
  15247. this.rotationOffset = 0;
  15248. this.heightOffset = 4;
  15249. this.cameraAcceleration = 0.05;
  15250. this.maxCameraSpeed = 20;
  15251. this.lockedTarget = lockedTarget;
  15252. }
  15253. FollowCamera.prototype.getRadians = function (degrees) {
  15254. return degrees * Math.PI / 180;
  15255. };
  15256. FollowCamera.prototype.follow = function (cameraTarget) {
  15257. if (!cameraTarget)
  15258. return;
  15259. var yRotation;
  15260. if (cameraTarget.rotationQuaternion) {
  15261. var rotMatrix = new BABYLON.Matrix();
  15262. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15263. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15264. }
  15265. else {
  15266. yRotation = cameraTarget.rotation.y;
  15267. }
  15268. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15269. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15270. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15271. var dx = targetX - this.position.x;
  15272. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15273. var dz = (targetZ) - this.position.z;
  15274. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15275. var vy = dy * this.cameraAcceleration;
  15276. var vz = dz * this.cameraAcceleration * 2;
  15277. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15278. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15279. }
  15280. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15281. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15282. }
  15283. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15284. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15285. }
  15286. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15287. this.setTarget(cameraTarget.position);
  15288. };
  15289. FollowCamera.prototype._checkInputs = function () {
  15290. _super.prototype._checkInputs.call(this);
  15291. this.follow(this.lockedTarget);
  15292. };
  15293. FollowCamera.prototype.getTypeName = function () {
  15294. return "FollowCamera";
  15295. };
  15296. __decorate([
  15297. BABYLON.serialize()
  15298. ], FollowCamera.prototype, "radius", void 0);
  15299. __decorate([
  15300. BABYLON.serialize()
  15301. ], FollowCamera.prototype, "rotationOffset", void 0);
  15302. __decorate([
  15303. BABYLON.serialize()
  15304. ], FollowCamera.prototype, "heightOffset", void 0);
  15305. __decorate([
  15306. BABYLON.serialize()
  15307. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15308. __decorate([
  15309. BABYLON.serialize()
  15310. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15311. __decorate([
  15312. BABYLON.serializeAsMeshReference("lockedTargetId")
  15313. ], FollowCamera.prototype, "lockedTarget", void 0);
  15314. return FollowCamera;
  15315. }(BABYLON.TargetCamera));
  15316. BABYLON.FollowCamera = FollowCamera;
  15317. var ArcFollowCamera = (function (_super) {
  15318. __extends(ArcFollowCamera, _super);
  15319. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15320. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15321. this.alpha = alpha;
  15322. this.beta = beta;
  15323. this.radius = radius;
  15324. this.target = target;
  15325. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15326. this.follow();
  15327. }
  15328. ArcFollowCamera.prototype.follow = function () {
  15329. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15330. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15331. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15332. this.position = this.target.position.add(this._cartesianCoordinates);
  15333. this.setTarget(this.target.position);
  15334. };
  15335. ArcFollowCamera.prototype._checkInputs = function () {
  15336. _super.prototype._checkInputs.call(this);
  15337. this.follow();
  15338. };
  15339. ArcFollowCamera.prototype.getTypeName = function () {
  15340. return "ArcFollowCamera";
  15341. };
  15342. return ArcFollowCamera;
  15343. }(BABYLON.TargetCamera));
  15344. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15345. })(BABYLON || (BABYLON = {}));
  15346. //# sourceMappingURL=babylon.followCamera.js.map
  15347. var BABYLON;
  15348. (function (BABYLON) {
  15349. // We're mainly based on the logic defined into the FreeCamera code
  15350. var TouchCamera = (function (_super) {
  15351. __extends(TouchCamera, _super);
  15352. //-- end properties for backward compatibility for inputs
  15353. function TouchCamera(name, position, scene) {
  15354. _super.call(this, name, position, scene);
  15355. this.inputs.addTouch();
  15356. this._setupInputs();
  15357. }
  15358. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15359. //-- Begin properties for backward compatibility for inputs
  15360. get: function () {
  15361. var touch = this.inputs.attached["touch"];
  15362. if (touch)
  15363. return touch.touchAngularSensibility;
  15364. },
  15365. set: function (value) {
  15366. var touch = this.inputs.attached["touch"];
  15367. if (touch)
  15368. touch.touchAngularSensibility = value;
  15369. },
  15370. enumerable: true,
  15371. configurable: true
  15372. });
  15373. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15374. get: function () {
  15375. var touch = this.inputs.attached["touch"];
  15376. if (touch)
  15377. return touch.touchMoveSensibility;
  15378. },
  15379. set: function (value) {
  15380. var touch = this.inputs.attached["touch"];
  15381. if (touch)
  15382. touch.touchMoveSensibility = value;
  15383. },
  15384. enumerable: true,
  15385. configurable: true
  15386. });
  15387. TouchCamera.prototype.getTypeName = function () {
  15388. return "TouchCamera";
  15389. };
  15390. TouchCamera.prototype._setupInputs = function () {
  15391. var mouse = this.inputs.attached["mouse"];
  15392. if (mouse) {
  15393. mouse.touchEnabled = false;
  15394. }
  15395. };
  15396. return TouchCamera;
  15397. }(BABYLON.FreeCamera));
  15398. BABYLON.TouchCamera = TouchCamera;
  15399. })(BABYLON || (BABYLON = {}));
  15400. //# sourceMappingURL=babylon.touchCamera.js.map
  15401. var BABYLON;
  15402. (function (BABYLON) {
  15403. var ArcRotateCamera = (function (_super) {
  15404. __extends(ArcRotateCamera, _super);
  15405. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15406. var _this = this;
  15407. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15408. this.inertialAlphaOffset = 0;
  15409. this.inertialBetaOffset = 0;
  15410. this.inertialRadiusOffset = 0;
  15411. this.lowerAlphaLimit = null;
  15412. this.upperAlphaLimit = null;
  15413. this.lowerBetaLimit = 0.01;
  15414. this.upperBetaLimit = Math.PI;
  15415. this.lowerRadiusLimit = null;
  15416. this.upperRadiusLimit = null;
  15417. this.inertialPanningX = 0;
  15418. this.inertialPanningY = 0;
  15419. //-- end properties for backward compatibility for inputs
  15420. this.zoomOnFactor = 1;
  15421. this.targetScreenOffset = BABYLON.Vector2.Zero();
  15422. this.allowUpsideDown = true;
  15423. this._viewMatrix = new BABYLON.Matrix();
  15424. // Panning
  15425. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15426. this.checkCollisions = false;
  15427. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15428. this._collider = new BABYLON.Collider();
  15429. this._previousPosition = BABYLON.Vector3.Zero();
  15430. this._collisionVelocity = BABYLON.Vector3.Zero();
  15431. this._newPosition = BABYLON.Vector3.Zero();
  15432. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15433. if (collidedMesh === void 0) { collidedMesh = null; }
  15434. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15435. newPosition.multiplyInPlace(_this._collider.radius);
  15436. }
  15437. if (!collidedMesh) {
  15438. _this._previousPosition.copyFrom(_this.position);
  15439. }
  15440. else {
  15441. _this.setPosition(newPosition);
  15442. if (_this.onCollide) {
  15443. _this.onCollide(collidedMesh);
  15444. }
  15445. }
  15446. // Recompute because of constraints
  15447. var cosa = Math.cos(_this.alpha);
  15448. var sina = Math.sin(_this.alpha);
  15449. var cosb = Math.cos(_this.beta);
  15450. var sinb = Math.sin(_this.beta);
  15451. if (sinb === 0) {
  15452. sinb = 0.0001;
  15453. }
  15454. var target = _this._getTargetPosition();
  15455. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15456. _this.position.copyFrom(_this._newPosition);
  15457. var up = _this.upVector;
  15458. if (_this.allowUpsideDown && _this.beta < 0) {
  15459. up = up.clone();
  15460. up = up.negate();
  15461. }
  15462. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15463. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15464. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15465. _this._collisionTriggered = false;
  15466. };
  15467. if (!target) {
  15468. this.target = BABYLON.Vector3.Zero();
  15469. }
  15470. else {
  15471. this.target = target;
  15472. }
  15473. this.alpha = alpha;
  15474. this.beta = beta;
  15475. this.radius = radius;
  15476. this.getViewMatrix();
  15477. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15478. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15479. }
  15480. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15481. //-- begin properties for backward compatibility for inputs
  15482. get: function () {
  15483. var pointers = this.inputs.attached["pointers"];
  15484. if (pointers)
  15485. return pointers.angularSensibilityX;
  15486. },
  15487. set: function (value) {
  15488. var pointers = this.inputs.attached["pointers"];
  15489. if (pointers) {
  15490. pointers.angularSensibilityX = value;
  15491. }
  15492. },
  15493. enumerable: true,
  15494. configurable: true
  15495. });
  15496. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15497. get: function () {
  15498. var pointers = this.inputs.attached["pointers"];
  15499. if (pointers)
  15500. return pointers.angularSensibilityY;
  15501. },
  15502. set: function (value) {
  15503. var pointers = this.inputs.attached["pointers"];
  15504. if (pointers) {
  15505. pointers.angularSensibilityY = value;
  15506. }
  15507. },
  15508. enumerable: true,
  15509. configurable: true
  15510. });
  15511. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15512. get: function () {
  15513. var pointers = this.inputs.attached["pointers"];
  15514. if (pointers)
  15515. return pointers.pinchPrecision;
  15516. },
  15517. set: function (value) {
  15518. var pointers = this.inputs.attached["pointers"];
  15519. if (pointers) {
  15520. pointers.pinchPrecision = value;
  15521. }
  15522. },
  15523. enumerable: true,
  15524. configurable: true
  15525. });
  15526. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15527. get: function () {
  15528. var pointers = this.inputs.attached["pointers"];
  15529. if (pointers)
  15530. return pointers.panningSensibility;
  15531. },
  15532. set: function (value) {
  15533. var pointers = this.inputs.attached["pointers"];
  15534. if (pointers) {
  15535. pointers.panningSensibility = value;
  15536. }
  15537. },
  15538. enumerable: true,
  15539. configurable: true
  15540. });
  15541. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15542. get: function () {
  15543. var keyboard = this.inputs.attached["keyboard"];
  15544. if (keyboard)
  15545. return keyboard.keysUp;
  15546. },
  15547. set: function (value) {
  15548. var keyboard = this.inputs.attached["keyboard"];
  15549. if (keyboard)
  15550. keyboard.keysUp = value;
  15551. },
  15552. enumerable: true,
  15553. configurable: true
  15554. });
  15555. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15556. get: function () {
  15557. var keyboard = this.inputs.attached["keyboard"];
  15558. if (keyboard)
  15559. return keyboard.keysDown;
  15560. },
  15561. set: function (value) {
  15562. var keyboard = this.inputs.attached["keyboard"];
  15563. if (keyboard)
  15564. keyboard.keysDown = value;
  15565. },
  15566. enumerable: true,
  15567. configurable: true
  15568. });
  15569. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15570. get: function () {
  15571. var keyboard = this.inputs.attached["keyboard"];
  15572. if (keyboard)
  15573. return keyboard.keysLeft;
  15574. },
  15575. set: function (value) {
  15576. var keyboard = this.inputs.attached["keyboard"];
  15577. if (keyboard)
  15578. keyboard.keysLeft = value;
  15579. },
  15580. enumerable: true,
  15581. configurable: true
  15582. });
  15583. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15584. get: function () {
  15585. var keyboard = this.inputs.attached["keyboard"];
  15586. if (keyboard)
  15587. return keyboard.keysRight;
  15588. },
  15589. set: function (value) {
  15590. var keyboard = this.inputs.attached["keyboard"];
  15591. if (keyboard)
  15592. keyboard.keysRight = value;
  15593. },
  15594. enumerable: true,
  15595. configurable: true
  15596. });
  15597. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15598. get: function () {
  15599. var mousewheel = this.inputs.attached["mousewheel"];
  15600. if (mousewheel)
  15601. return mousewheel.wheelPrecision;
  15602. },
  15603. set: function (value) {
  15604. var mousewheel = this.inputs.attached["mousewheel"];
  15605. if (mousewheel)
  15606. mousewheel.wheelPrecision = value;
  15607. },
  15608. enumerable: true,
  15609. configurable: true
  15610. });
  15611. // Cache
  15612. ArcRotateCamera.prototype._initCache = function () {
  15613. _super.prototype._initCache.call(this);
  15614. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15615. this._cache.alpha = undefined;
  15616. this._cache.beta = undefined;
  15617. this._cache.radius = undefined;
  15618. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15619. };
  15620. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15621. if (!ignoreParentClass) {
  15622. _super.prototype._updateCache.call(this);
  15623. }
  15624. this._cache.target.copyFrom(this._getTargetPosition());
  15625. this._cache.alpha = this.alpha;
  15626. this._cache.beta = this.beta;
  15627. this._cache.radius = this.radius;
  15628. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15629. };
  15630. ArcRotateCamera.prototype._getTargetPosition = function () {
  15631. if (this.target.getAbsolutePosition) {
  15632. var pos = this.target.getAbsolutePosition();
  15633. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15634. }
  15635. return this.target;
  15636. };
  15637. // Synchronized
  15638. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15639. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15640. return false;
  15641. return this._cache.target.equals(this.target)
  15642. && this._cache.alpha === this.alpha
  15643. && this._cache.beta === this.beta
  15644. && this._cache.radius === this.radius
  15645. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15646. };
  15647. // Methods
  15648. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15649. var _this = this;
  15650. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15651. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15652. this._useCtrlForPanning = useCtrlForPanning;
  15653. this._panningMouseButton = panningMouseButton;
  15654. this.inputs.attachElement(element, noPreventDefault);
  15655. this._reset = function () {
  15656. _this.inertialAlphaOffset = 0;
  15657. _this.inertialBetaOffset = 0;
  15658. _this.inertialRadiusOffset = 0;
  15659. };
  15660. };
  15661. ArcRotateCamera.prototype.detachControl = function (element) {
  15662. this.inputs.detachElement(element);
  15663. if (this._reset) {
  15664. this._reset();
  15665. }
  15666. };
  15667. ArcRotateCamera.prototype._checkInputs = function () {
  15668. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15669. if (this._collisionTriggered) {
  15670. return;
  15671. }
  15672. this.inputs.checkInputs();
  15673. // Inertia
  15674. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15675. if (this.getScene().useRightHandedSystem) {
  15676. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15677. }
  15678. else {
  15679. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15680. }
  15681. this.beta += this.inertialBetaOffset;
  15682. this.radius -= this.inertialRadiusOffset;
  15683. this.inertialAlphaOffset *= this.inertia;
  15684. this.inertialBetaOffset *= this.inertia;
  15685. this.inertialRadiusOffset *= this.inertia;
  15686. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15687. this.inertialAlphaOffset = 0;
  15688. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15689. this.inertialBetaOffset = 0;
  15690. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15691. this.inertialRadiusOffset = 0;
  15692. }
  15693. // Panning inertia
  15694. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15695. if (!this._localDirection) {
  15696. this._localDirection = BABYLON.Vector3.Zero();
  15697. this._transformedDirection = BABYLON.Vector3.Zero();
  15698. }
  15699. this.inertialPanningX *= this.inertia;
  15700. this.inertialPanningY *= this.inertia;
  15701. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15702. this.inertialPanningX = 0;
  15703. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15704. this.inertialPanningY = 0;
  15705. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15706. this._localDirection.multiplyInPlace(this.panningAxis);
  15707. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15708. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15709. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15710. if (!this.panningAxis.y) {
  15711. this._transformedDirection.y = 0;
  15712. }
  15713. if (!this.target.getAbsolutePosition) {
  15714. this.target.addInPlace(this._transformedDirection);
  15715. }
  15716. }
  15717. // Limits
  15718. this._checkLimits();
  15719. _super.prototype._checkInputs.call(this);
  15720. };
  15721. ArcRotateCamera.prototype._checkLimits = function () {
  15722. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15723. if (this.allowUpsideDown && this.beta > Math.PI) {
  15724. this.beta = this.beta - (2 * Math.PI);
  15725. }
  15726. }
  15727. else {
  15728. if (this.beta < this.lowerBetaLimit) {
  15729. this.beta = this.lowerBetaLimit;
  15730. }
  15731. }
  15732. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15733. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15734. this.beta = this.beta + (2 * Math.PI);
  15735. }
  15736. }
  15737. else {
  15738. if (this.beta > this.upperBetaLimit) {
  15739. this.beta = this.upperBetaLimit;
  15740. }
  15741. }
  15742. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15743. this.alpha = this.lowerAlphaLimit;
  15744. }
  15745. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15746. this.alpha = this.upperAlphaLimit;
  15747. }
  15748. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15749. this.radius = this.lowerRadiusLimit;
  15750. }
  15751. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15752. this.radius = this.upperRadiusLimit;
  15753. }
  15754. };
  15755. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15756. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15757. this.radius = radiusv3.length();
  15758. // Alpha
  15759. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15760. if (radiusv3.z < 0) {
  15761. this.alpha = 2 * Math.PI - this.alpha;
  15762. }
  15763. // Beta
  15764. this.beta = Math.acos(radiusv3.y / this.radius);
  15765. this._checkLimits();
  15766. };
  15767. ArcRotateCamera.prototype.setPosition = function (position) {
  15768. if (this.position.equals(position)) {
  15769. return;
  15770. }
  15771. this.position.copyFrom(position);
  15772. this.rebuildAnglesAndRadius();
  15773. };
  15774. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15775. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15776. if (this._getTargetPosition().equals(target)) {
  15777. return;
  15778. }
  15779. if (toBoundingCenter && target.getBoundingInfo) {
  15780. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15781. }
  15782. else {
  15783. this._targetBoundingCenter = null;
  15784. }
  15785. this.target = target;
  15786. this.rebuildAnglesAndRadius();
  15787. };
  15788. ArcRotateCamera.prototype._getViewMatrix = function () {
  15789. // Compute
  15790. var cosa = Math.cos(this.alpha);
  15791. var sina = Math.sin(this.alpha);
  15792. var cosb = Math.cos(this.beta);
  15793. var sinb = Math.sin(this.beta);
  15794. if (sinb === 0) {
  15795. sinb = 0.0001;
  15796. }
  15797. var target = this._getTargetPosition();
  15798. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15799. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15800. this._collider.radius = this.collisionRadius;
  15801. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15802. this._collisionTriggered = true;
  15803. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15804. }
  15805. else {
  15806. this.position.copyFrom(this._newPosition);
  15807. var up = this.upVector;
  15808. if (this.allowUpsideDown && this.beta < 0) {
  15809. up = up.clone();
  15810. up = up.negate();
  15811. }
  15812. if (this.getScene().useRightHandedSystem) {
  15813. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15814. }
  15815. else {
  15816. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15817. }
  15818. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15819. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15820. }
  15821. this._currentTarget = target;
  15822. return this._viewMatrix;
  15823. };
  15824. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15825. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15826. meshes = meshes || this.getScene().meshes;
  15827. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15828. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15829. this.radius = distance * this.zoomOnFactor;
  15830. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15831. };
  15832. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15833. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15834. var meshesOrMinMaxVector;
  15835. var distance;
  15836. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15837. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15838. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15839. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15840. }
  15841. else {
  15842. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15843. distance = meshesOrMinMaxVectorAndDistance.distance;
  15844. }
  15845. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15846. if (!doNotUpdateMaxZ) {
  15847. this.maxZ = distance * 2;
  15848. }
  15849. };
  15850. /**
  15851. * @override
  15852. * Override Camera.createRigCamera
  15853. */
  15854. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15855. var alphaShift;
  15856. switch (this.cameraRigMode) {
  15857. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15858. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15859. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15860. case BABYLON.Camera.RIG_MODE_VR:
  15861. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15862. break;
  15863. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15864. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15865. break;
  15866. }
  15867. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15868. rigCam._cameraRigParams = {};
  15869. return rigCam;
  15870. };
  15871. /**
  15872. * @override
  15873. * Override Camera._updateRigCameras
  15874. */
  15875. ArcRotateCamera.prototype._updateRigCameras = function () {
  15876. var camLeft = this._rigCameras[0];
  15877. var camRight = this._rigCameras[1];
  15878. camLeft.beta = camRight.beta = this.beta;
  15879. camLeft.radius = camRight.radius = this.radius;
  15880. switch (this.cameraRigMode) {
  15881. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15882. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15883. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15884. case BABYLON.Camera.RIG_MODE_VR:
  15885. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15886. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15887. break;
  15888. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15889. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15890. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15891. break;
  15892. }
  15893. _super.prototype._updateRigCameras.call(this);
  15894. };
  15895. ArcRotateCamera.prototype.dispose = function () {
  15896. this.inputs.clear();
  15897. _super.prototype.dispose.call(this);
  15898. };
  15899. ArcRotateCamera.prototype.getTypeName = function () {
  15900. return "ArcRotateCamera";
  15901. };
  15902. __decorate([
  15903. BABYLON.serialize()
  15904. ], ArcRotateCamera.prototype, "alpha", void 0);
  15905. __decorate([
  15906. BABYLON.serialize()
  15907. ], ArcRotateCamera.prototype, "beta", void 0);
  15908. __decorate([
  15909. BABYLON.serialize()
  15910. ], ArcRotateCamera.prototype, "radius", void 0);
  15911. __decorate([
  15912. BABYLON.serializeAsVector3()
  15913. ], ArcRotateCamera.prototype, "target", void 0);
  15914. __decorate([
  15915. BABYLON.serialize()
  15916. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15917. __decorate([
  15918. BABYLON.serialize()
  15919. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15920. __decorate([
  15921. BABYLON.serialize()
  15922. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15923. __decorate([
  15924. BABYLON.serialize()
  15925. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15926. __decorate([
  15927. BABYLON.serialize()
  15928. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15929. __decorate([
  15930. BABYLON.serialize()
  15931. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15932. __decorate([
  15933. BABYLON.serialize()
  15934. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15935. __decorate([
  15936. BABYLON.serialize()
  15937. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15938. __decorate([
  15939. BABYLON.serialize()
  15940. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15941. __decorate([
  15942. BABYLON.serialize()
  15943. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15944. __decorate([
  15945. BABYLON.serialize()
  15946. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15947. __decorate([
  15948. BABYLON.serialize()
  15949. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15950. __decorate([
  15951. BABYLON.serialize()
  15952. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15953. return ArcRotateCamera;
  15954. }(BABYLON.TargetCamera));
  15955. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15956. })(BABYLON || (BABYLON = {}));
  15957. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  15958. var BABYLON;
  15959. (function (BABYLON) {
  15960. var ArcRotateCameraInputsManager = (function (_super) {
  15961. __extends(ArcRotateCameraInputsManager, _super);
  15962. function ArcRotateCameraInputsManager(camera) {
  15963. _super.call(this, camera);
  15964. }
  15965. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15966. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15967. return this;
  15968. };
  15969. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15970. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15971. return this;
  15972. };
  15973. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15974. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15975. return this;
  15976. };
  15977. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15978. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15979. return this;
  15980. };
  15981. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15982. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15983. return this;
  15984. };
  15985. return ArcRotateCameraInputsManager;
  15986. }(BABYLON.CameraInputsManager));
  15987. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15988. })(BABYLON || (BABYLON = {}));
  15989. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  15990. var BABYLON;
  15991. (function (BABYLON) {
  15992. var RenderingManager = (function () {
  15993. function RenderingManager(scene) {
  15994. this._renderingGroups = new Array();
  15995. this._autoClearDepthStencil = {};
  15996. this._customOpaqueSortCompareFn = {};
  15997. this._customAlphaTestSortCompareFn = {};
  15998. this._customTransparentSortCompareFn = {};
  15999. this._renderinGroupInfo = null;
  16000. this._scene = scene;
  16001. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16002. this._autoClearDepthStencil[i] = true;
  16003. }
  16004. }
  16005. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  16006. if (this._scene._activeParticleSystems.length === 0) {
  16007. return;
  16008. }
  16009. // Particles
  16010. var activeCamera = this._scene.activeCamera;
  16011. this._scene._particlesDuration.beginMonitoring();
  16012. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16013. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16014. if (particleSystem.renderingGroupId !== index) {
  16015. continue;
  16016. }
  16017. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16018. continue;
  16019. }
  16020. this._clearDepthStencilBuffer();
  16021. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  16022. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16023. }
  16024. }
  16025. this._scene._particlesDuration.endMonitoring(false);
  16026. };
  16027. RenderingManager.prototype._renderSprites = function (index) {
  16028. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  16029. return;
  16030. }
  16031. // Sprites
  16032. var activeCamera = this._scene.activeCamera;
  16033. this._scene._spritesDuration.beginMonitoring();
  16034. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  16035. var spriteManager = this._scene.spriteManagers[id];
  16036. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16037. this._clearDepthStencilBuffer();
  16038. spriteManager.render();
  16039. }
  16040. }
  16041. this._scene._spritesDuration.endMonitoring(false);
  16042. };
  16043. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  16044. if (this._depthStencilBufferAlreadyCleaned) {
  16045. return;
  16046. }
  16047. this._scene.getEngine().clear(0, false, true, true);
  16048. this._depthStencilBufferAlreadyCleaned = true;
  16049. };
  16050. RenderingManager.prototype._renderSpritesAndParticles = function () {
  16051. if (this._currentRenderSprites) {
  16052. this._renderSprites(this._currentIndex);
  16053. }
  16054. if (this._currentRenderParticles) {
  16055. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  16056. }
  16057. };
  16058. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16059. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16060. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16061. var info = null;
  16062. if (observable) {
  16063. if (!this._renderinGroupInfo) {
  16064. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16065. }
  16066. info = this._renderinGroupInfo;
  16067. info.scene = this._scene;
  16068. info.camera = this._scene.activeCamera;
  16069. }
  16070. this._currentActiveMeshes = activeMeshes;
  16071. this._currentRenderParticles = renderParticles;
  16072. this._currentRenderSprites = renderSprites;
  16073. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16074. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16075. var renderingGroup = this._renderingGroups[index];
  16076. var needToStepBack = false;
  16077. this._currentIndex = index;
  16078. if (renderingGroup) {
  16079. var renderingGroupMask = 0;
  16080. // Fire PRECLEAR stage
  16081. if (observable) {
  16082. renderingGroupMask = Math.pow(2, index);
  16083. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16084. info.renderingGroupId = index;
  16085. observable.notifyObservers(info, renderingGroupMask);
  16086. }
  16087. // Clear depth/stencil if needed
  16088. if (this._autoClearDepthStencil[index]) {
  16089. this._clearDepthStencilBuffer();
  16090. }
  16091. // Fire PREOPAQUE stage
  16092. if (observable) {
  16093. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16094. observable.notifyObservers(info, renderingGroupMask);
  16095. }
  16096. if (!renderingGroup.onBeforeTransparentRendering) {
  16097. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  16098. }
  16099. // Fire PRETRANSPARENT stage
  16100. if (observable) {
  16101. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16102. observable.notifyObservers(info, renderingGroupMask);
  16103. }
  16104. if (!renderingGroup.render(customRenderFunction)) {
  16105. this._renderingGroups.splice(index, 1);
  16106. needToStepBack = true;
  16107. this._renderSpritesAndParticles();
  16108. }
  16109. // Fire POSTTRANSPARENT stage
  16110. if (observable) {
  16111. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16112. observable.notifyObservers(info, renderingGroupMask);
  16113. }
  16114. }
  16115. else {
  16116. this._renderSpritesAndParticles();
  16117. if (observable) {
  16118. var renderingGroupMask = Math.pow(2, index);
  16119. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16120. info.renderingGroupId = index;
  16121. observable.notifyObservers(info, renderingGroupMask);
  16122. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16123. observable.notifyObservers(info, renderingGroupMask);
  16124. }
  16125. }
  16126. if (needToStepBack) {
  16127. index--;
  16128. }
  16129. }
  16130. };
  16131. RenderingManager.prototype.reset = function () {
  16132. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16133. var renderingGroup = this._renderingGroups[index];
  16134. if (renderingGroup) {
  16135. renderingGroup.prepare();
  16136. }
  16137. }
  16138. };
  16139. RenderingManager.prototype.dispatch = function (subMesh) {
  16140. var mesh = subMesh.getMesh();
  16141. var renderingGroupId = mesh.renderingGroupId || 0;
  16142. if (!this._renderingGroups[renderingGroupId]) {
  16143. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16144. }
  16145. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16146. };
  16147. /**
  16148. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16149. * This allowed control for front to back rendering or reversly depending of the special needs.
  16150. *
  16151. * @param renderingGroupId The rendering group id corresponding to its index
  16152. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16153. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16154. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16155. */
  16156. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16157. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16158. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16159. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16160. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16161. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16162. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16163. if (this._renderingGroups[renderingGroupId]) {
  16164. var group = this._renderingGroups[renderingGroupId];
  16165. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16166. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16167. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16168. }
  16169. };
  16170. /**
  16171. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16172. *
  16173. * @param renderingGroupId The rendering group id corresponding to its index
  16174. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16175. */
  16176. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  16177. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  16178. };
  16179. /**
  16180. * The max id used for rendering groups (not included)
  16181. */
  16182. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16183. /**
  16184. * The min id used for rendering groups (included)
  16185. */
  16186. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16187. return RenderingManager;
  16188. }());
  16189. BABYLON.RenderingManager = RenderingManager;
  16190. })(BABYLON || (BABYLON = {}));
  16191. //# sourceMappingURL=babylon.renderingManager.js.map
  16192. var BABYLON;
  16193. (function (BABYLON) {
  16194. var RenderingGroup = (function () {
  16195. /**
  16196. * Creates a new rendering group.
  16197. * @param index The rendering group index
  16198. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16199. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16200. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16201. */
  16202. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16203. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16204. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16205. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16206. this.index = index;
  16207. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16208. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16209. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16210. this._scene = scene;
  16211. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16212. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16213. this.transparentSortCompareFn = transparentSortCompareFn;
  16214. }
  16215. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16216. /**
  16217. * Set the opaque sort comparison function.
  16218. * If null the sub meshes will be render in the order they were created
  16219. */
  16220. set: function (value) {
  16221. this._opaqueSortCompareFn = value;
  16222. if (value) {
  16223. this._renderOpaque = this.renderOpaqueSorted;
  16224. }
  16225. else {
  16226. this._renderOpaque = RenderingGroup.renderUnsorted;
  16227. }
  16228. },
  16229. enumerable: true,
  16230. configurable: true
  16231. });
  16232. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16233. /**
  16234. * Set the alpha test sort comparison function.
  16235. * If null the sub meshes will be render in the order they were created
  16236. */
  16237. set: function (value) {
  16238. this._alphaTestSortCompareFn = value;
  16239. if (value) {
  16240. this._renderAlphaTest = this.renderAlphaTestSorted;
  16241. }
  16242. else {
  16243. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16244. }
  16245. },
  16246. enumerable: true,
  16247. configurable: true
  16248. });
  16249. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16250. /**
  16251. * Set the transparent sort comparison function.
  16252. * If null the sub meshes will be render in the order they were created
  16253. */
  16254. set: function (value) {
  16255. if (value) {
  16256. this._transparentSortCompareFn = value;
  16257. }
  16258. else {
  16259. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16260. }
  16261. this._renderTransparent = this.renderTransparentSorted;
  16262. },
  16263. enumerable: true,
  16264. configurable: true
  16265. });
  16266. /**
  16267. * Render all the sub meshes contained in the group.
  16268. * @param customRenderFunction Used to override the default render behaviour of the group.
  16269. * @returns true if rendered some submeshes.
  16270. */
  16271. RenderingGroup.prototype.render = function (customRenderFunction) {
  16272. if (customRenderFunction) {
  16273. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16274. return true;
  16275. }
  16276. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  16277. if (this.onBeforeTransparentRendering) {
  16278. this.onBeforeTransparentRendering();
  16279. }
  16280. return false;
  16281. }
  16282. var engine = this._scene.getEngine();
  16283. // Opaque
  16284. this._renderOpaque(this._opaqueSubMeshes);
  16285. // Alpha test
  16286. engine.setAlphaTesting(true);
  16287. this._renderAlphaTest(this._alphaTestSubMeshes);
  16288. engine.setAlphaTesting(false);
  16289. if (this.onBeforeTransparentRendering) {
  16290. this.onBeforeTransparentRendering();
  16291. }
  16292. // Transparent
  16293. this._renderTransparent(this._transparentSubMeshes);
  16294. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16295. return true;
  16296. };
  16297. /**
  16298. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16299. * @param subMeshes The submeshes to render
  16300. */
  16301. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16302. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16303. };
  16304. /**
  16305. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16306. * @param subMeshes The submeshes to render
  16307. */
  16308. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16309. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16310. };
  16311. /**
  16312. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16313. * @param subMeshes The submeshes to render
  16314. */
  16315. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16316. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16317. };
  16318. /**
  16319. * Renders the submeshes in a specified order.
  16320. * @param subMeshes The submeshes to sort before render
  16321. * @param sortCompareFn The comparison function use to sort
  16322. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16323. * @param transparent Specifies to activate blending if true
  16324. */
  16325. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16326. var subIndex = 0;
  16327. var subMesh;
  16328. for (; subIndex < subMeshes.length; subIndex++) {
  16329. subMesh = subMeshes.data[subIndex];
  16330. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16331. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16332. }
  16333. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16334. sortedArray.sort(sortCompareFn);
  16335. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16336. subMesh = sortedArray[subIndex];
  16337. subMesh.render(transparent);
  16338. }
  16339. };
  16340. /**
  16341. * Renders the submeshes in the order they were dispatched (no sort applied).
  16342. * @param subMeshes The submeshes to render
  16343. */
  16344. RenderingGroup.renderUnsorted = function (subMeshes) {
  16345. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16346. var submesh = subMeshes.data[subIndex];
  16347. submesh.render(false);
  16348. }
  16349. };
  16350. /**
  16351. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16352. * are rendered back to front if in the same alpha index.
  16353. *
  16354. * @param a The first submesh
  16355. * @param b The second submesh
  16356. * @returns The result of the comparison
  16357. */
  16358. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16359. // Alpha index first
  16360. if (a._alphaIndex > b._alphaIndex) {
  16361. return 1;
  16362. }
  16363. if (a._alphaIndex < b._alphaIndex) {
  16364. return -1;
  16365. }
  16366. // Then distance to camera
  16367. return RenderingGroup.backToFrontSortCompare(a, b);
  16368. };
  16369. /**
  16370. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16371. * are rendered back to front.
  16372. *
  16373. * @param a The first submesh
  16374. * @param b The second submesh
  16375. * @returns The result of the comparison
  16376. */
  16377. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16378. // Then distance to camera
  16379. if (a._distanceToCamera < b._distanceToCamera) {
  16380. return 1;
  16381. }
  16382. if (a._distanceToCamera > b._distanceToCamera) {
  16383. return -1;
  16384. }
  16385. return 0;
  16386. };
  16387. /**
  16388. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16389. * are rendered front to back (prevent overdraw).
  16390. *
  16391. * @param a The first submesh
  16392. * @param b The second submesh
  16393. * @returns The result of the comparison
  16394. */
  16395. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16396. // Then distance to camera
  16397. if (a._distanceToCamera < b._distanceToCamera) {
  16398. return -1;
  16399. }
  16400. if (a._distanceToCamera > b._distanceToCamera) {
  16401. return 1;
  16402. }
  16403. return 0;
  16404. };
  16405. /**
  16406. * Resets the different lists of submeshes to prepare a new frame.
  16407. */
  16408. RenderingGroup.prototype.prepare = function () {
  16409. this._opaqueSubMeshes.reset();
  16410. this._transparentSubMeshes.reset();
  16411. this._alphaTestSubMeshes.reset();
  16412. };
  16413. /**
  16414. * Inserts the submesh in its correct queue depending on its material.
  16415. * @param subMesh The submesh to dispatch
  16416. */
  16417. RenderingGroup.prototype.dispatch = function (subMesh) {
  16418. var material = subMesh.getMaterial();
  16419. var mesh = subMesh.getMesh();
  16420. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16421. this._transparentSubMeshes.push(subMesh);
  16422. }
  16423. else if (material.needAlphaTesting()) {
  16424. this._alphaTestSubMeshes.push(subMesh);
  16425. }
  16426. else {
  16427. this._opaqueSubMeshes.push(subMesh); // Opaque
  16428. }
  16429. };
  16430. return RenderingGroup;
  16431. }());
  16432. BABYLON.RenderingGroup = RenderingGroup;
  16433. })(BABYLON || (BABYLON = {}));
  16434. //# sourceMappingURL=babylon.renderingGroup.js.map
  16435. var BABYLON;
  16436. (function (BABYLON) {
  16437. var PointerEventTypes = (function () {
  16438. function PointerEventTypes() {
  16439. }
  16440. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16441. get: function () {
  16442. return PointerEventTypes._POINTERDOWN;
  16443. },
  16444. enumerable: true,
  16445. configurable: true
  16446. });
  16447. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16448. get: function () {
  16449. return PointerEventTypes._POINTERUP;
  16450. },
  16451. enumerable: true,
  16452. configurable: true
  16453. });
  16454. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16455. get: function () {
  16456. return PointerEventTypes._POINTERMOVE;
  16457. },
  16458. enumerable: true,
  16459. configurable: true
  16460. });
  16461. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16462. get: function () {
  16463. return PointerEventTypes._POINTERWHEEL;
  16464. },
  16465. enumerable: true,
  16466. configurable: true
  16467. });
  16468. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16469. get: function () {
  16470. return PointerEventTypes._POINTERPICK;
  16471. },
  16472. enumerable: true,
  16473. configurable: true
  16474. });
  16475. PointerEventTypes._POINTERDOWN = 0x01;
  16476. PointerEventTypes._POINTERUP = 0x02;
  16477. PointerEventTypes._POINTERMOVE = 0x04;
  16478. PointerEventTypes._POINTERWHEEL = 0x08;
  16479. PointerEventTypes._POINTERPICK = 0x10;
  16480. return PointerEventTypes;
  16481. }());
  16482. BABYLON.PointerEventTypes = PointerEventTypes;
  16483. var PointerInfoBase = (function () {
  16484. function PointerInfoBase(type, event) {
  16485. this.type = type;
  16486. this.event = event;
  16487. }
  16488. return PointerInfoBase;
  16489. }());
  16490. BABYLON.PointerInfoBase = PointerInfoBase;
  16491. /**
  16492. * This class is used to store pointer related info for the onPrePointerObservable event.
  16493. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16494. */
  16495. var PointerInfoPre = (function (_super) {
  16496. __extends(PointerInfoPre, _super);
  16497. function PointerInfoPre(type, event, localX, localY) {
  16498. _super.call(this, type, event);
  16499. this.skipOnPointerObservable = false;
  16500. this.localPosition = new BABYLON.Vector2(localX, localY);
  16501. }
  16502. return PointerInfoPre;
  16503. }(PointerInfoBase));
  16504. BABYLON.PointerInfoPre = PointerInfoPre;
  16505. /**
  16506. * This type contains all the data related to a pointer event in Babylon.js.
  16507. * 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.
  16508. */
  16509. var PointerInfo = (function (_super) {
  16510. __extends(PointerInfo, _super);
  16511. function PointerInfo(type, event, pickInfo) {
  16512. _super.call(this, type, event);
  16513. this.pickInfo = pickInfo;
  16514. }
  16515. return PointerInfo;
  16516. }(PointerInfoBase));
  16517. BABYLON.PointerInfo = PointerInfo;
  16518. /**
  16519. * This class is used by the onRenderingGroupObservable
  16520. */
  16521. var RenderingGroupInfo = (function () {
  16522. function RenderingGroupInfo() {
  16523. }
  16524. /**
  16525. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16526. * This stage will be fired no matter what
  16527. */
  16528. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16529. /**
  16530. * Called before opaque object are rendered.
  16531. * This stage will be fired only if there's 3D Opaque content to render
  16532. */
  16533. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16534. /**
  16535. * Called after the opaque objects are rendered and before the transparent ones
  16536. * This stage will be fired only if there's 3D transparent content to render
  16537. */
  16538. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16539. /**
  16540. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16541. * This stage will be fired no matter what
  16542. */
  16543. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16544. return RenderingGroupInfo;
  16545. }());
  16546. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16547. /**
  16548. * Represents a scene to be rendered by the engine.
  16549. * @see http://doc.babylonjs.com/page.php?p=21911
  16550. */
  16551. var Scene = (function () {
  16552. /**
  16553. * @constructor
  16554. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16555. */
  16556. function Scene(engine) {
  16557. // Members
  16558. this.autoClear = true;
  16559. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16560. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16561. this.forceWireframe = false;
  16562. this.forcePointsCloud = false;
  16563. this.forceShowBoundingBoxes = false;
  16564. this.animationsEnabled = true;
  16565. this.constantlyUpdateMeshUnderPointer = false;
  16566. this.useRightHandedSystem = false;
  16567. this.hoverCursor = "pointer";
  16568. // Metadata
  16569. this.metadata = null;
  16570. // Events
  16571. /**
  16572. * An event triggered when the scene is disposed.
  16573. * @type {BABYLON.Observable}
  16574. */
  16575. this.onDisposeObservable = new BABYLON.Observable();
  16576. /**
  16577. * An event triggered before rendering the scene
  16578. * @type {BABYLON.Observable}
  16579. */
  16580. this.onBeforeRenderObservable = new BABYLON.Observable();
  16581. /**
  16582. * An event triggered after rendering the scene
  16583. * @type {BABYLON.Observable}
  16584. */
  16585. this.onAfterRenderObservable = new BABYLON.Observable();
  16586. /**
  16587. * An event triggered when the scene is ready
  16588. * @type {BABYLON.Observable}
  16589. */
  16590. this.onReadyObservable = new BABYLON.Observable();
  16591. /**
  16592. * An event triggered before rendering a camera
  16593. * @type {BABYLON.Observable}
  16594. */
  16595. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16596. /**
  16597. * An event triggered after rendering a camera
  16598. * @type {BABYLON.Observable}
  16599. */
  16600. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16601. /**
  16602. * An event triggered when a camera is created
  16603. * @type {BABYLON.Observable}
  16604. */
  16605. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16606. /**
  16607. * An event triggered when a camera is removed
  16608. * @type {BABYLON.Observable}
  16609. */
  16610. this.onCameraRemovedObservable = new BABYLON.Observable();
  16611. /**
  16612. * An event triggered when a light is created
  16613. * @type {BABYLON.Observable}
  16614. */
  16615. this.onNewLightAddedObservable = new BABYLON.Observable();
  16616. /**
  16617. * An event triggered when a light is removed
  16618. * @type {BABYLON.Observable}
  16619. */
  16620. this.onLightRemovedObservable = new BABYLON.Observable();
  16621. /**
  16622. * An event triggered when a geometry is created
  16623. * @type {BABYLON.Observable}
  16624. */
  16625. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16626. /**
  16627. * An event triggered when a geometry is removed
  16628. * @type {BABYLON.Observable}
  16629. */
  16630. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16631. /**
  16632. * An event triggered when a mesh is created
  16633. * @type {BABYLON.Observable}
  16634. */
  16635. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16636. /**
  16637. * An event triggered when a mesh is removed
  16638. * @type {BABYLON.Observable}
  16639. */
  16640. this.onMeshRemovedObservable = new BABYLON.Observable();
  16641. /**
  16642. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16643. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16644. * 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)
  16645. */
  16646. this.onRenderingGroupObservable = new BABYLON.Observable();
  16647. // Animations
  16648. this.animations = [];
  16649. /**
  16650. * 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).
  16651. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16652. */
  16653. this.onPrePointerObservable = new BABYLON.Observable();
  16654. /**
  16655. * Observable event triggered each time an input event is received from the rendering canvas
  16656. */
  16657. this.onPointerObservable = new BABYLON.Observable();
  16658. 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
  16659. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16660. this._startingPointerTime = 0;
  16661. // Fog
  16662. /**
  16663. * is fog enabled on this scene.
  16664. * @type {boolean}
  16665. */
  16666. this.fogEnabled = true;
  16667. this.fogMode = Scene.FOGMODE_NONE;
  16668. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16669. this.fogDensity = 0.1;
  16670. this.fogStart = 0;
  16671. this.fogEnd = 1000.0;
  16672. // Lights
  16673. /**
  16674. * is shadow enabled on this scene.
  16675. * @type {boolean}
  16676. */
  16677. this.shadowsEnabled = true;
  16678. /**
  16679. * is light enabled on this scene.
  16680. * @type {boolean}
  16681. */
  16682. this.lightsEnabled = true;
  16683. /**
  16684. * All of the lights added to this scene.
  16685. * @see BABYLON.Light
  16686. * @type {BABYLON.Light[]}
  16687. */
  16688. this.lights = new Array();
  16689. // Cameras
  16690. /**
  16691. * All of the cameras added to this scene.
  16692. * @see BABYLON.Camera
  16693. * @type {BABYLON.Camera[]}
  16694. */
  16695. this.cameras = new Array();
  16696. this.activeCameras = new Array();
  16697. // Meshes
  16698. /**
  16699. * All of the (abstract) meshes added to this scene.
  16700. * @see BABYLON.AbstractMesh
  16701. * @type {BABYLON.AbstractMesh[]}
  16702. */
  16703. this.meshes = new Array();
  16704. // Geometries
  16705. this._geometries = new Array();
  16706. this.materials = new Array();
  16707. this.multiMaterials = new Array();
  16708. // Textures
  16709. this.texturesEnabled = true;
  16710. this.textures = new Array();
  16711. // Particles
  16712. this.particlesEnabled = true;
  16713. this.particleSystems = new Array();
  16714. // Sprites
  16715. this.spritesEnabled = true;
  16716. this.spriteManagers = new Array();
  16717. // Layers
  16718. this.layers = new Array();
  16719. this.highlightLayers = new Array();
  16720. // Skeletons
  16721. this.skeletonsEnabled = true;
  16722. this.skeletons = new Array();
  16723. // Lens flares
  16724. this.lensFlaresEnabled = true;
  16725. this.lensFlareSystems = new Array();
  16726. // Collisions
  16727. this.collisionsEnabled = true;
  16728. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16729. // Postprocesses
  16730. this.postProcessesEnabled = true;
  16731. // Customs render targets
  16732. this.renderTargetsEnabled = true;
  16733. this.dumpNextRenderTargets = false;
  16734. this.customRenderTargets = new Array();
  16735. // Imported meshes
  16736. this.importedMeshesFiles = new Array();
  16737. // Probes
  16738. this.probesEnabled = true;
  16739. this.reflectionProbes = new Array();
  16740. this._actionManagers = new Array();
  16741. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16742. // Procedural textures
  16743. this.proceduralTexturesEnabled = true;
  16744. this._proceduralTextures = new Array();
  16745. this.soundTracks = new Array();
  16746. this._audioEnabled = true;
  16747. this._headphone = false;
  16748. // Performance counters
  16749. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16750. this._totalLightsCounter = new BABYLON.PerfCounter();
  16751. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16752. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16753. this._totalVertices = new BABYLON.PerfCounter();
  16754. this._activeIndices = new BABYLON.PerfCounter();
  16755. this._activeParticles = new BABYLON.PerfCounter();
  16756. this._lastFrameDuration = new BABYLON.PerfCounter();
  16757. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16758. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16759. this._particlesDuration = new BABYLON.PerfCounter();
  16760. this._renderDuration = new BABYLON.PerfCounter();
  16761. this._spritesDuration = new BABYLON.PerfCounter();
  16762. this._activeBones = new BABYLON.PerfCounter();
  16763. this._renderId = 0;
  16764. this._executeWhenReadyTimeoutId = -1;
  16765. this._intermediateRendering = false;
  16766. this._toBeDisposed = new BABYLON.SmartArray(256);
  16767. this._pendingData = []; //ANY
  16768. this._activeMeshes = new BABYLON.SmartArray(256);
  16769. this._processedMaterials = new BABYLON.SmartArray(256);
  16770. this._renderTargets = new BABYLON.SmartArray(256);
  16771. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16772. this._activeSkeletons = new BABYLON.SmartArray(32);
  16773. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16774. this._activeAnimatables = new Array();
  16775. this._transformMatrix = BABYLON.Matrix.Zero();
  16776. this._edgesRenderers = new BABYLON.SmartArray(16);
  16777. this._uniqueIdCounter = 0;
  16778. this._engine = engine;
  16779. engine.scenes.push(this);
  16780. this._externalData = new BABYLON.StringDictionary();
  16781. this._uid = null;
  16782. this._renderingManager = new BABYLON.RenderingManager(this);
  16783. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16784. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16785. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16786. if (BABYLON.OutlineRenderer) {
  16787. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16788. }
  16789. this.attachControl();
  16790. if (BABYLON.SoundTrack) {
  16791. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16792. }
  16793. //simplification queue
  16794. if (BABYLON.SimplificationQueue) {
  16795. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16796. }
  16797. //collision coordinator initialization. For now legacy per default.
  16798. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16799. }
  16800. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16801. get: function () {
  16802. return Scene._FOGMODE_NONE;
  16803. },
  16804. enumerable: true,
  16805. configurable: true
  16806. });
  16807. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16808. get: function () {
  16809. return Scene._FOGMODE_EXP;
  16810. },
  16811. enumerable: true,
  16812. configurable: true
  16813. });
  16814. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16815. get: function () {
  16816. return Scene._FOGMODE_EXP2;
  16817. },
  16818. enumerable: true,
  16819. configurable: true
  16820. });
  16821. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16822. get: function () {
  16823. return Scene._FOGMODE_LINEAR;
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. Object.defineProperty(Scene.prototype, "onDispose", {
  16829. set: function (callback) {
  16830. if (this._onDisposeObserver) {
  16831. this.onDisposeObservable.remove(this._onDisposeObserver);
  16832. }
  16833. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16834. },
  16835. enumerable: true,
  16836. configurable: true
  16837. });
  16838. Object.defineProperty(Scene.prototype, "beforeRender", {
  16839. set: function (callback) {
  16840. if (this._onBeforeRenderObserver) {
  16841. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16842. }
  16843. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16844. },
  16845. enumerable: true,
  16846. configurable: true
  16847. });
  16848. Object.defineProperty(Scene.prototype, "afterRender", {
  16849. set: function (callback) {
  16850. if (this._onAfterRenderObserver) {
  16851. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16852. }
  16853. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16854. },
  16855. enumerable: true,
  16856. configurable: true
  16857. });
  16858. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16859. set: function (callback) {
  16860. if (this._onBeforeCameraRenderObserver) {
  16861. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16862. }
  16863. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16864. },
  16865. enumerable: true,
  16866. configurable: true
  16867. });
  16868. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16869. set: function (callback) {
  16870. if (this._onAfterCameraRenderObserver) {
  16871. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16872. }
  16873. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16874. },
  16875. enumerable: true,
  16876. configurable: true
  16877. });
  16878. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16879. get: function () {
  16880. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16881. },
  16882. enumerable: true,
  16883. configurable: true
  16884. });
  16885. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16886. get: function () {
  16887. if (!this._defaultMaterial) {
  16888. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16889. }
  16890. return this._defaultMaterial;
  16891. },
  16892. enumerable: true,
  16893. configurable: true
  16894. });
  16895. Object.defineProperty(Scene.prototype, "debugLayer", {
  16896. // Properties
  16897. get: function () {
  16898. if (!this._debugLayer) {
  16899. this._debugLayer = new BABYLON.DebugLayer(this);
  16900. }
  16901. return this._debugLayer;
  16902. },
  16903. enumerable: true,
  16904. configurable: true
  16905. });
  16906. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16907. get: function () {
  16908. return this._workerCollisions;
  16909. },
  16910. set: function (enabled) {
  16911. enabled = (enabled && !!Worker);
  16912. this._workerCollisions = enabled;
  16913. if (this.collisionCoordinator) {
  16914. this.collisionCoordinator.destroy();
  16915. }
  16916. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16917. this.collisionCoordinator.init(this);
  16918. },
  16919. enumerable: true,
  16920. configurable: true
  16921. });
  16922. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16923. get: function () {
  16924. return this._selectionOctree;
  16925. },
  16926. enumerable: true,
  16927. configurable: true
  16928. });
  16929. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16930. /**
  16931. * The mesh that is currently under the pointer.
  16932. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16933. */
  16934. get: function () {
  16935. return this._pointerOverMesh;
  16936. },
  16937. enumerable: true,
  16938. configurable: true
  16939. });
  16940. Object.defineProperty(Scene.prototype, "pointerX", {
  16941. /**
  16942. * Current on-screen X position of the pointer
  16943. * @return {number} X position of the pointer
  16944. */
  16945. get: function () {
  16946. return this._pointerX;
  16947. },
  16948. enumerable: true,
  16949. configurable: true
  16950. });
  16951. Object.defineProperty(Scene.prototype, "pointerY", {
  16952. /**
  16953. * Current on-screen Y position of the pointer
  16954. * @return {number} Y position of the pointer
  16955. */
  16956. get: function () {
  16957. return this._pointerY;
  16958. },
  16959. enumerable: true,
  16960. configurable: true
  16961. });
  16962. Scene.prototype.getCachedMaterial = function () {
  16963. return this._cachedMaterial;
  16964. };
  16965. Scene.prototype.getBoundingBoxRenderer = function () {
  16966. return this._boundingBoxRenderer;
  16967. };
  16968. Scene.prototype.getOutlineRenderer = function () {
  16969. return this._outlineRenderer;
  16970. };
  16971. Scene.prototype.getEngine = function () {
  16972. return this._engine;
  16973. };
  16974. Scene.prototype.getTotalVertices = function () {
  16975. return this._totalVertices.current;
  16976. };
  16977. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16978. get: function () {
  16979. return this._totalVertices;
  16980. },
  16981. enumerable: true,
  16982. configurable: true
  16983. });
  16984. Scene.prototype.getActiveIndices = function () {
  16985. return this._activeIndices.current;
  16986. };
  16987. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16988. get: function () {
  16989. return this._activeIndices;
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Scene.prototype.getActiveParticles = function () {
  16995. return this._activeParticles.current;
  16996. };
  16997. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16998. get: function () {
  16999. return this._activeParticles;
  17000. },
  17001. enumerable: true,
  17002. configurable: true
  17003. });
  17004. Scene.prototype.getActiveBones = function () {
  17005. return this._activeBones.current;
  17006. };
  17007. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17008. get: function () {
  17009. return this._activeBones;
  17010. },
  17011. enumerable: true,
  17012. configurable: true
  17013. });
  17014. // Stats
  17015. Scene.prototype.getLastFrameDuration = function () {
  17016. return this._lastFrameDuration.current;
  17017. };
  17018. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17019. get: function () {
  17020. return this._lastFrameDuration;
  17021. },
  17022. enumerable: true,
  17023. configurable: true
  17024. });
  17025. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17026. return this._evaluateActiveMeshesDuration.current;
  17027. };
  17028. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17029. get: function () {
  17030. return this._evaluateActiveMeshesDuration;
  17031. },
  17032. enumerable: true,
  17033. configurable: true
  17034. });
  17035. Scene.prototype.getActiveMeshes = function () {
  17036. return this._activeMeshes;
  17037. };
  17038. Scene.prototype.getRenderTargetsDuration = function () {
  17039. return this._renderTargetsDuration.current;
  17040. };
  17041. Scene.prototype.getRenderDuration = function () {
  17042. return this._renderDuration.current;
  17043. };
  17044. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17045. get: function () {
  17046. return this._renderDuration;
  17047. },
  17048. enumerable: true,
  17049. configurable: true
  17050. });
  17051. Scene.prototype.getParticlesDuration = function () {
  17052. return this._particlesDuration.current;
  17053. };
  17054. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17055. get: function () {
  17056. return this._particlesDuration;
  17057. },
  17058. enumerable: true,
  17059. configurable: true
  17060. });
  17061. Scene.prototype.getSpritesDuration = function () {
  17062. return this._spritesDuration.current;
  17063. };
  17064. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17065. get: function () {
  17066. return this._spritesDuration;
  17067. },
  17068. enumerable: true,
  17069. configurable: true
  17070. });
  17071. Scene.prototype.getAnimationRatio = function () {
  17072. return this._animationRatio;
  17073. };
  17074. Scene.prototype.getRenderId = function () {
  17075. return this._renderId;
  17076. };
  17077. Scene.prototype.incrementRenderId = function () {
  17078. this._renderId++;
  17079. };
  17080. Scene.prototype._updatePointerPosition = function (evt) {
  17081. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17082. this._pointerX = evt.clientX - canvasRect.left;
  17083. this._pointerY = evt.clientY - canvasRect.top;
  17084. this._unTranslatedPointerX = this._pointerX;
  17085. this._unTranslatedPointerY = this._pointerY;
  17086. if (this.cameraToUseForPointers) {
  17087. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17088. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17089. }
  17090. };
  17091. // Pointers handling
  17092. /**
  17093. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17094. * @param attachUp defines if you want to attach events to pointerup
  17095. * @param attachDown defines if you want to attach events to pointerdown
  17096. * @param attachMove defines if you want to attach events to pointermove
  17097. */
  17098. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17099. var _this = this;
  17100. if (attachUp === void 0) { attachUp = true; }
  17101. if (attachDown === void 0) { attachDown = true; }
  17102. if (attachMove === void 0) { attachMove = true; }
  17103. var spritePredicate = function (sprite) {
  17104. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17105. };
  17106. this._onPointerMove = function (evt) {
  17107. _this._updatePointerPosition(evt);
  17108. // PreObservable support
  17109. if (_this.onPrePointerObservable.hasObservers()) {
  17110. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17111. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17112. _this.onPrePointerObservable.notifyObservers(pi, type);
  17113. if (pi.skipOnPointerObservable) {
  17114. return;
  17115. }
  17116. }
  17117. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17118. return;
  17119. }
  17120. var canvas = _this._engine.getRenderingCanvas();
  17121. if (!_this.pointerMovePredicate) {
  17122. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17123. }
  17124. // Meshes
  17125. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17126. if (pickResult.hit && pickResult.pickedMesh) {
  17127. _this.setPointerOverSprite(null);
  17128. _this.setPointerOverMesh(pickResult.pickedMesh);
  17129. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17130. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17131. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17132. }
  17133. else {
  17134. canvas.style.cursor = _this.hoverCursor;
  17135. }
  17136. }
  17137. else {
  17138. canvas.style.cursor = "";
  17139. }
  17140. }
  17141. else {
  17142. _this.setPointerOverMesh(null);
  17143. // Sprites
  17144. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17145. if (pickResult.hit && pickResult.pickedSprite) {
  17146. _this.setPointerOverSprite(pickResult.pickedSprite);
  17147. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17148. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17149. }
  17150. else {
  17151. canvas.style.cursor = _this.hoverCursor;
  17152. }
  17153. }
  17154. else {
  17155. _this.setPointerOverSprite(null);
  17156. // Restore pointer
  17157. canvas.style.cursor = "";
  17158. }
  17159. }
  17160. if (_this.onPointerMove) {
  17161. _this.onPointerMove(evt, pickResult);
  17162. }
  17163. if (_this.onPointerObservable.hasObservers()) {
  17164. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17165. var pi = new PointerInfo(type, evt, pickResult);
  17166. _this.onPointerObservable.notifyObservers(pi, type);
  17167. }
  17168. };
  17169. this._onPointerDown = function (evt) {
  17170. _this._updatePointerPosition(evt);
  17171. // PreObservable support
  17172. if (_this.onPrePointerObservable.hasObservers()) {
  17173. var type = PointerEventTypes.POINTERDOWN;
  17174. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17175. _this.onPrePointerObservable.notifyObservers(pi, type);
  17176. if (pi.skipOnPointerObservable) {
  17177. return;
  17178. }
  17179. }
  17180. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17181. return;
  17182. }
  17183. _this._startingPointerPosition.x = _this._pointerX;
  17184. _this._startingPointerPosition.y = _this._pointerY;
  17185. _this._startingPointerTime = new Date().getTime();
  17186. if (!_this.pointerDownPredicate) {
  17187. _this.pointerDownPredicate = function (mesh) {
  17188. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17189. };
  17190. }
  17191. // Meshes
  17192. _this._pickedDownMesh = null;
  17193. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17194. if (pickResult.hit && pickResult.pickedMesh) {
  17195. if (pickResult.pickedMesh.actionManager) {
  17196. _this._pickedDownMesh = pickResult.pickedMesh;
  17197. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17198. switch (evt.button) {
  17199. case 0:
  17200. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17201. break;
  17202. case 1:
  17203. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17204. break;
  17205. case 2:
  17206. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17207. break;
  17208. }
  17209. if (pickResult.pickedMesh.actionManager) {
  17210. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17211. }
  17212. }
  17213. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17214. var that = _this;
  17215. window.setTimeout(function () {
  17216. 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);
  17217. if (pickResult.hit && pickResult.pickedMesh) {
  17218. if (pickResult.pickedMesh.actionManager) {
  17219. 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)) {
  17220. that._startingPointerTime = 0;
  17221. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17222. }
  17223. }
  17224. }
  17225. }, BABYLON.ActionManager.LongPressDelay);
  17226. }
  17227. }
  17228. }
  17229. if (_this.onPointerDown) {
  17230. _this.onPointerDown(evt, pickResult);
  17231. }
  17232. if (_this.onPointerObservable.hasObservers()) {
  17233. var type = PointerEventTypes.POINTERDOWN;
  17234. var pi = new PointerInfo(type, evt, pickResult);
  17235. _this.onPointerObservable.notifyObservers(pi, type);
  17236. }
  17237. // Sprites
  17238. _this._pickedDownSprite = null;
  17239. if (_this.spriteManagers.length > 0) {
  17240. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17241. if (pickResult.hit && pickResult.pickedSprite) {
  17242. if (pickResult.pickedSprite.actionManager) {
  17243. _this._pickedDownSprite = pickResult.pickedSprite;
  17244. switch (evt.button) {
  17245. case 0:
  17246. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17247. break;
  17248. case 1:
  17249. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17250. break;
  17251. case 2:
  17252. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17253. break;
  17254. }
  17255. if (pickResult.pickedSprite.actionManager) {
  17256. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17257. }
  17258. }
  17259. }
  17260. }
  17261. };
  17262. this._onPointerUp = function (evt) {
  17263. _this._updatePointerPosition(evt);
  17264. // PreObservable support
  17265. if (_this.onPrePointerObservable.hasObservers()) {
  17266. var type = PointerEventTypes.POINTERUP;
  17267. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17268. _this.onPrePointerObservable.notifyObservers(pi, type);
  17269. if (pi.skipOnPointerObservable) {
  17270. return;
  17271. }
  17272. }
  17273. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17274. return;
  17275. }
  17276. if (!_this.pointerUpPredicate) {
  17277. _this.pointerUpPredicate = function (mesh) {
  17278. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17279. };
  17280. }
  17281. // Meshes
  17282. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17283. if (pickResult.hit && pickResult.pickedMesh) {
  17284. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17285. if (_this.onPointerPick) {
  17286. _this.onPointerPick(evt, pickResult);
  17287. }
  17288. if (_this.onPointerObservable.hasObservers()) {
  17289. var type = PointerEventTypes.POINTERPICK;
  17290. var pi = new PointerInfo(type, evt, pickResult);
  17291. _this.onPointerObservable.notifyObservers(pi, type);
  17292. }
  17293. }
  17294. if (pickResult.pickedMesh.actionManager) {
  17295. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17296. if (pickResult.pickedMesh.actionManager) {
  17297. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17298. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17299. }
  17300. }
  17301. }
  17302. }
  17303. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17304. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17305. }
  17306. if (_this.onPointerUp) {
  17307. _this.onPointerUp(evt, pickResult);
  17308. }
  17309. if (_this.onPointerObservable.hasObservers()) {
  17310. var type = PointerEventTypes.POINTERUP;
  17311. var pi = new PointerInfo(type, evt, pickResult);
  17312. _this.onPointerObservable.notifyObservers(pi, type);
  17313. }
  17314. _this._startingPointerTime = 0;
  17315. // Sprites
  17316. if (_this.spriteManagers.length > 0) {
  17317. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17318. if (pickResult.hit && pickResult.pickedSprite) {
  17319. if (pickResult.pickedSprite.actionManager) {
  17320. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17321. if (pickResult.pickedSprite.actionManager) {
  17322. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17323. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17324. }
  17325. }
  17326. }
  17327. }
  17328. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17329. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17330. }
  17331. }
  17332. };
  17333. this._onKeyDown = function (evt) {
  17334. if (_this.actionManager) {
  17335. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17336. }
  17337. };
  17338. this._onKeyUp = function (evt) {
  17339. if (_this.actionManager) {
  17340. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17341. }
  17342. };
  17343. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17344. var canvas = this._engine.getRenderingCanvas();
  17345. if (attachMove) {
  17346. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17347. // Wheel
  17348. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17349. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17350. }
  17351. if (attachDown) {
  17352. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17353. }
  17354. if (attachUp) {
  17355. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17356. }
  17357. canvas.tabIndex = 1;
  17358. canvas.addEventListener("keydown", this._onKeyDown, false);
  17359. canvas.addEventListener("keyup", this._onKeyUp, false);
  17360. };
  17361. Scene.prototype.detachControl = function () {
  17362. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17363. var canvas = this._engine.getRenderingCanvas();
  17364. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17365. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17366. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17367. // Wheel
  17368. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17369. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17370. canvas.removeEventListener("keydown", this._onKeyDown);
  17371. canvas.removeEventListener("keyup", this._onKeyUp);
  17372. };
  17373. // Ready
  17374. Scene.prototype.isReady = function () {
  17375. if (this._pendingData.length > 0) {
  17376. return false;
  17377. }
  17378. var index;
  17379. for (index = 0; index < this._geometries.length; index++) {
  17380. var geometry = this._geometries[index];
  17381. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17382. return false;
  17383. }
  17384. }
  17385. for (index = 0; index < this.meshes.length; index++) {
  17386. var mesh = this.meshes[index];
  17387. if (!mesh.isReady()) {
  17388. return false;
  17389. }
  17390. var mat = mesh.material;
  17391. if (mat) {
  17392. if (!mat.isReady(mesh)) {
  17393. return false;
  17394. }
  17395. }
  17396. }
  17397. return true;
  17398. };
  17399. Scene.prototype.resetCachedMaterial = function () {
  17400. this._cachedMaterial = null;
  17401. };
  17402. Scene.prototype.registerBeforeRender = function (func) {
  17403. this.onBeforeRenderObservable.add(func);
  17404. };
  17405. Scene.prototype.unregisterBeforeRender = function (func) {
  17406. this.onBeforeRenderObservable.removeCallback(func);
  17407. };
  17408. Scene.prototype.registerAfterRender = function (func) {
  17409. this.onAfterRenderObservable.add(func);
  17410. };
  17411. Scene.prototype.unregisterAfterRender = function (func) {
  17412. this.onAfterRenderObservable.removeCallback(func);
  17413. };
  17414. Scene.prototype._addPendingData = function (data) {
  17415. this._pendingData.push(data);
  17416. };
  17417. Scene.prototype._removePendingData = function (data) {
  17418. var index = this._pendingData.indexOf(data);
  17419. if (index !== -1) {
  17420. this._pendingData.splice(index, 1);
  17421. }
  17422. };
  17423. Scene.prototype.getWaitingItemsCount = function () {
  17424. return this._pendingData.length;
  17425. };
  17426. /**
  17427. * Registers a function to be executed when the scene is ready.
  17428. * @param {Function} func - the function to be executed.
  17429. */
  17430. Scene.prototype.executeWhenReady = function (func) {
  17431. var _this = this;
  17432. this.onReadyObservable.add(func);
  17433. if (this._executeWhenReadyTimeoutId !== -1) {
  17434. return;
  17435. }
  17436. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17437. _this._checkIsReady();
  17438. }, 150);
  17439. };
  17440. Scene.prototype._checkIsReady = function () {
  17441. var _this = this;
  17442. if (this.isReady()) {
  17443. this.onReadyObservable.notifyObservers(this);
  17444. this.onReadyObservable.clear();
  17445. this._executeWhenReadyTimeoutId = -1;
  17446. return;
  17447. }
  17448. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17449. _this._checkIsReady();
  17450. }, 150);
  17451. };
  17452. // Animations
  17453. /**
  17454. * Will start the animation sequence of a given target
  17455. * @param target - the target
  17456. * @param {number} from - from which frame should animation start
  17457. * @param {number} to - till which frame should animation run.
  17458. * @param {boolean} [loop] - should the animation loop
  17459. * @param {number} [speedRatio] - the speed in which to run the animation
  17460. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17461. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17462. * @return {BABYLON.Animatable} the animatable object created for this animation
  17463. * @see BABYLON.Animatable
  17464. * @see http://doc.babylonjs.com/page.php?p=22081
  17465. */
  17466. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17467. if (speedRatio === void 0) { speedRatio = 1.0; }
  17468. this.stopAnimation(target);
  17469. if (!animatable) {
  17470. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17471. }
  17472. // Local animations
  17473. if (target.animations) {
  17474. animatable.appendAnimations(target, target.animations);
  17475. }
  17476. // Children animations
  17477. if (target.getAnimatables) {
  17478. var animatables = target.getAnimatables();
  17479. for (var index = 0; index < animatables.length; index++) {
  17480. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17481. }
  17482. }
  17483. animatable.reset();
  17484. return animatable;
  17485. };
  17486. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17487. if (speedRatio === undefined) {
  17488. speedRatio = 1.0;
  17489. }
  17490. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17491. return animatable;
  17492. };
  17493. Scene.prototype.getAnimatableByTarget = function (target) {
  17494. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17495. if (this._activeAnimatables[index].target === target) {
  17496. return this._activeAnimatables[index];
  17497. }
  17498. }
  17499. return null;
  17500. };
  17501. Object.defineProperty(Scene.prototype, "Animatables", {
  17502. get: function () {
  17503. return this._activeAnimatables;
  17504. },
  17505. enumerable: true,
  17506. configurable: true
  17507. });
  17508. /**
  17509. * Will stop the animation of the given target
  17510. * @param target - the target
  17511. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17512. * @see beginAnimation
  17513. */
  17514. Scene.prototype.stopAnimation = function (target, animationName) {
  17515. var animatable = this.getAnimatableByTarget(target);
  17516. if (animatable) {
  17517. animatable.stop(animationName);
  17518. }
  17519. };
  17520. Scene.prototype._animate = function () {
  17521. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17522. return;
  17523. }
  17524. if (!this._animationStartDate) {
  17525. if (this._pendingData.length > 0) {
  17526. return;
  17527. }
  17528. this._animationStartDate = BABYLON.Tools.Now;
  17529. }
  17530. // Getting time
  17531. var now = BABYLON.Tools.Now;
  17532. var delay = now - this._animationStartDate;
  17533. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17534. this._activeAnimatables[index]._animate(delay);
  17535. }
  17536. };
  17537. // Matrix
  17538. Scene.prototype.getViewMatrix = function () {
  17539. return this._viewMatrix;
  17540. };
  17541. Scene.prototype.getProjectionMatrix = function () {
  17542. return this._projectionMatrix;
  17543. };
  17544. Scene.prototype.getTransformMatrix = function () {
  17545. return this._transformMatrix;
  17546. };
  17547. Scene.prototype.setTransformMatrix = function (view, projection) {
  17548. this._viewMatrix = view;
  17549. this._projectionMatrix = projection;
  17550. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17551. // Update frustum
  17552. if (!this._frustumPlanes) {
  17553. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17554. }
  17555. else {
  17556. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17557. }
  17558. };
  17559. // Methods
  17560. Scene.prototype.addMesh = function (newMesh) {
  17561. newMesh.uniqueId = this._uniqueIdCounter++;
  17562. var position = this.meshes.push(newMesh);
  17563. //notify the collision coordinator
  17564. this.collisionCoordinator.onMeshAdded(newMesh);
  17565. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17566. };
  17567. Scene.prototype.removeMesh = function (toRemove) {
  17568. var index = this.meshes.indexOf(toRemove);
  17569. if (index !== -1) {
  17570. // Remove from the scene if mesh found
  17571. this.meshes.splice(index, 1);
  17572. }
  17573. //notify the collision coordinator
  17574. this.collisionCoordinator.onMeshRemoved(toRemove);
  17575. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17576. return index;
  17577. };
  17578. Scene.prototype.removeSkeleton = function (toRemove) {
  17579. var index = this.skeletons.indexOf(toRemove);
  17580. if (index !== -1) {
  17581. // Remove from the scene if mesh found
  17582. this.skeletons.splice(index, 1);
  17583. }
  17584. return index;
  17585. };
  17586. Scene.prototype.removeLight = function (toRemove) {
  17587. var index = this.lights.indexOf(toRemove);
  17588. if (index !== -1) {
  17589. // Remove from the scene if mesh found
  17590. this.lights.splice(index, 1);
  17591. }
  17592. this.onLightRemovedObservable.notifyObservers(toRemove);
  17593. return index;
  17594. };
  17595. Scene.prototype.removeCamera = function (toRemove) {
  17596. var index = this.cameras.indexOf(toRemove);
  17597. if (index !== -1) {
  17598. // Remove from the scene if mesh found
  17599. this.cameras.splice(index, 1);
  17600. }
  17601. // Remove from activeCameras
  17602. var index2 = this.activeCameras.indexOf(toRemove);
  17603. if (index2 !== -1) {
  17604. // Remove from the scene if mesh found
  17605. this.activeCameras.splice(index2, 1);
  17606. }
  17607. // Reset the activeCamera
  17608. if (this.activeCamera === toRemove) {
  17609. if (this.cameras.length > 0) {
  17610. this.activeCamera = this.cameras[0];
  17611. }
  17612. else {
  17613. this.activeCamera = null;
  17614. }
  17615. }
  17616. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17617. return index;
  17618. };
  17619. Scene.prototype.addLight = function (newLight) {
  17620. newLight.uniqueId = this._uniqueIdCounter++;
  17621. var position = this.lights.push(newLight);
  17622. this.onNewLightAddedObservable.notifyObservers(newLight);
  17623. };
  17624. Scene.prototype.addCamera = function (newCamera) {
  17625. newCamera.uniqueId = this._uniqueIdCounter++;
  17626. var position = this.cameras.push(newCamera);
  17627. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17628. };
  17629. /**
  17630. * Switch active camera
  17631. * @param {Camera} newCamera - new active camera
  17632. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17633. */
  17634. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17635. if (attachControl === void 0) { attachControl = true; }
  17636. var canvas = this._engine.getRenderingCanvas();
  17637. this.activeCamera.detachControl(canvas);
  17638. this.activeCamera = newCamera;
  17639. if (attachControl) {
  17640. newCamera.attachControl(canvas);
  17641. }
  17642. };
  17643. /**
  17644. * sets the active camera of the scene using its ID
  17645. * @param {string} id - the camera's ID
  17646. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17647. * @see activeCamera
  17648. */
  17649. Scene.prototype.setActiveCameraByID = function (id) {
  17650. var camera = this.getCameraByID(id);
  17651. if (camera) {
  17652. this.activeCamera = camera;
  17653. return camera;
  17654. }
  17655. return null;
  17656. };
  17657. /**
  17658. * sets the active camera of the scene using its name
  17659. * @param {string} name - the camera's name
  17660. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17661. * @see activeCamera
  17662. */
  17663. Scene.prototype.setActiveCameraByName = function (name) {
  17664. var camera = this.getCameraByName(name);
  17665. if (camera) {
  17666. this.activeCamera = camera;
  17667. return camera;
  17668. }
  17669. return null;
  17670. };
  17671. /**
  17672. * get a material using its id
  17673. * @param {string} the material's ID
  17674. * @return {BABYLON.Material|null} the material or null if none found.
  17675. */
  17676. Scene.prototype.getMaterialByID = function (id) {
  17677. for (var index = 0; index < this.materials.length; index++) {
  17678. if (this.materials[index].id === id) {
  17679. return this.materials[index];
  17680. }
  17681. }
  17682. return null;
  17683. };
  17684. /**
  17685. * get a material using its name
  17686. * @param {string} the material's name
  17687. * @return {BABYLON.Material|null} the material or null if none found.
  17688. */
  17689. Scene.prototype.getMaterialByName = function (name) {
  17690. for (var index = 0; index < this.materials.length; index++) {
  17691. if (this.materials[index].name === name) {
  17692. return this.materials[index];
  17693. }
  17694. }
  17695. return null;
  17696. };
  17697. Scene.prototype.getLensFlareSystemByName = function (name) {
  17698. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17699. if (this.lensFlareSystems[index].name === name) {
  17700. return this.lensFlareSystems[index];
  17701. }
  17702. }
  17703. return null;
  17704. };
  17705. Scene.prototype.getLensFlareSystemByID = function (id) {
  17706. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17707. if (this.lensFlareSystems[index].id === id) {
  17708. return this.lensFlareSystems[index];
  17709. }
  17710. }
  17711. return null;
  17712. };
  17713. Scene.prototype.getCameraByID = function (id) {
  17714. for (var index = 0; index < this.cameras.length; index++) {
  17715. if (this.cameras[index].id === id) {
  17716. return this.cameras[index];
  17717. }
  17718. }
  17719. return null;
  17720. };
  17721. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17722. for (var index = 0; index < this.cameras.length; index++) {
  17723. if (this.cameras[index].uniqueId === uniqueId) {
  17724. return this.cameras[index];
  17725. }
  17726. }
  17727. return null;
  17728. };
  17729. /**
  17730. * get a camera using its name
  17731. * @param {string} the camera's name
  17732. * @return {BABYLON.Camera|null} the camera or null if none found.
  17733. */
  17734. Scene.prototype.getCameraByName = function (name) {
  17735. for (var index = 0; index < this.cameras.length; index++) {
  17736. if (this.cameras[index].name === name) {
  17737. return this.cameras[index];
  17738. }
  17739. }
  17740. return null;
  17741. };
  17742. /**
  17743. * get a bone using its id
  17744. * @param {string} the bone's id
  17745. * @return {BABYLON.Bone|null} the bone or null if not found
  17746. */
  17747. Scene.prototype.getBoneByID = function (id) {
  17748. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17749. var skeleton = this.skeletons[skeletonIndex];
  17750. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17751. if (skeleton.bones[boneIndex].id === id) {
  17752. return skeleton.bones[boneIndex];
  17753. }
  17754. }
  17755. }
  17756. return null;
  17757. };
  17758. /**
  17759. * get a bone using its id
  17760. * @param {string} the bone's name
  17761. * @return {BABYLON.Bone|null} the bone or null if not found
  17762. */
  17763. Scene.prototype.getBoneByName = function (name) {
  17764. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17765. var skeleton = this.skeletons[skeletonIndex];
  17766. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17767. if (skeleton.bones[boneIndex].name === name) {
  17768. return skeleton.bones[boneIndex];
  17769. }
  17770. }
  17771. }
  17772. return null;
  17773. };
  17774. /**
  17775. * get a light node using its name
  17776. * @param {string} the light's name
  17777. * @return {BABYLON.Light|null} the light or null if none found.
  17778. */
  17779. Scene.prototype.getLightByName = function (name) {
  17780. for (var index = 0; index < this.lights.length; index++) {
  17781. if (this.lights[index].name === name) {
  17782. return this.lights[index];
  17783. }
  17784. }
  17785. return null;
  17786. };
  17787. /**
  17788. * get a light node using its ID
  17789. * @param {string} the light's id
  17790. * @return {BABYLON.Light|null} the light or null if none found.
  17791. */
  17792. Scene.prototype.getLightByID = function (id) {
  17793. for (var index = 0; index < this.lights.length; index++) {
  17794. if (this.lights[index].id === id) {
  17795. return this.lights[index];
  17796. }
  17797. }
  17798. return null;
  17799. };
  17800. /**
  17801. * get a light node using its scene-generated unique ID
  17802. * @param {number} the light's unique id
  17803. * @return {BABYLON.Light|null} the light or null if none found.
  17804. */
  17805. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17806. for (var index = 0; index < this.lights.length; index++) {
  17807. if (this.lights[index].uniqueId === uniqueId) {
  17808. return this.lights[index];
  17809. }
  17810. }
  17811. return null;
  17812. };
  17813. /**
  17814. * get a particle system by id
  17815. * @param id {number} the particle system id
  17816. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17817. */
  17818. Scene.prototype.getParticleSystemByID = function (id) {
  17819. for (var index = 0; index < this.particleSystems.length; index++) {
  17820. if (this.particleSystems[index].id === id) {
  17821. return this.particleSystems[index];
  17822. }
  17823. }
  17824. return null;
  17825. };
  17826. /**
  17827. * get a geometry using its ID
  17828. * @param {string} the geometry's id
  17829. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17830. */
  17831. Scene.prototype.getGeometryByID = function (id) {
  17832. for (var index = 0; index < this._geometries.length; index++) {
  17833. if (this._geometries[index].id === id) {
  17834. return this._geometries[index];
  17835. }
  17836. }
  17837. return null;
  17838. };
  17839. /**
  17840. * add a new geometry to this scene.
  17841. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17842. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17843. * @return {boolean} was the geometry added or not
  17844. */
  17845. Scene.prototype.pushGeometry = function (geometry, force) {
  17846. if (!force && this.getGeometryByID(geometry.id)) {
  17847. return false;
  17848. }
  17849. this._geometries.push(geometry);
  17850. //notify the collision coordinator
  17851. this.collisionCoordinator.onGeometryAdded(geometry);
  17852. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17853. return true;
  17854. };
  17855. /**
  17856. * Removes an existing geometry
  17857. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17858. * @return {boolean} was the geometry removed or not
  17859. */
  17860. Scene.prototype.removeGeometry = function (geometry) {
  17861. var index = this._geometries.indexOf(geometry);
  17862. if (index > -1) {
  17863. this._geometries.splice(index, 1);
  17864. //notify the collision coordinator
  17865. this.collisionCoordinator.onGeometryDeleted(geometry);
  17866. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17867. return true;
  17868. }
  17869. return false;
  17870. };
  17871. Scene.prototype.getGeometries = function () {
  17872. return this._geometries;
  17873. };
  17874. /**
  17875. * Get the first added mesh found of a given ID
  17876. * @param {string} id - the id to search for
  17877. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17878. */
  17879. Scene.prototype.getMeshByID = function (id) {
  17880. for (var index = 0; index < this.meshes.length; index++) {
  17881. if (this.meshes[index].id === id) {
  17882. return this.meshes[index];
  17883. }
  17884. }
  17885. return null;
  17886. };
  17887. Scene.prototype.getMeshesByID = function (id) {
  17888. return this.meshes.filter(function (m) {
  17889. return m.id === id;
  17890. });
  17891. };
  17892. /**
  17893. * Get a mesh with its auto-generated unique id
  17894. * @param {number} uniqueId - the unique id to search for
  17895. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17896. */
  17897. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17898. for (var index = 0; index < this.meshes.length; index++) {
  17899. if (this.meshes[index].uniqueId === uniqueId) {
  17900. return this.meshes[index];
  17901. }
  17902. }
  17903. return null;
  17904. };
  17905. /**
  17906. * Get a the last added mesh found of a given ID
  17907. * @param {string} id - the id to search for
  17908. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17909. */
  17910. Scene.prototype.getLastMeshByID = function (id) {
  17911. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17912. if (this.meshes[index].id === id) {
  17913. return this.meshes[index];
  17914. }
  17915. }
  17916. return null;
  17917. };
  17918. /**
  17919. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17920. * @param {string} id - the id to search for
  17921. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17922. */
  17923. Scene.prototype.getLastEntryByID = function (id) {
  17924. var index;
  17925. for (index = this.meshes.length - 1; index >= 0; index--) {
  17926. if (this.meshes[index].id === id) {
  17927. return this.meshes[index];
  17928. }
  17929. }
  17930. for (index = this.cameras.length - 1; index >= 0; index--) {
  17931. if (this.cameras[index].id === id) {
  17932. return this.cameras[index];
  17933. }
  17934. }
  17935. for (index = this.lights.length - 1; index >= 0; index--) {
  17936. if (this.lights[index].id === id) {
  17937. return this.lights[index];
  17938. }
  17939. }
  17940. return null;
  17941. };
  17942. Scene.prototype.getNodeByID = function (id) {
  17943. var mesh = this.getMeshByID(id);
  17944. if (mesh) {
  17945. return mesh;
  17946. }
  17947. var light = this.getLightByID(id);
  17948. if (light) {
  17949. return light;
  17950. }
  17951. var camera = this.getCameraByID(id);
  17952. if (camera) {
  17953. return camera;
  17954. }
  17955. var bone = this.getBoneByID(id);
  17956. return bone;
  17957. };
  17958. Scene.prototype.getNodeByName = function (name) {
  17959. var mesh = this.getMeshByName(name);
  17960. if (mesh) {
  17961. return mesh;
  17962. }
  17963. var light = this.getLightByName(name);
  17964. if (light) {
  17965. return light;
  17966. }
  17967. var camera = this.getCameraByName(name);
  17968. if (camera) {
  17969. return camera;
  17970. }
  17971. var bone = this.getBoneByName(name);
  17972. return bone;
  17973. };
  17974. Scene.prototype.getMeshByName = function (name) {
  17975. for (var index = 0; index < this.meshes.length; index++) {
  17976. if (this.meshes[index].name === name) {
  17977. return this.meshes[index];
  17978. }
  17979. }
  17980. return null;
  17981. };
  17982. Scene.prototype.getSoundByName = function (name) {
  17983. var index;
  17984. if (BABYLON.AudioEngine) {
  17985. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17986. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17987. return this.mainSoundTrack.soundCollection[index];
  17988. }
  17989. }
  17990. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17991. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17992. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17993. return this.soundTracks[sdIndex].soundCollection[index];
  17994. }
  17995. }
  17996. }
  17997. }
  17998. return null;
  17999. };
  18000. Scene.prototype.getLastSkeletonByID = function (id) {
  18001. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18002. if (this.skeletons[index].id === id) {
  18003. return this.skeletons[index];
  18004. }
  18005. }
  18006. return null;
  18007. };
  18008. Scene.prototype.getSkeletonById = function (id) {
  18009. for (var index = 0; index < this.skeletons.length; index++) {
  18010. if (this.skeletons[index].id === id) {
  18011. return this.skeletons[index];
  18012. }
  18013. }
  18014. return null;
  18015. };
  18016. Scene.prototype.getSkeletonByName = function (name) {
  18017. for (var index = 0; index < this.skeletons.length; index++) {
  18018. if (this.skeletons[index].name === name) {
  18019. return this.skeletons[index];
  18020. }
  18021. }
  18022. return null;
  18023. };
  18024. Scene.prototype.isActiveMesh = function (mesh) {
  18025. return (this._activeMeshes.indexOf(mesh) !== -1);
  18026. };
  18027. Object.defineProperty(Scene.prototype, "uid", {
  18028. /**
  18029. * Return a unique id as a string which can serve as an identifier for the scene
  18030. */
  18031. get: function () {
  18032. if (!this._uid) {
  18033. this._uid = BABYLON.Tools.RandomId();
  18034. }
  18035. return this._uid;
  18036. },
  18037. enumerable: true,
  18038. configurable: true
  18039. });
  18040. /**
  18041. * Add an externaly attached data from its key.
  18042. * This method call will fail and return false, if such key already exists.
  18043. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18044. * @param key the unique key that identifies the data
  18045. * @param data the data object to associate to the key for this Engine instance
  18046. * @return true if no such key were already present and the data was added successfully, false otherwise
  18047. */
  18048. Scene.prototype.addExternalData = function (key, data) {
  18049. return this._externalData.add(key, data);
  18050. };
  18051. /**
  18052. * Get an externaly attached data from its key
  18053. * @param key the unique key that identifies the data
  18054. * @return the associated data, if present (can be null), or undefined if not present
  18055. */
  18056. Scene.prototype.getExternalData = function (key) {
  18057. return this._externalData.get(key);
  18058. };
  18059. /**
  18060. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18061. * @param key the unique key that identifies the data
  18062. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18063. * @return the associated data, can be null if the factory returned null.
  18064. */
  18065. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18066. return this._externalData.getOrAddWithFactory(key, factory);
  18067. };
  18068. /**
  18069. * Remove an externaly attached data from the Engine instance
  18070. * @param key the unique key that identifies the data
  18071. * @return true if the data was successfully removed, false if it doesn't exist
  18072. */
  18073. Scene.prototype.removeExternalData = function (key) {
  18074. return this._externalData.remove(key);
  18075. };
  18076. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18077. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18078. var material = subMesh.getMaterial();
  18079. if (mesh.showSubMeshesBoundingBox) {
  18080. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18081. }
  18082. if (material) {
  18083. // Render targets
  18084. if (material.getRenderTargetTextures) {
  18085. if (this._processedMaterials.indexOf(material) === -1) {
  18086. this._processedMaterials.push(material);
  18087. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18088. }
  18089. }
  18090. // Dispatch
  18091. this._activeIndices.addCount(subMesh.indexCount, false);
  18092. this._renderingManager.dispatch(subMesh);
  18093. }
  18094. }
  18095. };
  18096. Scene.prototype._isInIntermediateRendering = function () {
  18097. return this._intermediateRendering;
  18098. };
  18099. Scene.prototype._evaluateActiveMeshes = function () {
  18100. this.activeCamera._activeMeshes.reset();
  18101. this._activeMeshes.reset();
  18102. this._renderingManager.reset();
  18103. this._processedMaterials.reset();
  18104. this._activeParticleSystems.reset();
  18105. this._activeSkeletons.reset();
  18106. this._softwareSkinnedMeshes.reset();
  18107. this._boundingBoxRenderer.reset();
  18108. this._edgesRenderers.reset();
  18109. // Meshes
  18110. var meshes;
  18111. var len;
  18112. if (this._selectionOctree) {
  18113. var selection = this._selectionOctree.select(this._frustumPlanes);
  18114. meshes = selection.data;
  18115. len = selection.length;
  18116. }
  18117. else {
  18118. len = this.meshes.length;
  18119. meshes = this.meshes;
  18120. }
  18121. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18122. var mesh = meshes[meshIndex];
  18123. if (mesh.isBlocked) {
  18124. continue;
  18125. }
  18126. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18127. if (!mesh.isReady() || !mesh.isEnabled()) {
  18128. continue;
  18129. }
  18130. mesh.computeWorldMatrix();
  18131. // Intersections
  18132. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18133. this._meshesForIntersections.pushNoDuplicate(mesh);
  18134. }
  18135. // Switch to current LOD
  18136. var meshLOD = mesh.getLOD(this.activeCamera);
  18137. if (!meshLOD) {
  18138. continue;
  18139. }
  18140. mesh._preActivate();
  18141. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18142. this._activeMeshes.push(mesh);
  18143. this.activeCamera._activeMeshes.push(mesh);
  18144. mesh._activate(this._renderId);
  18145. this._activeMesh(mesh, meshLOD);
  18146. }
  18147. }
  18148. // Particle systems
  18149. this._particlesDuration.beginMonitoring();
  18150. var beforeParticlesDate = BABYLON.Tools.Now;
  18151. if (this.particlesEnabled) {
  18152. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18153. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18154. var particleSystem = this.particleSystems[particleIndex];
  18155. if (!particleSystem.isStarted()) {
  18156. continue;
  18157. }
  18158. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18159. this._activeParticleSystems.push(particleSystem);
  18160. particleSystem.animate();
  18161. }
  18162. }
  18163. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18164. }
  18165. this._particlesDuration.endMonitoring(false);
  18166. };
  18167. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18168. if (mesh.skeleton && this.skeletonsEnabled) {
  18169. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18170. mesh.skeleton.prepare();
  18171. }
  18172. if (!mesh.computeBonesUsingShaders) {
  18173. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18174. }
  18175. }
  18176. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18177. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18178. }
  18179. if (sourceMesh._edgesRenderer) {
  18180. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18181. }
  18182. if (mesh && mesh.subMeshes) {
  18183. // Submeshes Octrees
  18184. var len;
  18185. var subMeshes;
  18186. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18187. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18188. len = intersections.length;
  18189. subMeshes = intersections.data;
  18190. }
  18191. else {
  18192. subMeshes = mesh.subMeshes;
  18193. len = subMeshes.length;
  18194. }
  18195. for (var subIndex = 0; subIndex < len; subIndex++) {
  18196. var subMesh = subMeshes[subIndex];
  18197. this._evaluateSubMesh(subMesh, mesh);
  18198. }
  18199. }
  18200. };
  18201. Scene.prototype.updateTransformMatrix = function (force) {
  18202. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18203. };
  18204. Scene.prototype._renderForCamera = function (camera) {
  18205. var engine = this._engine;
  18206. var startTime = BABYLON.Tools.Now;
  18207. this.activeCamera = camera;
  18208. if (!this.activeCamera)
  18209. throw new Error("Active camera not set");
  18210. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18211. // Viewport
  18212. engine.setViewport(this.activeCamera.viewport);
  18213. // Camera
  18214. this.resetCachedMaterial();
  18215. this._renderId++;
  18216. this.updateTransformMatrix();
  18217. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18218. // Meshes
  18219. this._evaluateActiveMeshesDuration.beginMonitoring();
  18220. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18221. this._evaluateActiveMeshes();
  18222. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18223. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18224. // Software skinning
  18225. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18226. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18227. mesh.applySkeleton(mesh.skeleton);
  18228. }
  18229. // Render targets
  18230. this._renderTargetsDuration.beginMonitoring();
  18231. var needsRestoreFrameBuffer = false;
  18232. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18233. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18234. this._intermediateRendering = true;
  18235. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18236. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18237. var renderTarget = this._renderTargets.data[renderIndex];
  18238. if (renderTarget._shouldRender()) {
  18239. this._renderId++;
  18240. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18241. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18242. }
  18243. }
  18244. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18245. this._intermediateRendering = false;
  18246. this._renderId++;
  18247. needsRestoreFrameBuffer = true; // Restore back buffer
  18248. }
  18249. // Render HighlightLayer Texture
  18250. var stencilState = this._engine.getStencilBuffer();
  18251. var renderhighlights = false;
  18252. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18253. this._intermediateRendering = true;
  18254. for (var i = 0; i < this.highlightLayers.length; i++) {
  18255. var highlightLayer = this.highlightLayers[i];
  18256. if (highlightLayer.shouldRender() &&
  18257. (!highlightLayer.camera ||
  18258. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18259. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18260. renderhighlights = true;
  18261. var renderTarget = highlightLayer._mainTexture;
  18262. if (renderTarget._shouldRender()) {
  18263. this._renderId++;
  18264. renderTarget.render(false, false);
  18265. needsRestoreFrameBuffer = true;
  18266. }
  18267. }
  18268. }
  18269. this._intermediateRendering = false;
  18270. this._renderId++;
  18271. }
  18272. if (needsRestoreFrameBuffer) {
  18273. engine.restoreDefaultFramebuffer();
  18274. }
  18275. this._renderTargetsDuration.endMonitoring(false);
  18276. // Prepare Frame
  18277. this.postProcessManager._prepareFrame();
  18278. this._renderDuration.beginMonitoring();
  18279. // Backgrounds
  18280. var layerIndex;
  18281. var layer;
  18282. if (this.layers.length) {
  18283. engine.setDepthBuffer(false);
  18284. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18285. layer = this.layers[layerIndex];
  18286. if (layer.isBackground) {
  18287. layer.render();
  18288. }
  18289. }
  18290. engine.setDepthBuffer(true);
  18291. }
  18292. // Render
  18293. BABYLON.Tools.StartPerformanceCounter("Main render");
  18294. // Activate HighlightLayer stencil
  18295. if (renderhighlights) {
  18296. this._engine.setStencilBuffer(true);
  18297. }
  18298. this._renderingManager.render(null, null, true, true);
  18299. // Restore HighlightLayer stencil
  18300. if (renderhighlights) {
  18301. this._engine.setStencilBuffer(stencilState);
  18302. }
  18303. BABYLON.Tools.EndPerformanceCounter("Main render");
  18304. // Bounding boxes
  18305. this._boundingBoxRenderer.render();
  18306. // Edges
  18307. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18308. this._edgesRenderers.data[edgesRendererIndex].render();
  18309. }
  18310. // Lens flares
  18311. if (this.lensFlaresEnabled) {
  18312. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18313. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18314. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18315. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18316. lensFlareSystem.render();
  18317. }
  18318. }
  18319. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18320. }
  18321. // Foregrounds
  18322. if (this.layers.length) {
  18323. engine.setDepthBuffer(false);
  18324. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18325. layer = this.layers[layerIndex];
  18326. if (!layer.isBackground) {
  18327. layer.render();
  18328. }
  18329. }
  18330. engine.setDepthBuffer(true);
  18331. }
  18332. // Highlight Layer
  18333. if (renderhighlights) {
  18334. engine.setDepthBuffer(false);
  18335. for (var i = 0; i < this.highlightLayers.length; i++) {
  18336. if (this.highlightLayers[i].shouldRender()) {
  18337. this.highlightLayers[i].render();
  18338. }
  18339. }
  18340. engine.setDepthBuffer(true);
  18341. }
  18342. this._renderDuration.endMonitoring(false);
  18343. // Finalize frame
  18344. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18345. // Update camera
  18346. this.activeCamera._updateFromScene();
  18347. // Reset some special arrays
  18348. this._renderTargets.reset();
  18349. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18350. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18351. };
  18352. Scene.prototype._processSubCameras = function (camera) {
  18353. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18354. this._renderForCamera(camera);
  18355. return;
  18356. }
  18357. // rig cameras
  18358. for (var index = 0; index < camera._rigCameras.length; index++) {
  18359. this._renderForCamera(camera._rigCameras[index]);
  18360. }
  18361. this.activeCamera = camera;
  18362. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18363. // Update camera
  18364. this.activeCamera._updateFromScene();
  18365. };
  18366. Scene.prototype._checkIntersections = function () {
  18367. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18368. var sourceMesh = this._meshesForIntersections.data[index];
  18369. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18370. var action = sourceMesh.actionManager.actions[actionIndex];
  18371. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18372. var parameters = action.getTriggerParameter();
  18373. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18374. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18375. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18376. if (areIntersecting && currentIntersectionInProgress === -1) {
  18377. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18378. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18379. sourceMesh._intersectionsInProgress.push(otherMesh);
  18380. }
  18381. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18382. sourceMesh._intersectionsInProgress.push(otherMesh);
  18383. }
  18384. }
  18385. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18386. //They intersected, and now they don't.
  18387. //is this trigger an exit trigger? execute an event.
  18388. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18389. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18390. }
  18391. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18392. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18393. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18394. }
  18395. }
  18396. }
  18397. }
  18398. }
  18399. };
  18400. Scene.prototype.render = function () {
  18401. this._lastFrameDuration.beginMonitoring();
  18402. this._particlesDuration.fetchNewFrame();
  18403. this._spritesDuration.fetchNewFrame();
  18404. this._activeParticles.fetchNewFrame();
  18405. this._renderDuration.fetchNewFrame();
  18406. this._renderTargetsDuration.fetchNewFrame();
  18407. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18408. this._totalVertices.fetchNewFrame();
  18409. this._activeIndices.fetchNewFrame();
  18410. this._activeBones.fetchNewFrame();
  18411. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18412. this._meshesForIntersections.reset();
  18413. this.resetCachedMaterial();
  18414. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18415. // Actions
  18416. if (this.actionManager) {
  18417. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18418. }
  18419. //Simplification Queue
  18420. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18421. this.simplificationQueue.executeNext();
  18422. }
  18423. // Animations
  18424. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18425. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18426. this._animate();
  18427. // Physics
  18428. if (this._physicsEngine) {
  18429. BABYLON.Tools.StartPerformanceCounter("Physics");
  18430. this._physicsEngine._step(deltaTime / 1000.0);
  18431. BABYLON.Tools.EndPerformanceCounter("Physics");
  18432. }
  18433. // Before render
  18434. this.onBeforeRenderObservable.notifyObservers(this);
  18435. // Customs render targets
  18436. this._renderTargetsDuration.beginMonitoring();
  18437. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18438. var engine = this.getEngine();
  18439. var currentActiveCamera = this.activeCamera;
  18440. if (this.renderTargetsEnabled) {
  18441. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18442. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18443. var renderTarget = this.customRenderTargets[customIndex];
  18444. if (renderTarget._shouldRender()) {
  18445. this._renderId++;
  18446. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18447. if (!this.activeCamera)
  18448. throw new Error("Active camera not set");
  18449. // Viewport
  18450. engine.setViewport(this.activeCamera.viewport);
  18451. // Camera
  18452. this.updateTransformMatrix();
  18453. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18454. }
  18455. }
  18456. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18457. this._renderId++;
  18458. }
  18459. if (this.customRenderTargets.length > 0) {
  18460. engine.restoreDefaultFramebuffer();
  18461. }
  18462. this._renderTargetsDuration.endMonitoring();
  18463. this.activeCamera = currentActiveCamera;
  18464. // Procedural textures
  18465. if (this.proceduralTexturesEnabled) {
  18466. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18467. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18468. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18469. if (proceduralTexture._shouldRender()) {
  18470. proceduralTexture.render();
  18471. }
  18472. }
  18473. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18474. }
  18475. // Clear
  18476. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18477. // Shadows
  18478. if (this.shadowsEnabled) {
  18479. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18480. var light = this.lights[lightIndex];
  18481. var shadowGenerator = light.getShadowGenerator();
  18482. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18483. this._renderTargets.push(shadowGenerator.getShadowMap());
  18484. }
  18485. }
  18486. }
  18487. // Depth renderer
  18488. if (this._depthRenderer) {
  18489. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18490. }
  18491. // RenderPipeline
  18492. this.postProcessRenderPipelineManager.update();
  18493. // Multi-cameras?
  18494. if (this.activeCameras.length > 0) {
  18495. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18496. if (cameraIndex > 0) {
  18497. this._engine.clear(0, false, true, true);
  18498. }
  18499. this._processSubCameras(this.activeCameras[cameraIndex]);
  18500. }
  18501. }
  18502. else {
  18503. if (!this.activeCamera) {
  18504. throw new Error("No camera defined");
  18505. }
  18506. this._processSubCameras(this.activeCamera);
  18507. }
  18508. // Intersection checks
  18509. this._checkIntersections();
  18510. // Update the audio listener attached to the camera
  18511. if (BABYLON.AudioEngine) {
  18512. this._updateAudioParameters();
  18513. }
  18514. // After render
  18515. if (this.afterRender) {
  18516. this.afterRender();
  18517. }
  18518. this.onAfterRenderObservable.notifyObservers(this);
  18519. // Cleaning
  18520. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18521. this._toBeDisposed.data[index].dispose();
  18522. this._toBeDisposed[index] = null;
  18523. }
  18524. this._toBeDisposed.reset();
  18525. if (this.dumpNextRenderTargets) {
  18526. this.dumpNextRenderTargets = false;
  18527. }
  18528. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18529. this._lastFrameDuration.endMonitoring();
  18530. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18531. this._totalLightsCounter.addCount(this.lights.length, true);
  18532. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18533. this._totalTexturesCounter.addCount(this.textures.length, true);
  18534. this._activeBones.addCount(0, true);
  18535. this._activeIndices.addCount(0, true);
  18536. this._activeParticles.addCount(0, true);
  18537. };
  18538. Scene.prototype._updateAudioParameters = function () {
  18539. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18540. return;
  18541. }
  18542. var listeningCamera;
  18543. var audioEngine = BABYLON.Engine.audioEngine;
  18544. if (this.activeCameras.length > 0) {
  18545. listeningCamera = this.activeCameras[0];
  18546. }
  18547. else {
  18548. listeningCamera = this.activeCamera;
  18549. }
  18550. if (listeningCamera && audioEngine.canUseWebAudio) {
  18551. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18552. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18553. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18554. cameraDirection.normalize();
  18555. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18556. var i;
  18557. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18558. var sound = this.mainSoundTrack.soundCollection[i];
  18559. if (sound.useCustomAttenuation) {
  18560. sound.updateDistanceFromListener();
  18561. }
  18562. }
  18563. for (i = 0; i < this.soundTracks.length; i++) {
  18564. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18565. sound = this.soundTracks[i].soundCollection[j];
  18566. if (sound.useCustomAttenuation) {
  18567. sound.updateDistanceFromListener();
  18568. }
  18569. }
  18570. }
  18571. }
  18572. };
  18573. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18574. // Audio
  18575. get: function () {
  18576. return this._audioEnabled;
  18577. },
  18578. set: function (value) {
  18579. this._audioEnabled = value;
  18580. if (BABYLON.AudioEngine) {
  18581. if (this._audioEnabled) {
  18582. this._enableAudio();
  18583. }
  18584. else {
  18585. this._disableAudio();
  18586. }
  18587. }
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. Scene.prototype._disableAudio = function () {
  18593. var i;
  18594. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18595. this.mainSoundTrack.soundCollection[i].pause();
  18596. }
  18597. for (i = 0; i < this.soundTracks.length; i++) {
  18598. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18599. this.soundTracks[i].soundCollection[j].pause();
  18600. }
  18601. }
  18602. };
  18603. Scene.prototype._enableAudio = function () {
  18604. var i;
  18605. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18606. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18607. this.mainSoundTrack.soundCollection[i].play();
  18608. }
  18609. }
  18610. for (i = 0; i < this.soundTracks.length; i++) {
  18611. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18612. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18613. this.soundTracks[i].soundCollection[j].play();
  18614. }
  18615. }
  18616. }
  18617. };
  18618. Object.defineProperty(Scene.prototype, "headphone", {
  18619. get: function () {
  18620. return this._headphone;
  18621. },
  18622. set: function (value) {
  18623. this._headphone = value;
  18624. if (BABYLON.AudioEngine) {
  18625. if (this._headphone) {
  18626. this._switchAudioModeForHeadphones();
  18627. }
  18628. else {
  18629. this._switchAudioModeForNormalSpeakers();
  18630. }
  18631. }
  18632. },
  18633. enumerable: true,
  18634. configurable: true
  18635. });
  18636. Scene.prototype._switchAudioModeForHeadphones = function () {
  18637. this.mainSoundTrack.switchPanningModelToHRTF();
  18638. for (var i = 0; i < this.soundTracks.length; i++) {
  18639. this.soundTracks[i].switchPanningModelToHRTF();
  18640. }
  18641. };
  18642. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18643. this.mainSoundTrack.switchPanningModelToEqualPower();
  18644. for (var i = 0; i < this.soundTracks.length; i++) {
  18645. this.soundTracks[i].switchPanningModelToEqualPower();
  18646. }
  18647. };
  18648. Scene.prototype.enableDepthRenderer = function () {
  18649. if (this._depthRenderer) {
  18650. return this._depthRenderer;
  18651. }
  18652. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18653. return this._depthRenderer;
  18654. };
  18655. Scene.prototype.disableDepthRenderer = function () {
  18656. if (!this._depthRenderer) {
  18657. return;
  18658. }
  18659. this._depthRenderer.dispose();
  18660. this._depthRenderer = null;
  18661. };
  18662. Scene.prototype.freezeMaterials = function () {
  18663. for (var i = 0; i < this.materials.length; i++) {
  18664. this.materials[i].freeze();
  18665. }
  18666. };
  18667. Scene.prototype.unfreezeMaterials = function () {
  18668. for (var i = 0; i < this.materials.length; i++) {
  18669. this.materials[i].unfreeze();
  18670. }
  18671. };
  18672. Scene.prototype.dispose = function () {
  18673. this.beforeRender = null;
  18674. this.afterRender = null;
  18675. this.skeletons = [];
  18676. this._boundingBoxRenderer.dispose();
  18677. if (this._depthRenderer) {
  18678. this._depthRenderer.dispose();
  18679. }
  18680. // Debug layer
  18681. if (this._debugLayer) {
  18682. this._debugLayer.hide();
  18683. }
  18684. // Events
  18685. this.onDisposeObservable.notifyObservers(this);
  18686. this.onDisposeObservable.clear();
  18687. this.onBeforeRenderObservable.clear();
  18688. this.onAfterRenderObservable.clear();
  18689. this.detachControl();
  18690. // Release sounds & sounds tracks
  18691. if (BABYLON.AudioEngine) {
  18692. this.disposeSounds();
  18693. }
  18694. // Detach cameras
  18695. var canvas = this._engine.getRenderingCanvas();
  18696. var index;
  18697. for (index = 0; index < this.cameras.length; index++) {
  18698. this.cameras[index].detachControl(canvas);
  18699. }
  18700. // Release lights
  18701. while (this.lights.length) {
  18702. this.lights[0].dispose();
  18703. }
  18704. // Release meshes
  18705. while (this.meshes.length) {
  18706. this.meshes[0].dispose(true);
  18707. }
  18708. // Release cameras
  18709. while (this.cameras.length) {
  18710. this.cameras[0].dispose();
  18711. }
  18712. // Release materials
  18713. while (this.materials.length) {
  18714. this.materials[0].dispose();
  18715. }
  18716. // Release particles
  18717. while (this.particleSystems.length) {
  18718. this.particleSystems[0].dispose();
  18719. }
  18720. // Release sprites
  18721. while (this.spriteManagers.length) {
  18722. this.spriteManagers[0].dispose();
  18723. }
  18724. // Release layers
  18725. while (this.layers.length) {
  18726. this.layers[0].dispose();
  18727. }
  18728. while (this.highlightLayers.length) {
  18729. this.highlightLayers[0].dispose();
  18730. }
  18731. // Release textures
  18732. while (this.textures.length) {
  18733. this.textures[0].dispose();
  18734. }
  18735. // Post-processes
  18736. this.postProcessManager.dispose();
  18737. // Physics
  18738. if (this._physicsEngine) {
  18739. this.disablePhysicsEngine();
  18740. }
  18741. // Remove from engine
  18742. index = this._engine.scenes.indexOf(this);
  18743. if (index > -1) {
  18744. this._engine.scenes.splice(index, 1);
  18745. }
  18746. this._engine.wipeCaches();
  18747. };
  18748. // Release sounds & sounds tracks
  18749. Scene.prototype.disposeSounds = function () {
  18750. this.mainSoundTrack.dispose();
  18751. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18752. this.soundTracks[scIndex].dispose();
  18753. }
  18754. };
  18755. // Octrees
  18756. Scene.prototype.getWorldExtends = function () {
  18757. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18758. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18759. for (var index = 0; index < this.meshes.length; index++) {
  18760. var mesh = this.meshes[index];
  18761. mesh.computeWorldMatrix(true);
  18762. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18763. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18764. BABYLON.Tools.CheckExtends(minBox, min, max);
  18765. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18766. }
  18767. return {
  18768. min: min,
  18769. max: max
  18770. };
  18771. };
  18772. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18773. if (maxCapacity === void 0) { maxCapacity = 64; }
  18774. if (maxDepth === void 0) { maxDepth = 2; }
  18775. if (!this._selectionOctree) {
  18776. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18777. }
  18778. var worldExtends = this.getWorldExtends();
  18779. // Update octree
  18780. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18781. return this._selectionOctree;
  18782. };
  18783. // Picking
  18784. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18785. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18786. var engine = this._engine;
  18787. if (!camera) {
  18788. if (!this.activeCamera)
  18789. throw new Error("Active camera not set");
  18790. camera = this.activeCamera;
  18791. }
  18792. var cameraViewport = camera.viewport;
  18793. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18794. // Moving coordinates to local viewport world
  18795. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18796. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18797. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18798. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18799. };
  18800. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18801. var engine = this._engine;
  18802. if (!camera) {
  18803. if (!this.activeCamera)
  18804. throw new Error("Active camera not set");
  18805. camera = this.activeCamera;
  18806. }
  18807. var cameraViewport = camera.viewport;
  18808. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18809. var identity = BABYLON.Matrix.Identity();
  18810. // Moving coordinates to local viewport world
  18811. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18812. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18813. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18814. };
  18815. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18816. var pickingInfo = null;
  18817. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18818. var mesh = this.meshes[meshIndex];
  18819. if (predicate) {
  18820. if (!predicate(mesh)) {
  18821. continue;
  18822. }
  18823. }
  18824. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18825. continue;
  18826. }
  18827. var world = mesh.getWorldMatrix();
  18828. var ray = rayFunction(world);
  18829. var result = mesh.intersects(ray, fastCheck);
  18830. if (!result || !result.hit)
  18831. continue;
  18832. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18833. continue;
  18834. pickingInfo = result;
  18835. if (fastCheck) {
  18836. break;
  18837. }
  18838. }
  18839. return pickingInfo || new BABYLON.PickingInfo();
  18840. };
  18841. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18842. var pickingInfos = new Array();
  18843. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18844. var mesh = this.meshes[meshIndex];
  18845. if (predicate) {
  18846. if (!predicate(mesh)) {
  18847. continue;
  18848. }
  18849. }
  18850. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18851. continue;
  18852. }
  18853. var world = mesh.getWorldMatrix();
  18854. var ray = rayFunction(world);
  18855. var result = mesh.intersects(ray, false);
  18856. if (!result || !result.hit)
  18857. continue;
  18858. pickingInfos.push(result);
  18859. }
  18860. return pickingInfos;
  18861. };
  18862. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18863. var pickingInfo = null;
  18864. camera = camera || this.activeCamera;
  18865. if (this.spriteManagers.length > 0) {
  18866. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18867. var spriteManager = this.spriteManagers[spriteIndex];
  18868. if (!spriteManager.isPickable) {
  18869. continue;
  18870. }
  18871. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18872. if (!result || !result.hit)
  18873. continue;
  18874. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18875. continue;
  18876. pickingInfo = result;
  18877. if (fastCheck) {
  18878. break;
  18879. }
  18880. }
  18881. }
  18882. return pickingInfo || new BABYLON.PickingInfo();
  18883. };
  18884. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18885. /// <param name="x">X position on screen</param>
  18886. /// <param name="y">Y position on screen</param>
  18887. /// <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>
  18888. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18889. /// <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>
  18890. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18891. var _this = this;
  18892. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18893. };
  18894. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18895. /// <param name="x">X position on screen</param>
  18896. /// <param name="y">Y position on screen</param>
  18897. /// <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>
  18898. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18899. /// <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>
  18900. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18901. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18902. };
  18903. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18904. var _this = this;
  18905. return this._internalPick(function (world) {
  18906. if (!_this._pickWithRayInverseMatrix) {
  18907. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18908. }
  18909. world.invertToRef(_this._pickWithRayInverseMatrix);
  18910. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18911. }, predicate, fastCheck);
  18912. };
  18913. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18914. /// <param name="x">X position on screen</param>
  18915. /// <param name="y">Y position on screen</param>
  18916. /// <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>
  18917. /// <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>
  18918. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18919. var _this = this;
  18920. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18921. };
  18922. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18923. /// <param name="ray">Ray to use</param>
  18924. /// <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>
  18925. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18926. var _this = this;
  18927. return this._internalMultiPick(function (world) {
  18928. if (!_this._pickWithRayInverseMatrix) {
  18929. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18930. }
  18931. world.invertToRef(_this._pickWithRayInverseMatrix);
  18932. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18933. }, predicate);
  18934. };
  18935. Scene.prototype.setPointerOverMesh = function (mesh) {
  18936. if (this._pointerOverMesh === mesh) {
  18937. return;
  18938. }
  18939. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18940. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18941. }
  18942. this._pointerOverMesh = mesh;
  18943. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18944. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18945. }
  18946. };
  18947. Scene.prototype.getPointerOverMesh = function () {
  18948. return this._pointerOverMesh;
  18949. };
  18950. Scene.prototype.setPointerOverSprite = function (sprite) {
  18951. if (this._pointerOverSprite === sprite) {
  18952. return;
  18953. }
  18954. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18955. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18956. }
  18957. this._pointerOverSprite = sprite;
  18958. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18959. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18960. }
  18961. };
  18962. Scene.prototype.getPointerOverSprite = function () {
  18963. return this._pointerOverSprite;
  18964. };
  18965. // Physics
  18966. Scene.prototype.getPhysicsEngine = function () {
  18967. return this._physicsEngine;
  18968. };
  18969. /**
  18970. * Enables physics to the current scene
  18971. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18972. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18973. * @return {boolean} was the physics engine initialized
  18974. */
  18975. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18976. if (this._physicsEngine) {
  18977. return true;
  18978. }
  18979. try {
  18980. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18981. return true;
  18982. }
  18983. catch (e) {
  18984. BABYLON.Tools.Error(e.message);
  18985. return false;
  18986. }
  18987. };
  18988. Scene.prototype.disablePhysicsEngine = function () {
  18989. if (!this._physicsEngine) {
  18990. return;
  18991. }
  18992. this._physicsEngine.dispose();
  18993. this._physicsEngine = undefined;
  18994. };
  18995. Scene.prototype.isPhysicsEnabled = function () {
  18996. return this._physicsEngine !== undefined;
  18997. };
  18998. /**
  18999. *
  19000. * Sets the gravity of the physics engine (and NOT of the scene)
  19001. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19002. */
  19003. Scene.prototype.setGravity = function (gravity) {
  19004. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19005. if (!this._physicsEngine) {
  19006. return;
  19007. }
  19008. this._physicsEngine.setGravity(gravity);
  19009. };
  19010. /**
  19011. * Legacy support, using the new API
  19012. * @Deprecated
  19013. */
  19014. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19015. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19016. if (parts.parts) {
  19017. options = parts;
  19018. parts = parts.parts;
  19019. }
  19020. var mainMesh = parts[0].mesh;
  19021. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19022. for (var index = 1; index < parts.length; index++) {
  19023. var mesh = parts[index].mesh;
  19024. if (mesh.parent !== mainMesh) {
  19025. mesh.position = mesh.position.subtract(mainMesh.position);
  19026. mesh.parent = mainMesh;
  19027. }
  19028. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19029. }
  19030. mainMesh.physicsImpostor.forceUpdate();
  19031. };
  19032. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19033. var mesh = compound.parts[0].mesh;
  19034. mesh.physicsImpostor.dispose();
  19035. mesh.physicsImpostor = null;
  19036. };
  19037. // Misc.
  19038. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19039. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19040. // Light
  19041. if (this.lights.length === 0) {
  19042. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19043. }
  19044. // Camera
  19045. if (!this.activeCamera) {
  19046. // Compute position
  19047. var worldExtends = this.getWorldExtends();
  19048. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19049. var camera;
  19050. if (createArcRotateCamera) {
  19051. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19052. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19053. camera.setTarget(worldCenter);
  19054. }
  19055. else {
  19056. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19057. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19058. camera.setTarget(worldCenter);
  19059. }
  19060. this.activeCamera = camera;
  19061. }
  19062. };
  19063. // Tags
  19064. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19065. if (tagsQuery === undefined) {
  19066. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19067. return list;
  19068. }
  19069. var listByTags = [];
  19070. forEach = forEach || (function (item) { return; });
  19071. for (var i in list) {
  19072. var item = list[i];
  19073. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19074. listByTags.push(item);
  19075. forEach(item);
  19076. }
  19077. }
  19078. return listByTags;
  19079. };
  19080. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19081. return this._getByTags(this.meshes, tagsQuery, forEach);
  19082. };
  19083. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19084. return this._getByTags(this.cameras, tagsQuery, forEach);
  19085. };
  19086. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19087. return this._getByTags(this.lights, tagsQuery, forEach);
  19088. };
  19089. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19090. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19091. };
  19092. /**
  19093. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19094. * This allowed control for front to back rendering or reversly depending of the special needs.
  19095. *
  19096. * @param renderingGroupId The rendering group id corresponding to its index
  19097. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19098. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19099. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19100. */
  19101. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19102. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19103. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19104. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19105. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19106. };
  19107. /**
  19108. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19109. *
  19110. * @param renderingGroupId The rendering group id corresponding to its index
  19111. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19112. */
  19113. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  19114. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  19115. };
  19116. // Statics
  19117. Scene._FOGMODE_NONE = 0;
  19118. Scene._FOGMODE_EXP = 1;
  19119. Scene._FOGMODE_EXP2 = 2;
  19120. Scene._FOGMODE_LINEAR = 3;
  19121. Scene.MinDeltaTime = 1.0;
  19122. Scene.MaxDeltaTime = 1000.0;
  19123. return Scene;
  19124. }());
  19125. BABYLON.Scene = Scene;
  19126. })(BABYLON || (BABYLON = {}));
  19127. //# sourceMappingURL=babylon.scene.js.map
  19128. var BABYLON;
  19129. (function (BABYLON) {
  19130. var Buffer = (function () {
  19131. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19132. if (engine instanceof BABYLON.Mesh) {
  19133. this._engine = engine.getScene().getEngine();
  19134. }
  19135. else {
  19136. this._engine = engine;
  19137. }
  19138. this._updatable = updatable;
  19139. this._data = data;
  19140. this._strideSize = stride;
  19141. if (!postponeInternalCreation) {
  19142. this.create();
  19143. }
  19144. this._instanced = instanced;
  19145. }
  19146. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19147. // a lot of these parameters are ignored as they are overriden by the buffer
  19148. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19149. };
  19150. // Properties
  19151. Buffer.prototype.isUpdatable = function () {
  19152. return this._updatable;
  19153. };
  19154. Buffer.prototype.getData = function () {
  19155. return this._data;
  19156. };
  19157. Buffer.prototype.getBuffer = function () {
  19158. return this._buffer;
  19159. };
  19160. Buffer.prototype.getStrideSize = function () {
  19161. return this._strideSize;
  19162. };
  19163. Buffer.prototype.getIsInstanced = function () {
  19164. return this._instanced;
  19165. };
  19166. // Methods
  19167. Buffer.prototype.create = function (data) {
  19168. if (!data && this._buffer) {
  19169. return; // nothing to do
  19170. }
  19171. data = data || this._data;
  19172. if (!this._buffer) {
  19173. if (this._updatable) {
  19174. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19175. this._data = data;
  19176. }
  19177. else {
  19178. this._buffer = this._engine.createVertexBuffer(data);
  19179. }
  19180. }
  19181. else if (this._updatable) {
  19182. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19183. this._data = data;
  19184. }
  19185. };
  19186. Buffer.prototype.update = function (data) {
  19187. this.create(data);
  19188. };
  19189. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19190. if (!this._buffer) {
  19191. return;
  19192. }
  19193. if (this._updatable) {
  19194. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19195. this._data = null;
  19196. }
  19197. };
  19198. Buffer.prototype.dispose = function () {
  19199. if (!this._buffer) {
  19200. return;
  19201. }
  19202. if (this._engine._releaseBuffer(this._buffer)) {
  19203. this._buffer = null;
  19204. }
  19205. };
  19206. return Buffer;
  19207. }());
  19208. BABYLON.Buffer = Buffer;
  19209. })(BABYLON || (BABYLON = {}));
  19210. //# sourceMappingURL=babylon.buffer.js.map
  19211. var BABYLON;
  19212. (function (BABYLON) {
  19213. var VertexBuffer = (function () {
  19214. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19215. if (!stride) {
  19216. // Deduce stride from kind
  19217. switch (kind) {
  19218. case VertexBuffer.PositionKind:
  19219. stride = 3;
  19220. break;
  19221. case VertexBuffer.NormalKind:
  19222. stride = 3;
  19223. break;
  19224. case VertexBuffer.UVKind:
  19225. case VertexBuffer.UV2Kind:
  19226. case VertexBuffer.UV3Kind:
  19227. case VertexBuffer.UV4Kind:
  19228. case VertexBuffer.UV5Kind:
  19229. case VertexBuffer.UV6Kind:
  19230. stride = 2;
  19231. break;
  19232. case VertexBuffer.ColorKind:
  19233. stride = 4;
  19234. break;
  19235. case VertexBuffer.MatricesIndicesKind:
  19236. case VertexBuffer.MatricesIndicesExtraKind:
  19237. stride = 4;
  19238. break;
  19239. case VertexBuffer.MatricesWeightsKind:
  19240. case VertexBuffer.MatricesWeightsExtraKind:
  19241. stride = 4;
  19242. break;
  19243. }
  19244. }
  19245. if (data instanceof BABYLON.Buffer) {
  19246. if (!stride) {
  19247. stride = data.getStrideSize();
  19248. }
  19249. this._buffer = data;
  19250. this._ownsBuffer = false;
  19251. }
  19252. else {
  19253. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19254. this._ownsBuffer = true;
  19255. }
  19256. this._stride = stride;
  19257. this._offset = offset ? offset : 0;
  19258. this._size = size ? size : stride;
  19259. this._kind = kind;
  19260. }
  19261. VertexBuffer.prototype.getKind = function () {
  19262. return this._kind;
  19263. };
  19264. // Properties
  19265. VertexBuffer.prototype.isUpdatable = function () {
  19266. return this._buffer.isUpdatable();
  19267. };
  19268. VertexBuffer.prototype.getData = function () {
  19269. return this._buffer.getData();
  19270. };
  19271. VertexBuffer.prototype.getBuffer = function () {
  19272. return this._buffer.getBuffer();
  19273. };
  19274. VertexBuffer.prototype.getStrideSize = function () {
  19275. return this._stride;
  19276. };
  19277. VertexBuffer.prototype.getOffset = function () {
  19278. return this._offset;
  19279. };
  19280. VertexBuffer.prototype.getSize = function () {
  19281. return this._size;
  19282. };
  19283. VertexBuffer.prototype.getIsInstanced = function () {
  19284. return this._buffer.getIsInstanced();
  19285. };
  19286. // Methods
  19287. VertexBuffer.prototype.create = function (data) {
  19288. return this._buffer.create(data);
  19289. };
  19290. VertexBuffer.prototype.update = function (data) {
  19291. return this._buffer.update(data);
  19292. };
  19293. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19294. return this._buffer.updateDirectly(data, offset);
  19295. };
  19296. VertexBuffer.prototype.dispose = function () {
  19297. if (this._ownsBuffer) {
  19298. this._buffer.dispose();
  19299. }
  19300. };
  19301. Object.defineProperty(VertexBuffer, "PositionKind", {
  19302. get: function () {
  19303. return VertexBuffer._PositionKind;
  19304. },
  19305. enumerable: true,
  19306. configurable: true
  19307. });
  19308. Object.defineProperty(VertexBuffer, "NormalKind", {
  19309. get: function () {
  19310. return VertexBuffer._NormalKind;
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. Object.defineProperty(VertexBuffer, "UVKind", {
  19316. get: function () {
  19317. return VertexBuffer._UVKind;
  19318. },
  19319. enumerable: true,
  19320. configurable: true
  19321. });
  19322. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19323. get: function () {
  19324. return VertexBuffer._UV2Kind;
  19325. },
  19326. enumerable: true,
  19327. configurable: true
  19328. });
  19329. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19330. get: function () {
  19331. return VertexBuffer._UV3Kind;
  19332. },
  19333. enumerable: true,
  19334. configurable: true
  19335. });
  19336. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19337. get: function () {
  19338. return VertexBuffer._UV4Kind;
  19339. },
  19340. enumerable: true,
  19341. configurable: true
  19342. });
  19343. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19344. get: function () {
  19345. return VertexBuffer._UV5Kind;
  19346. },
  19347. enumerable: true,
  19348. configurable: true
  19349. });
  19350. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19351. get: function () {
  19352. return VertexBuffer._UV6Kind;
  19353. },
  19354. enumerable: true,
  19355. configurable: true
  19356. });
  19357. Object.defineProperty(VertexBuffer, "ColorKind", {
  19358. get: function () {
  19359. return VertexBuffer._ColorKind;
  19360. },
  19361. enumerable: true,
  19362. configurable: true
  19363. });
  19364. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19365. get: function () {
  19366. return VertexBuffer._MatricesIndicesKind;
  19367. },
  19368. enumerable: true,
  19369. configurable: true
  19370. });
  19371. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19372. get: function () {
  19373. return VertexBuffer._MatricesWeightsKind;
  19374. },
  19375. enumerable: true,
  19376. configurable: true
  19377. });
  19378. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19379. get: function () {
  19380. return VertexBuffer._MatricesIndicesExtraKind;
  19381. },
  19382. enumerable: true,
  19383. configurable: true
  19384. });
  19385. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19386. get: function () {
  19387. return VertexBuffer._MatricesWeightsExtraKind;
  19388. },
  19389. enumerable: true,
  19390. configurable: true
  19391. });
  19392. // Enums
  19393. VertexBuffer._PositionKind = "position";
  19394. VertexBuffer._NormalKind = "normal";
  19395. VertexBuffer._UVKind = "uv";
  19396. VertexBuffer._UV2Kind = "uv2";
  19397. VertexBuffer._UV3Kind = "uv3";
  19398. VertexBuffer._UV4Kind = "uv4";
  19399. VertexBuffer._UV5Kind = "uv5";
  19400. VertexBuffer._UV6Kind = "uv6";
  19401. VertexBuffer._ColorKind = "color";
  19402. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19403. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19404. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19405. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19406. return VertexBuffer;
  19407. }());
  19408. BABYLON.VertexBuffer = VertexBuffer;
  19409. })(BABYLON || (BABYLON = {}));
  19410. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19411. var BABYLON;
  19412. (function (BABYLON) {
  19413. /**
  19414. * Creates an instance based on a source mesh.
  19415. */
  19416. var InstancedMesh = (function (_super) {
  19417. __extends(InstancedMesh, _super);
  19418. function InstancedMesh(name, source) {
  19419. _super.call(this, name, source.getScene());
  19420. source.instances.push(this);
  19421. this._sourceMesh = source;
  19422. this.position.copyFrom(source.position);
  19423. this.rotation.copyFrom(source.rotation);
  19424. this.scaling.copyFrom(source.scaling);
  19425. if (source.rotationQuaternion) {
  19426. this.rotationQuaternion = source.rotationQuaternion.clone();
  19427. }
  19428. this.infiniteDistance = source.infiniteDistance;
  19429. this.setPivotMatrix(source.getPivotMatrix());
  19430. this.refreshBoundingInfo();
  19431. this._syncSubMeshes();
  19432. }
  19433. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19434. // Methods
  19435. get: function () {
  19436. return this._sourceMesh.receiveShadows;
  19437. },
  19438. enumerable: true,
  19439. configurable: true
  19440. });
  19441. Object.defineProperty(InstancedMesh.prototype, "material", {
  19442. get: function () {
  19443. return this._sourceMesh.material;
  19444. },
  19445. enumerable: true,
  19446. configurable: true
  19447. });
  19448. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19449. get: function () {
  19450. return this._sourceMesh.visibility;
  19451. },
  19452. enumerable: true,
  19453. configurable: true
  19454. });
  19455. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19456. get: function () {
  19457. return this._sourceMesh.skeleton;
  19458. },
  19459. enumerable: true,
  19460. configurable: true
  19461. });
  19462. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19463. get: function () {
  19464. return this._sourceMesh.renderingGroupId;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. InstancedMesh.prototype.getTotalVertices = function () {
  19470. return this._sourceMesh.getTotalVertices();
  19471. };
  19472. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19473. get: function () {
  19474. return this._sourceMesh;
  19475. },
  19476. enumerable: true,
  19477. configurable: true
  19478. });
  19479. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19480. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19481. };
  19482. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19483. return this._sourceMesh.isVerticesDataPresent(kind);
  19484. };
  19485. InstancedMesh.prototype.getIndices = function () {
  19486. return this._sourceMesh.getIndices();
  19487. };
  19488. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19489. get: function () {
  19490. return this._sourceMesh._positions;
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19496. var meshBB = this._sourceMesh.getBoundingInfo();
  19497. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19498. this._updateBoundingInfo();
  19499. };
  19500. InstancedMesh.prototype._preActivate = function () {
  19501. if (this._currentLOD) {
  19502. this._currentLOD._preActivate();
  19503. }
  19504. };
  19505. InstancedMesh.prototype._activate = function (renderId) {
  19506. if (this._currentLOD) {
  19507. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19508. }
  19509. };
  19510. InstancedMesh.prototype.getLOD = function (camera) {
  19511. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19512. if (this._currentLOD === this.sourceMesh) {
  19513. return this;
  19514. }
  19515. return this._currentLOD;
  19516. };
  19517. InstancedMesh.prototype._syncSubMeshes = function () {
  19518. this.releaseSubMeshes();
  19519. if (this._sourceMesh.subMeshes) {
  19520. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19521. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19522. }
  19523. }
  19524. };
  19525. InstancedMesh.prototype._generatePointsArray = function () {
  19526. return this._sourceMesh._generatePointsArray();
  19527. };
  19528. // Clone
  19529. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19530. var result = this._sourceMesh.createInstance(name);
  19531. // Deep copy
  19532. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19533. // Bounding info
  19534. this.refreshBoundingInfo();
  19535. // Parent
  19536. if (newParent) {
  19537. result.parent = newParent;
  19538. }
  19539. if (!doNotCloneChildren) {
  19540. // Children
  19541. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19542. var mesh = this.getScene().meshes[index];
  19543. if (mesh.parent === this) {
  19544. mesh.clone(mesh.name, result);
  19545. }
  19546. }
  19547. }
  19548. result.computeWorldMatrix(true);
  19549. return result;
  19550. };
  19551. // Dispoe
  19552. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19553. // Remove from mesh
  19554. var index = this._sourceMesh.instances.indexOf(this);
  19555. this._sourceMesh.instances.splice(index, 1);
  19556. _super.prototype.dispose.call(this, doNotRecurse);
  19557. };
  19558. return InstancedMesh;
  19559. }(BABYLON.AbstractMesh));
  19560. BABYLON.InstancedMesh = InstancedMesh;
  19561. })(BABYLON || (BABYLON = {}));
  19562. //# sourceMappingURL=babylon.instancedMesh.js.map
  19563. var BABYLON;
  19564. (function (BABYLON) {
  19565. var _InstancesBatch = (function () {
  19566. function _InstancesBatch() {
  19567. this.mustReturn = false;
  19568. this.visibleInstances = new Array();
  19569. this.renderSelf = new Array();
  19570. }
  19571. return _InstancesBatch;
  19572. }());
  19573. BABYLON._InstancesBatch = _InstancesBatch;
  19574. var Mesh = (function (_super) {
  19575. __extends(Mesh, _super);
  19576. /**
  19577. * @constructor
  19578. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19579. * @param {Scene} scene The scene to add this mesh to.
  19580. * @param {Node} parent The parent of this mesh, if it has one
  19581. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19582. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19583. * When false, achieved by calling a clone(), also passing False.
  19584. * This will make creation of children, recursive.
  19585. */
  19586. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19587. if (parent === void 0) { parent = null; }
  19588. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19589. _super.call(this, name, scene);
  19590. // Events
  19591. /**
  19592. * An event triggered before rendering the mesh
  19593. * @type {BABYLON.Observable}
  19594. */
  19595. this.onBeforeRenderObservable = new BABYLON.Observable();
  19596. /**
  19597. * An event triggered after rendering the mesh
  19598. * @type {BABYLON.Observable}
  19599. */
  19600. this.onAfterRenderObservable = new BABYLON.Observable();
  19601. /**
  19602. * An event triggered before drawing the mesh
  19603. * @type {BABYLON.Observable}
  19604. */
  19605. this.onBeforeDrawObservable = new BABYLON.Observable();
  19606. // Members
  19607. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19608. this.instances = new Array();
  19609. this._LODLevels = new Array();
  19610. this._visibleInstances = {};
  19611. this._renderIdForInstances = new Array();
  19612. this._batchCache = new _InstancesBatch();
  19613. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19614. this._sideOrientation = Mesh._DEFAULTSIDE;
  19615. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19616. if (source) {
  19617. // Geometry
  19618. if (source._geometry) {
  19619. source._geometry.applyToMesh(this);
  19620. }
  19621. // Deep copy
  19622. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  19623. // Parent
  19624. this.parent = source.parent;
  19625. // Pivot
  19626. this.setPivotMatrix(source.getPivotMatrix());
  19627. this.id = name + "." + source.id;
  19628. // Material
  19629. this.material = source.material;
  19630. var index;
  19631. if (!doNotCloneChildren) {
  19632. // Children
  19633. for (index = 0; index < scene.meshes.length; index++) {
  19634. var mesh = scene.meshes[index];
  19635. if (mesh.parent === source) {
  19636. // doNotCloneChildren is always going to be False
  19637. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  19638. }
  19639. }
  19640. }
  19641. // Physics clone
  19642. var physicsEngine = this.getScene().getPhysicsEngine();
  19643. if (clonePhysicsImpostor && physicsEngine) {
  19644. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19645. if (impostor) {
  19646. this.physicsImpostor = impostor.clone(this);
  19647. }
  19648. }
  19649. // Particles
  19650. for (index = 0; index < scene.particleSystems.length; index++) {
  19651. var system = scene.particleSystems[index];
  19652. if (system.emitter === source) {
  19653. system.clone(system.name, this);
  19654. }
  19655. }
  19656. this.computeWorldMatrix(true);
  19657. }
  19658. // Parent
  19659. if (parent !== null) {
  19660. this.parent = parent;
  19661. }
  19662. }
  19663. Object.defineProperty(Mesh, "FRONTSIDE", {
  19664. /**
  19665. * Mesh side orientation : usually the external or front surface
  19666. */
  19667. get: function () {
  19668. return Mesh._FRONTSIDE;
  19669. },
  19670. enumerable: true,
  19671. configurable: true
  19672. });
  19673. Object.defineProperty(Mesh, "BACKSIDE", {
  19674. /**
  19675. * Mesh side orientation : usually the internal or back surface
  19676. */
  19677. get: function () {
  19678. return Mesh._BACKSIDE;
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19684. /**
  19685. * Mesh side orientation : both internal and external or front and back surfaces
  19686. */
  19687. get: function () {
  19688. return Mesh._DOUBLESIDE;
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19694. /**
  19695. * Mesh side orientation : by default, `FRONTSIDE`
  19696. */
  19697. get: function () {
  19698. return Mesh._DEFAULTSIDE;
  19699. },
  19700. enumerable: true,
  19701. configurable: true
  19702. });
  19703. Object.defineProperty(Mesh, "NO_CAP", {
  19704. /**
  19705. * Mesh cap setting : no cap
  19706. */
  19707. get: function () {
  19708. return Mesh._NO_CAP;
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(Mesh, "CAP_START", {
  19714. /**
  19715. * Mesh cap setting : one cap at the beginning of the mesh
  19716. */
  19717. get: function () {
  19718. return Mesh._CAP_START;
  19719. },
  19720. enumerable: true,
  19721. configurable: true
  19722. });
  19723. Object.defineProperty(Mesh, "CAP_END", {
  19724. /**
  19725. * Mesh cap setting : one cap at the end of the mesh
  19726. */
  19727. get: function () {
  19728. return Mesh._CAP_END;
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(Mesh, "CAP_ALL", {
  19734. /**
  19735. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19736. */
  19737. get: function () {
  19738. return Mesh._CAP_ALL;
  19739. },
  19740. enumerable: true,
  19741. configurable: true
  19742. });
  19743. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19744. set: function (callback) {
  19745. if (this._onBeforeDrawObserver) {
  19746. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19747. }
  19748. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19749. },
  19750. enumerable: true,
  19751. configurable: true
  19752. });
  19753. // Methods
  19754. /**
  19755. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19756. */
  19757. Mesh.prototype.toString = function (fullDetails) {
  19758. var ret = _super.prototype.toString.call(this, fullDetails);
  19759. ret += ", n vertices: " + this.getTotalVertices();
  19760. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19761. if (this.animations) {
  19762. for (var i = 0; i < this.animations.length; i++) {
  19763. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19764. }
  19765. }
  19766. if (fullDetails) {
  19767. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19768. }
  19769. return ret;
  19770. };
  19771. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19772. get: function () {
  19773. return this._LODLevels.length > 0;
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. Mesh.prototype._sortLODLevels = function () {
  19779. this._LODLevels.sort(function (a, b) {
  19780. if (a.distance < b.distance) {
  19781. return 1;
  19782. }
  19783. if (a.distance > b.distance) {
  19784. return -1;
  19785. }
  19786. return 0;
  19787. });
  19788. };
  19789. /**
  19790. * Add a mesh as LOD level triggered at the given distance.
  19791. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19792. * @param {number} distance The distance from the center of the object to show this level
  19793. * @param {Mesh} mesh The mesh to be added as LOD level
  19794. * @return {Mesh} This mesh (for chaining)
  19795. */
  19796. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19797. if (mesh && mesh._masterMesh) {
  19798. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19799. return this;
  19800. }
  19801. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19802. this._LODLevels.push(level);
  19803. if (mesh) {
  19804. mesh._masterMesh = this;
  19805. }
  19806. this._sortLODLevels();
  19807. return this;
  19808. };
  19809. /**
  19810. * Returns the LOD level mesh at the passed distance or null if not found.
  19811. * It is related to the method `addLODLevel(distance, mesh)`.
  19812. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19813. */
  19814. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19815. for (var index = 0; index < this._LODLevels.length; index++) {
  19816. var level = this._LODLevels[index];
  19817. if (level.distance === distance) {
  19818. return level.mesh;
  19819. }
  19820. }
  19821. return null;
  19822. };
  19823. /**
  19824. * Remove a mesh from the LOD array
  19825. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19826. * @param {Mesh} mesh The mesh to be removed.
  19827. * @return {Mesh} This mesh (for chaining)
  19828. */
  19829. Mesh.prototype.removeLODLevel = function (mesh) {
  19830. for (var index = 0; index < this._LODLevels.length; index++) {
  19831. if (this._LODLevels[index].mesh === mesh) {
  19832. this._LODLevels.splice(index, 1);
  19833. if (mesh) {
  19834. mesh._masterMesh = null;
  19835. }
  19836. }
  19837. }
  19838. this._sortLODLevels();
  19839. return this;
  19840. };
  19841. /**
  19842. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19843. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19844. */
  19845. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19846. if (!this._LODLevels || this._LODLevels.length === 0) {
  19847. return this;
  19848. }
  19849. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19850. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19851. if (this.onLODLevelSelection) {
  19852. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19853. }
  19854. return this;
  19855. }
  19856. for (var index = 0; index < this._LODLevels.length; index++) {
  19857. var level = this._LODLevels[index];
  19858. if (level.distance < distanceToCamera) {
  19859. if (level.mesh) {
  19860. level.mesh._preActivate();
  19861. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19862. }
  19863. if (this.onLODLevelSelection) {
  19864. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19865. }
  19866. return level.mesh;
  19867. }
  19868. }
  19869. if (this.onLODLevelSelection) {
  19870. this.onLODLevelSelection(distanceToCamera, this, this);
  19871. }
  19872. return this;
  19873. };
  19874. Object.defineProperty(Mesh.prototype, "geometry", {
  19875. /**
  19876. * Returns the mesh internal Geometry object.
  19877. */
  19878. get: function () {
  19879. return this._geometry;
  19880. },
  19881. enumerable: true,
  19882. configurable: true
  19883. });
  19884. /**
  19885. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19886. */
  19887. Mesh.prototype.getTotalVertices = function () {
  19888. if (!this._geometry) {
  19889. return 0;
  19890. }
  19891. return this._geometry.getTotalVertices();
  19892. };
  19893. /**
  19894. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19895. * 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.
  19896. * Returns null if the mesh has no geometry or no vertex buffer.
  19897. * Possible `kind` values :
  19898. * - BABYLON.VertexBuffer.PositionKind
  19899. * - BABYLON.VertexBuffer.UVKind
  19900. * - BABYLON.VertexBuffer.UV2Kind
  19901. * - BABYLON.VertexBuffer.UV3Kind
  19902. * - BABYLON.VertexBuffer.UV4Kind
  19903. * - BABYLON.VertexBuffer.UV5Kind
  19904. * - BABYLON.VertexBuffer.UV6Kind
  19905. * - BABYLON.VertexBuffer.ColorKind
  19906. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19907. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19908. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19909. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19910. */
  19911. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19912. if (!this._geometry) {
  19913. return null;
  19914. }
  19915. return this._geometry.getVerticesData(kind, copyWhenShared);
  19916. };
  19917. /**
  19918. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19919. * Returns `undefined` if the mesh has no geometry.
  19920. * Possible `kind` values :
  19921. * - BABYLON.VertexBuffer.PositionKind
  19922. * - BABYLON.VertexBuffer.UVKind
  19923. * - BABYLON.VertexBuffer.UV2Kind
  19924. * - BABYLON.VertexBuffer.UV3Kind
  19925. * - BABYLON.VertexBuffer.UV4Kind
  19926. * - BABYLON.VertexBuffer.UV5Kind
  19927. * - BABYLON.VertexBuffer.UV6Kind
  19928. * - BABYLON.VertexBuffer.ColorKind
  19929. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19930. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19931. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19932. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19933. */
  19934. Mesh.prototype.getVertexBuffer = function (kind) {
  19935. if (!this._geometry) {
  19936. return undefined;
  19937. }
  19938. return this._geometry.getVertexBuffer(kind);
  19939. };
  19940. /**
  19941. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19942. * Possible `kind` values :
  19943. * - BABYLON.VertexBuffer.PositionKind
  19944. * - BABYLON.VertexBuffer.UVKind
  19945. * - BABYLON.VertexBuffer.UV2Kind
  19946. * - BABYLON.VertexBuffer.UV3Kind
  19947. * - BABYLON.VertexBuffer.UV4Kind
  19948. * - BABYLON.VertexBuffer.UV5Kind
  19949. * - BABYLON.VertexBuffer.UV6Kind
  19950. * - BABYLON.VertexBuffer.ColorKind
  19951. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19952. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19953. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19954. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19955. */
  19956. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19957. if (!this._geometry) {
  19958. if (this._delayInfo) {
  19959. return this._delayInfo.indexOf(kind) !== -1;
  19960. }
  19961. return false;
  19962. }
  19963. return this._geometry.isVerticesDataPresent(kind);
  19964. };
  19965. /**
  19966. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19967. * Possible `kind` values :
  19968. * - BABYLON.VertexBuffer.PositionKind
  19969. * - BABYLON.VertexBuffer.UVKind
  19970. * - BABYLON.VertexBuffer.UV2Kind
  19971. * - BABYLON.VertexBuffer.UV3Kind
  19972. * - BABYLON.VertexBuffer.UV4Kind
  19973. * - BABYLON.VertexBuffer.UV5Kind
  19974. * - BABYLON.VertexBuffer.UV6Kind
  19975. * - BABYLON.VertexBuffer.ColorKind
  19976. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19977. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19978. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19979. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19980. */
  19981. Mesh.prototype.getVerticesDataKinds = function () {
  19982. if (!this._geometry) {
  19983. var result = [];
  19984. if (this._delayInfo) {
  19985. this._delayInfo.forEach(function (kind, index, array) {
  19986. result.push(kind);
  19987. });
  19988. }
  19989. return result;
  19990. }
  19991. return this._geometry.getVerticesDataKinds();
  19992. };
  19993. /**
  19994. * Returns a positive integer : the total number of indices in this mesh geometry.
  19995. * Returns zero if the mesh has no geometry.
  19996. */
  19997. Mesh.prototype.getTotalIndices = function () {
  19998. if (!this._geometry) {
  19999. return 0;
  20000. }
  20001. return this._geometry.getTotalIndices();
  20002. };
  20003. /**
  20004. * Returns an array of integers or a Int32Array populated with the mesh indices.
  20005. * 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.
  20006. * Returns an empty array if the mesh has no geometry.
  20007. */
  20008. Mesh.prototype.getIndices = function (copyWhenShared) {
  20009. if (!this._geometry) {
  20010. return [];
  20011. }
  20012. return this._geometry.getIndices(copyWhenShared);
  20013. };
  20014. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20015. get: function () {
  20016. return this._masterMesh !== null && this._masterMesh !== undefined;
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. /**
  20022. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20023. */
  20024. Mesh.prototype.isReady = function () {
  20025. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20026. return false;
  20027. }
  20028. return _super.prototype.isReady.call(this);
  20029. };
  20030. /**
  20031. * Boolean : true if the mesh has been disposed.
  20032. */
  20033. Mesh.prototype.isDisposed = function () {
  20034. return this._isDisposed;
  20035. };
  20036. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20037. get: function () {
  20038. return this._sideOrientation;
  20039. },
  20040. /**
  20041. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20042. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20043. */
  20044. set: function (sideO) {
  20045. this._sideOrientation = sideO;
  20046. },
  20047. enumerable: true,
  20048. configurable: true
  20049. });
  20050. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20051. /**
  20052. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20053. * This property is pertinent only for updatable parametric shapes.
  20054. */
  20055. get: function () {
  20056. return this._areNormalsFrozen;
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. /**
  20062. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20063. * It has no effect at all on other shapes.
  20064. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20065. */
  20066. Mesh.prototype.freezeNormals = function () {
  20067. this._areNormalsFrozen = true;
  20068. };
  20069. /**
  20070. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20071. * It has no effect at all on other shapes.
  20072. * It reactivates the mesh normals computation if it was previously frozen.
  20073. */
  20074. Mesh.prototype.unfreezeNormals = function () {
  20075. this._areNormalsFrozen = false;
  20076. };
  20077. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20078. /**
  20079. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20080. */
  20081. set: function (count) {
  20082. this._overridenInstanceCount = count;
  20083. },
  20084. enumerable: true,
  20085. configurable: true
  20086. });
  20087. // Methods
  20088. Mesh.prototype._preActivate = function () {
  20089. var sceneRenderId = this.getScene().getRenderId();
  20090. if (this._preActivateId === sceneRenderId) {
  20091. return;
  20092. }
  20093. this._preActivateId = sceneRenderId;
  20094. this._visibleInstances = null;
  20095. };
  20096. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20097. if (this._visibleInstances) {
  20098. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20099. }
  20100. };
  20101. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20102. if (!this._visibleInstances) {
  20103. this._visibleInstances = {};
  20104. this._visibleInstances.defaultRenderId = renderId;
  20105. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20106. }
  20107. if (!this._visibleInstances[renderId]) {
  20108. this._visibleInstances[renderId] = new Array();
  20109. }
  20110. this._visibleInstances[renderId].push(instance);
  20111. };
  20112. /**
  20113. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20114. * This means the mesh underlying bounding box and sphere are recomputed.
  20115. */
  20116. Mesh.prototype.refreshBoundingInfo = function () {
  20117. if (this._boundingInfo.isLocked) {
  20118. return;
  20119. }
  20120. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20121. if (data) {
  20122. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20123. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20124. }
  20125. if (this.subMeshes) {
  20126. for (var index = 0; index < this.subMeshes.length; index++) {
  20127. this.subMeshes[index].refreshBoundingInfo();
  20128. }
  20129. }
  20130. this._updateBoundingInfo();
  20131. };
  20132. Mesh.prototype._createGlobalSubMesh = function () {
  20133. var totalVertices = this.getTotalVertices();
  20134. if (!totalVertices || !this.getIndices()) {
  20135. return null;
  20136. }
  20137. this.releaseSubMeshes();
  20138. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20139. };
  20140. Mesh.prototype.subdivide = function (count) {
  20141. if (count < 1) {
  20142. return;
  20143. }
  20144. var totalIndices = this.getTotalIndices();
  20145. var subdivisionSize = (totalIndices / count) | 0;
  20146. var offset = 0;
  20147. // Ensure that subdivisionSize is a multiple of 3
  20148. while (subdivisionSize % 3 !== 0) {
  20149. subdivisionSize++;
  20150. }
  20151. this.releaseSubMeshes();
  20152. for (var index = 0; index < count; index++) {
  20153. if (offset >= totalIndices) {
  20154. break;
  20155. }
  20156. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20157. offset += subdivisionSize;
  20158. }
  20159. this.synchronizeInstances();
  20160. };
  20161. /**
  20162. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20163. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20164. * The `data` are either a numeric array either a Float32Array.
  20165. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20166. * 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).
  20167. * Note that a new underlying VertexBuffer object is created each call.
  20168. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20169. *
  20170. * Possible `kind` values :
  20171. * - BABYLON.VertexBuffer.PositionKind
  20172. * - BABYLON.VertexBuffer.UVKind
  20173. * - BABYLON.VertexBuffer.UV2Kind
  20174. * - BABYLON.VertexBuffer.UV3Kind
  20175. * - BABYLON.VertexBuffer.UV4Kind
  20176. * - BABYLON.VertexBuffer.UV5Kind
  20177. * - BABYLON.VertexBuffer.UV6Kind
  20178. * - BABYLON.VertexBuffer.ColorKind
  20179. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20180. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20181. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20182. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20183. */
  20184. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20185. if (!this._geometry) {
  20186. var vertexData = new BABYLON.VertexData();
  20187. vertexData.set(data, kind);
  20188. var scene = this.getScene();
  20189. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20190. }
  20191. else {
  20192. this._geometry.setVerticesData(kind, data, updatable, stride);
  20193. }
  20194. };
  20195. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20196. if (!this._geometry) {
  20197. var scene = this.getScene();
  20198. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20199. }
  20200. this._geometry.setVerticesBuffer(buffer);
  20201. };
  20202. /**
  20203. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20204. * If the mesh has no geometry, it is simply returned as it is.
  20205. * The `data` are either a numeric array either a Float32Array.
  20206. * No new underlying VertexBuffer object is created.
  20207. * 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.
  20208. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20209. *
  20210. * Possible `kind` values :
  20211. * - BABYLON.VertexBuffer.PositionKind
  20212. * - BABYLON.VertexBuffer.UVKind
  20213. * - BABYLON.VertexBuffer.UV2Kind
  20214. * - BABYLON.VertexBuffer.UV3Kind
  20215. * - BABYLON.VertexBuffer.UV4Kind
  20216. * - BABYLON.VertexBuffer.UV5Kind
  20217. * - BABYLON.VertexBuffer.UV6Kind
  20218. * - BABYLON.VertexBuffer.ColorKind
  20219. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20220. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20221. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20222. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20223. */
  20224. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20225. if (!this._geometry) {
  20226. return;
  20227. }
  20228. if (!makeItUnique) {
  20229. this._geometry.updateVerticesData(kind, data, updateExtends);
  20230. }
  20231. else {
  20232. this.makeGeometryUnique();
  20233. this.updateVerticesData(kind, data, updateExtends, false);
  20234. }
  20235. };
  20236. /**
  20237. * Deprecated since BabylonJS v2.3
  20238. */
  20239. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20240. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20241. if (!this._geometry) {
  20242. return;
  20243. }
  20244. if (!makeItUnique) {
  20245. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20246. }
  20247. else {
  20248. this.makeGeometryUnique();
  20249. this.updateVerticesDataDirectly(kind, data, offset, false);
  20250. }
  20251. };
  20252. /**
  20253. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20254. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20255. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20256. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20257. */
  20258. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20259. if (computeNormals === void 0) { computeNormals = true; }
  20260. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20261. positionFunction(positions);
  20262. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20263. if (computeNormals) {
  20264. var indices = this.getIndices();
  20265. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20266. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20267. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20268. }
  20269. };
  20270. Mesh.prototype.makeGeometryUnique = function () {
  20271. if (!this._geometry) {
  20272. return;
  20273. }
  20274. var oldGeometry = this._geometry;
  20275. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20276. oldGeometry.releaseForMesh(this, true);
  20277. geometry.applyToMesh(this);
  20278. };
  20279. /**
  20280. * Sets the mesh indices.
  20281. * Expects an array populated with integers or a Int32Array.
  20282. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20283. * This method creates a new index buffer each call.
  20284. */
  20285. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20286. if (!this._geometry) {
  20287. var vertexData = new BABYLON.VertexData();
  20288. vertexData.indices = indices;
  20289. var scene = this.getScene();
  20290. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20291. }
  20292. else {
  20293. this._geometry.setIndices(indices, totalVertices);
  20294. }
  20295. };
  20296. /**
  20297. * Invert the geometry to move from a right handed system to a left handed one.
  20298. */
  20299. Mesh.prototype.toLeftHanded = function () {
  20300. if (!this._geometry) {
  20301. return;
  20302. }
  20303. this._geometry.toLeftHanded();
  20304. };
  20305. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20306. var engine = this.getScene().getEngine();
  20307. // Wireframe
  20308. var indexToBind;
  20309. if (this._unIndexed) {
  20310. indexToBind = null;
  20311. }
  20312. else {
  20313. switch (fillMode) {
  20314. case BABYLON.Material.PointFillMode:
  20315. indexToBind = null;
  20316. break;
  20317. case BABYLON.Material.WireFrameFillMode:
  20318. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20319. break;
  20320. default:
  20321. case BABYLON.Material.TriangleFillMode:
  20322. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20323. break;
  20324. }
  20325. }
  20326. // VBOs
  20327. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  20328. };
  20329. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20330. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20331. return;
  20332. }
  20333. this.onBeforeDrawObservable.notifyObservers(this);
  20334. var engine = this.getScene().getEngine();
  20335. // Draw order
  20336. switch (fillMode) {
  20337. case BABYLON.Material.PointFillMode:
  20338. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20339. break;
  20340. case BABYLON.Material.WireFrameFillMode:
  20341. if (this._unIndexed) {
  20342. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20343. }
  20344. else {
  20345. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20346. }
  20347. break;
  20348. default:
  20349. if (this._unIndexed) {
  20350. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20351. }
  20352. else {
  20353. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20354. }
  20355. }
  20356. };
  20357. /**
  20358. * Registers for this mesh a javascript function called just before the rendering process.
  20359. * This function is passed the current mesh and doesn't return anything.
  20360. */
  20361. Mesh.prototype.registerBeforeRender = function (func) {
  20362. this.onBeforeRenderObservable.add(func);
  20363. };
  20364. /**
  20365. * Disposes a previously registered javascript function called before the rendering.
  20366. * This function is passed the current mesh and doesn't return anything.
  20367. */
  20368. Mesh.prototype.unregisterBeforeRender = function (func) {
  20369. this.onBeforeRenderObservable.removeCallback(func);
  20370. };
  20371. /**
  20372. * Registers for this mesh a javascript function called just after the rendering is complete.
  20373. * This function is passed the current mesh and doesn't return anything.
  20374. */
  20375. Mesh.prototype.registerAfterRender = function (func) {
  20376. this.onAfterRenderObservable.add(func);
  20377. };
  20378. /**
  20379. * Disposes a previously registered javascript function called after the rendering.
  20380. * This function is passed the current mesh and doesn't return anything.
  20381. */
  20382. Mesh.prototype.unregisterAfterRender = function (func) {
  20383. this.onAfterRenderObservable.removeCallback(func);
  20384. };
  20385. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20386. var scene = this.getScene();
  20387. this._batchCache.mustReturn = false;
  20388. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20389. this._batchCache.visibleInstances[subMeshId] = null;
  20390. if (this._visibleInstances) {
  20391. var currentRenderId = scene.getRenderId();
  20392. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20393. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20394. var selfRenderId = this._renderId;
  20395. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20396. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20397. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20398. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20399. }
  20400. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20401. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20402. this._batchCache.mustReturn = true;
  20403. return this._batchCache;
  20404. }
  20405. if (currentRenderId !== selfRenderId) {
  20406. this._batchCache.renderSelf[subMeshId] = false;
  20407. }
  20408. }
  20409. this._renderIdForInstances[subMeshId] = currentRenderId;
  20410. }
  20411. return this._batchCache;
  20412. };
  20413. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20414. var visibleInstances = batch.visibleInstances[subMesh._id];
  20415. var matricesCount = visibleInstances.length + 1;
  20416. var bufferSize = matricesCount * 16 * 4;
  20417. var currentInstancesBufferSize = this._instancesBufferSize;
  20418. var instancesBuffer = this._instancesBuffer;
  20419. while (this._instancesBufferSize < bufferSize) {
  20420. this._instancesBufferSize *= 2;
  20421. }
  20422. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20423. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20424. }
  20425. var offset = 0;
  20426. var instancesCount = 0;
  20427. var world = this.getWorldMatrix();
  20428. if (batch.renderSelf[subMesh._id]) {
  20429. world.copyToArray(this._instancesData, offset);
  20430. offset += 16;
  20431. instancesCount++;
  20432. }
  20433. if (visibleInstances) {
  20434. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20435. var instance = visibleInstances[instanceIndex];
  20436. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20437. offset += 16;
  20438. instancesCount++;
  20439. }
  20440. }
  20441. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20442. if (instancesBuffer) {
  20443. instancesBuffer.dispose();
  20444. }
  20445. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20446. this._instancesBuffer = instancesBuffer;
  20447. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20448. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20449. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20450. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20451. }
  20452. else {
  20453. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20454. }
  20455. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20456. this._draw(subMesh, fillMode, instancesCount);
  20457. engine.unbindInstanceAttributes();
  20458. };
  20459. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20460. var scene = this.getScene();
  20461. var engine = scene.getEngine();
  20462. if (hardwareInstancedRendering) {
  20463. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20464. }
  20465. else {
  20466. if (batch.renderSelf[subMesh._id]) {
  20467. // Draw
  20468. if (onBeforeDraw) {
  20469. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20470. }
  20471. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20472. }
  20473. if (batch.visibleInstances[subMesh._id]) {
  20474. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20475. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20476. // World
  20477. var world = instance.getWorldMatrix();
  20478. if (onBeforeDraw) {
  20479. onBeforeDraw(true, world, effectiveMaterial);
  20480. }
  20481. // Draw
  20482. this._draw(subMesh, fillMode);
  20483. }
  20484. }
  20485. }
  20486. };
  20487. /**
  20488. * Triggers the draw call for the mesh.
  20489. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20490. */
  20491. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20492. var scene = this.getScene();
  20493. // Managing instances
  20494. var batch = this._getInstancesRenderList(subMesh._id);
  20495. if (batch.mustReturn) {
  20496. return;
  20497. }
  20498. // Checking geometry state
  20499. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20500. return;
  20501. }
  20502. var callbackIndex;
  20503. this.onBeforeRenderObservable.notifyObservers(this);
  20504. var engine = scene.getEngine();
  20505. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20506. // Material
  20507. var effectiveMaterial = subMesh.getMaterial();
  20508. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20509. return;
  20510. }
  20511. // Outline - step 1
  20512. var savedDepthWrite = engine.getDepthWrite();
  20513. if (this.renderOutline) {
  20514. engine.setDepthWrite(false);
  20515. scene.getOutlineRenderer().render(subMesh, batch);
  20516. engine.setDepthWrite(savedDepthWrite);
  20517. }
  20518. effectiveMaterial._preBind();
  20519. var effect = effectiveMaterial.getEffect();
  20520. // Bind
  20521. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20522. this._bind(subMesh, effect, fillMode);
  20523. var world = this.getWorldMatrix();
  20524. effectiveMaterial.bind(world, this);
  20525. // Alpha mode
  20526. if (enableAlphaMode) {
  20527. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20528. }
  20529. // Draw
  20530. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20531. // Unbind
  20532. effectiveMaterial.unbind();
  20533. // Outline - step 2
  20534. if (this.renderOutline && savedDepthWrite) {
  20535. engine.setDepthWrite(true);
  20536. engine.setColorWrite(false);
  20537. scene.getOutlineRenderer().render(subMesh, batch);
  20538. engine.setColorWrite(true);
  20539. }
  20540. // Overlay
  20541. if (this.renderOverlay) {
  20542. var currentMode = engine.getAlphaMode();
  20543. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20544. scene.getOutlineRenderer().render(subMesh, batch, true);
  20545. engine.setAlphaMode(currentMode);
  20546. }
  20547. this.onAfterRenderObservable.notifyObservers(this);
  20548. };
  20549. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20550. if (isInstance) {
  20551. effectiveMaterial.bindOnlyWorldMatrix(world);
  20552. }
  20553. };
  20554. /**
  20555. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20556. */
  20557. Mesh.prototype.getEmittedParticleSystems = function () {
  20558. var results = new Array();
  20559. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20560. var particleSystem = this.getScene().particleSystems[index];
  20561. if (particleSystem.emitter === this) {
  20562. results.push(particleSystem);
  20563. }
  20564. }
  20565. return results;
  20566. };
  20567. /**
  20568. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20569. */
  20570. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20571. var results = new Array();
  20572. var descendants = this.getDescendants();
  20573. descendants.push(this);
  20574. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20575. var particleSystem = this.getScene().particleSystems[index];
  20576. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20577. results.push(particleSystem);
  20578. }
  20579. }
  20580. return results;
  20581. };
  20582. Mesh.prototype._checkDelayState = function () {
  20583. var scene = this.getScene();
  20584. if (this._geometry) {
  20585. this._geometry.load(scene);
  20586. }
  20587. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20588. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20589. this._queueLoad(this, scene);
  20590. }
  20591. };
  20592. Mesh.prototype._queueLoad = function (mesh, scene) {
  20593. var _this = this;
  20594. scene._addPendingData(mesh);
  20595. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20596. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20597. if (data instanceof ArrayBuffer) {
  20598. _this._delayLoadingFunction(data, _this);
  20599. }
  20600. else {
  20601. _this._delayLoadingFunction(JSON.parse(data), _this);
  20602. }
  20603. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20604. scene._removePendingData(_this);
  20605. }, function () { }, scene.database, getBinaryData);
  20606. };
  20607. /**
  20608. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20609. */
  20610. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20611. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20612. return false;
  20613. }
  20614. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20615. return false;
  20616. }
  20617. this._checkDelayState();
  20618. return true;
  20619. };
  20620. /**
  20621. * Sets the mesh material by the material or multiMaterial `id` property.
  20622. * The material `id` is a string identifying the material or the multiMaterial.
  20623. * This method returns nothing.
  20624. */
  20625. Mesh.prototype.setMaterialByID = function (id) {
  20626. var materials = this.getScene().materials;
  20627. var index;
  20628. for (index = 0; index < materials.length; index++) {
  20629. if (materials[index].id === id) {
  20630. this.material = materials[index];
  20631. return;
  20632. }
  20633. }
  20634. // Multi
  20635. var multiMaterials = this.getScene().multiMaterials;
  20636. for (index = 0; index < multiMaterials.length; index++) {
  20637. if (multiMaterials[index].id === id) {
  20638. this.material = multiMaterials[index];
  20639. return;
  20640. }
  20641. }
  20642. };
  20643. /**
  20644. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20645. */
  20646. Mesh.prototype.getAnimatables = function () {
  20647. var results = [];
  20648. if (this.material) {
  20649. results.push(this.material);
  20650. }
  20651. if (this.skeleton) {
  20652. results.push(this.skeleton);
  20653. }
  20654. return results;
  20655. };
  20656. /**
  20657. * Modifies the mesh geometry according to the passed transformation matrix.
  20658. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20659. * The mesh normals are modified accordingly the same transformation.
  20660. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20661. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20662. */
  20663. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20664. // Position
  20665. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20666. return;
  20667. }
  20668. var submeshes = this.subMeshes.splice(0);
  20669. this._resetPointsArrayCache();
  20670. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20671. var temp = [];
  20672. var index;
  20673. for (index = 0; index < data.length; index += 3) {
  20674. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20675. }
  20676. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20677. // Normals
  20678. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20679. return;
  20680. }
  20681. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20682. temp = [];
  20683. for (index = 0; index < data.length; index += 3) {
  20684. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20685. }
  20686. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20687. // flip faces?
  20688. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20689. this.flipFaces();
  20690. }
  20691. // Restore submeshes
  20692. this.releaseSubMeshes();
  20693. this.subMeshes = submeshes;
  20694. };
  20695. /**
  20696. * Modifies the mesh geometry according to its own current World Matrix.
  20697. * The mesh World Matrix is then reset.
  20698. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20699. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20700. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20701. */
  20702. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20703. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20704. this.scaling.copyFromFloats(1, 1, 1);
  20705. this.position.copyFromFloats(0, 0, 0);
  20706. this.rotation.copyFromFloats(0, 0, 0);
  20707. //only if quaternion is already set
  20708. if (this.rotationQuaternion) {
  20709. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20710. }
  20711. this._worldMatrix = BABYLON.Matrix.Identity();
  20712. };
  20713. // Cache
  20714. Mesh.prototype._resetPointsArrayCache = function () {
  20715. this._positions = null;
  20716. };
  20717. Mesh.prototype._generatePointsArray = function () {
  20718. if (this._positions)
  20719. return true;
  20720. this._positions = [];
  20721. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20722. if (!data) {
  20723. return false;
  20724. }
  20725. for (var index = 0; index < data.length; index += 3) {
  20726. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20727. }
  20728. return true;
  20729. };
  20730. /**
  20731. * Returns a new Mesh object generated from the current mesh properties.
  20732. * This method must not get confused with createInstance().
  20733. * The parameter `name` is a string, the name given to the new mesh.
  20734. * The optional parameter `newParent` can be any Node object (default `null`).
  20735. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20736. * 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.
  20737. */
  20738. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20739. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20740. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20741. };
  20742. /**
  20743. * Disposes the mesh.
  20744. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20745. */
  20746. Mesh.prototype.dispose = function (doNotRecurse) {
  20747. if (this._geometry) {
  20748. this._geometry.releaseForMesh(this, true);
  20749. }
  20750. // Instances
  20751. if (this._instancesBuffer) {
  20752. this._instancesBuffer.dispose();
  20753. this._instancesBuffer = null;
  20754. }
  20755. while (this.instances.length) {
  20756. this.instances[0].dispose();
  20757. }
  20758. // Highlight layers.
  20759. var highlightLayers = this.getScene().highlightLayers;
  20760. for (var i = 0; i < highlightLayers.length; i++) {
  20761. var highlightLayer = highlightLayers[i];
  20762. if (highlightLayer) {
  20763. highlightLayer.removeMesh(this);
  20764. highlightLayer.removeExcludedMesh(this);
  20765. }
  20766. }
  20767. _super.prototype.dispose.call(this, doNotRecurse);
  20768. };
  20769. /**
  20770. * Modifies the mesh geometry according to a displacement map.
  20771. * 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.
  20772. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20773. * This method returns nothing.
  20774. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20775. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20776. * 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.
  20777. */
  20778. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20779. var _this = this;
  20780. var scene = this.getScene();
  20781. var onload = function (img) {
  20782. // Getting height map data
  20783. var canvas = document.createElement("canvas");
  20784. var context = canvas.getContext("2d");
  20785. var heightMapWidth = img.width;
  20786. var heightMapHeight = img.height;
  20787. canvas.width = heightMapWidth;
  20788. canvas.height = heightMapHeight;
  20789. context.drawImage(img, 0, 0);
  20790. // Create VertexData from map data
  20791. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20792. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20793. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20794. //execute success callback, if set
  20795. if (onSuccess) {
  20796. onSuccess(_this);
  20797. }
  20798. };
  20799. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20800. };
  20801. /**
  20802. * Modifies the mesh geometry according to a displacementMap buffer.
  20803. * 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.
  20804. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20805. * This method returns nothing.
  20806. * 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.
  20807. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20808. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20809. */
  20810. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20811. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20812. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20813. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20814. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20815. return;
  20816. }
  20817. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20818. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20819. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20820. var position = BABYLON.Vector3.Zero();
  20821. var normal = BABYLON.Vector3.Zero();
  20822. var uv = BABYLON.Vector2.Zero();
  20823. for (var index = 0; index < positions.length; index += 3) {
  20824. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20825. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20826. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20827. // Compute height
  20828. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20829. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20830. var pos = (u + v * heightMapWidth) * 4;
  20831. var r = buffer[pos] / 255.0;
  20832. var g = buffer[pos + 1] / 255.0;
  20833. var b = buffer[pos + 2] / 255.0;
  20834. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20835. normal.normalize();
  20836. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20837. position = position.add(normal);
  20838. position.toArray(positions, index);
  20839. }
  20840. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20841. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20842. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20843. };
  20844. /**
  20845. * Modify the mesh to get a flat shading rendering.
  20846. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20847. * This method returns nothing.
  20848. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20849. */
  20850. Mesh.prototype.convertToFlatShadedMesh = function () {
  20851. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20852. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20853. var kinds = this.getVerticesDataKinds();
  20854. var vbs = [];
  20855. var data = [];
  20856. var newdata = [];
  20857. var updatableNormals = false;
  20858. var kindIndex;
  20859. var kind;
  20860. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20861. kind = kinds[kindIndex];
  20862. var vertexBuffer = this.getVertexBuffer(kind);
  20863. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20864. updatableNormals = vertexBuffer.isUpdatable();
  20865. kinds.splice(kindIndex, 1);
  20866. kindIndex--;
  20867. continue;
  20868. }
  20869. vbs[kind] = vertexBuffer;
  20870. data[kind] = vbs[kind].getData();
  20871. newdata[kind] = [];
  20872. }
  20873. // Save previous submeshes
  20874. var previousSubmeshes = this.subMeshes.slice(0);
  20875. var indices = this.getIndices();
  20876. var totalIndices = this.getTotalIndices();
  20877. // Generating unique vertices per face
  20878. var index;
  20879. for (index = 0; index < totalIndices; index++) {
  20880. var vertexIndex = indices[index];
  20881. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20882. kind = kinds[kindIndex];
  20883. var stride = vbs[kind].getStrideSize();
  20884. for (var offset = 0; offset < stride; offset++) {
  20885. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20886. }
  20887. }
  20888. }
  20889. // Updating faces & normal
  20890. var normals = [];
  20891. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20892. for (index = 0; index < totalIndices; index += 3) {
  20893. indices[index] = index;
  20894. indices[index + 1] = index + 1;
  20895. indices[index + 2] = index + 2;
  20896. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20897. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20898. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20899. var p1p2 = p1.subtract(p2);
  20900. var p3p2 = p3.subtract(p2);
  20901. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20902. // Store same normals for every vertex
  20903. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20904. normals.push(normal.x);
  20905. normals.push(normal.y);
  20906. normals.push(normal.z);
  20907. }
  20908. }
  20909. this.setIndices(indices);
  20910. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20911. // Updating vertex buffers
  20912. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20913. kind = kinds[kindIndex];
  20914. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20915. }
  20916. // Updating submeshes
  20917. this.releaseSubMeshes();
  20918. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20919. var previousOne = previousSubmeshes[submeshIndex];
  20920. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20921. }
  20922. this.synchronizeInstances();
  20923. };
  20924. /**
  20925. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20926. * In other words, more vertices, no more indices and a single bigger VBO.
  20927. * This method returns nothing.
  20928. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20929. *
  20930. */
  20931. Mesh.prototype.convertToUnIndexedMesh = function () {
  20932. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20933. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20934. var kinds = this.getVerticesDataKinds();
  20935. var vbs = [];
  20936. var data = [];
  20937. var newdata = [];
  20938. var updatableNormals = false;
  20939. var kindIndex;
  20940. var kind;
  20941. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20942. kind = kinds[kindIndex];
  20943. var vertexBuffer = this.getVertexBuffer(kind);
  20944. vbs[kind] = vertexBuffer;
  20945. data[kind] = vbs[kind].getData();
  20946. newdata[kind] = [];
  20947. }
  20948. // Save previous submeshes
  20949. var previousSubmeshes = this.subMeshes.slice(0);
  20950. var indices = this.getIndices();
  20951. var totalIndices = this.getTotalIndices();
  20952. // Generating unique vertices per face
  20953. var index;
  20954. for (index = 0; index < totalIndices; index++) {
  20955. var vertexIndex = indices[index];
  20956. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20957. kind = kinds[kindIndex];
  20958. var stride = vbs[kind].getStrideSize();
  20959. for (var offset = 0; offset < stride; offset++) {
  20960. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20961. }
  20962. }
  20963. }
  20964. // Updating indices
  20965. for (index = 0; index < totalIndices; index += 3) {
  20966. indices[index] = index;
  20967. indices[index + 1] = index + 1;
  20968. indices[index + 2] = index + 2;
  20969. }
  20970. this.setIndices(indices);
  20971. // Updating vertex buffers
  20972. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20973. kind = kinds[kindIndex];
  20974. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20975. }
  20976. // Updating submeshes
  20977. this.releaseSubMeshes();
  20978. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20979. var previousOne = previousSubmeshes[submeshIndex];
  20980. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20981. }
  20982. this._unIndexed = true;
  20983. this.synchronizeInstances();
  20984. };
  20985. /**
  20986. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20987. * This method returns nothing.
  20988. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20989. */
  20990. Mesh.prototype.flipFaces = function (flipNormals) {
  20991. if (flipNormals === void 0) { flipNormals = false; }
  20992. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20993. var i;
  20994. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20995. for (i = 0; i < vertex_data.normals.length; i++) {
  20996. vertex_data.normals[i] *= -1;
  20997. }
  20998. }
  20999. var temp;
  21000. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21001. // reassign indices
  21002. temp = vertex_data.indices[i + 1];
  21003. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21004. vertex_data.indices[i + 2] = temp;
  21005. }
  21006. vertex_data.applyToMesh(this);
  21007. };
  21008. // Instances
  21009. /**
  21010. * Creates a new InstancedMesh object from the mesh model.
  21011. * An instance shares the same properties and the same material than its model.
  21012. * Only these properties of each instance can then be set individually :
  21013. * - position
  21014. * - rotation
  21015. * - rotationQuaternion
  21016. * - setPivotMatrix
  21017. * - scaling
  21018. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21019. * Warning : this method is not supported for Line mesh and LineSystem
  21020. */
  21021. Mesh.prototype.createInstance = function (name) {
  21022. return new BABYLON.InstancedMesh(name, this);
  21023. };
  21024. /**
  21025. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21026. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21027. * This method returns nothing.
  21028. */
  21029. Mesh.prototype.synchronizeInstances = function () {
  21030. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21031. var instance = this.instances[instanceIndex];
  21032. instance._syncSubMeshes();
  21033. }
  21034. };
  21035. /**
  21036. * Simplify the mesh according to the given array of settings.
  21037. * Function will return immediately and will simplify async. It returns nothing.
  21038. * @param settings a collection of simplification settings.
  21039. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21040. * @param type the type of simplification to run.
  21041. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21042. */
  21043. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21044. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21045. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21046. this.getScene().simplificationQueue.addTask({
  21047. settings: settings,
  21048. parallelProcessing: parallelProcessing,
  21049. mesh: this,
  21050. simplificationType: simplificationType,
  21051. successCallback: successCallback
  21052. });
  21053. };
  21054. /**
  21055. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21056. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21057. * This should be used together with the simplification to avoid disappearing triangles.
  21058. * @param successCallback an optional success callback to be called after the optimization finished.
  21059. */
  21060. Mesh.prototype.optimizeIndices = function (successCallback) {
  21061. var _this = this;
  21062. var indices = this.getIndices();
  21063. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21064. var vectorPositions = [];
  21065. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21066. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21067. }
  21068. var dupes = [];
  21069. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21070. var realPos = vectorPositions.length - 1 - iteration;
  21071. var testedPosition = vectorPositions[realPos];
  21072. for (var j = 0; j < realPos; ++j) {
  21073. var againstPosition = vectorPositions[j];
  21074. if (testedPosition.equals(againstPosition)) {
  21075. dupes[realPos] = j;
  21076. break;
  21077. }
  21078. }
  21079. }, function () {
  21080. for (var i = 0; i < indices.length; ++i) {
  21081. indices[i] = dupes[indices[i]] || indices[i];
  21082. }
  21083. //indices are now reordered
  21084. var originalSubMeshes = _this.subMeshes.slice(0);
  21085. _this.setIndices(indices);
  21086. _this.subMeshes = originalSubMeshes;
  21087. if (successCallback) {
  21088. successCallback(_this);
  21089. }
  21090. });
  21091. };
  21092. // Statics
  21093. /**
  21094. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21095. * The parameter `parsedMesh` is the mesh to be copied.
  21096. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21097. */
  21098. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21099. var mesh = new Mesh(parsedMesh.name, scene);
  21100. mesh.id = parsedMesh.id;
  21101. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21102. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21103. if (parsedMesh.metadata !== undefined) {
  21104. mesh.metadata = parsedMesh.metadata;
  21105. }
  21106. if (parsedMesh.rotationQuaternion) {
  21107. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21108. }
  21109. else if (parsedMesh.rotation) {
  21110. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21111. }
  21112. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21113. if (parsedMesh.localMatrix) {
  21114. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21115. }
  21116. else if (parsedMesh.pivotMatrix) {
  21117. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21118. }
  21119. mesh.setEnabled(parsedMesh.isEnabled);
  21120. mesh.isVisible = parsedMesh.isVisible;
  21121. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21122. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21123. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21124. if (parsedMesh.applyFog !== undefined) {
  21125. mesh.applyFog = parsedMesh.applyFog;
  21126. }
  21127. if (parsedMesh.pickable !== undefined) {
  21128. mesh.isPickable = parsedMesh.pickable;
  21129. }
  21130. if (parsedMesh.alphaIndex !== undefined) {
  21131. mesh.alphaIndex = parsedMesh.alphaIndex;
  21132. }
  21133. mesh.receiveShadows = parsedMesh.receiveShadows;
  21134. mesh.billboardMode = parsedMesh.billboardMode;
  21135. if (parsedMesh.visibility !== undefined) {
  21136. mesh.visibility = parsedMesh.visibility;
  21137. }
  21138. mesh.checkCollisions = parsedMesh.checkCollisions;
  21139. if (parsedMesh.isBlocker !== undefined) {
  21140. mesh.isBlocker = parsedMesh.isBlocker;
  21141. }
  21142. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21143. // freezeWorldMatrix
  21144. if (parsedMesh.freezeWorldMatrix) {
  21145. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21146. }
  21147. // Parent
  21148. if (parsedMesh.parentId) {
  21149. mesh._waitingParentId = parsedMesh.parentId;
  21150. }
  21151. // Actions
  21152. if (parsedMesh.actions !== undefined) {
  21153. mesh._waitingActions = parsedMesh.actions;
  21154. }
  21155. // Overlay
  21156. if (parsedMesh.overlayAlpha !== undefined) {
  21157. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21158. }
  21159. if (parsedMesh.overlayColor !== undefined) {
  21160. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21161. }
  21162. if (parsedMesh.renderOverlay !== undefined) {
  21163. mesh.renderOverlay = parsedMesh.renderOverlay;
  21164. }
  21165. // Geometry
  21166. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21167. if (parsedMesh.delayLoadingFile) {
  21168. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21169. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21170. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21171. if (parsedMesh._binaryInfo) {
  21172. mesh._binaryInfo = parsedMesh._binaryInfo;
  21173. }
  21174. mesh._delayInfo = [];
  21175. if (parsedMesh.hasUVs) {
  21176. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21177. }
  21178. if (parsedMesh.hasUVs2) {
  21179. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21180. }
  21181. if (parsedMesh.hasUVs3) {
  21182. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21183. }
  21184. if (parsedMesh.hasUVs4) {
  21185. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21186. }
  21187. if (parsedMesh.hasUVs5) {
  21188. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21189. }
  21190. if (parsedMesh.hasUVs6) {
  21191. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21192. }
  21193. if (parsedMesh.hasColors) {
  21194. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21195. }
  21196. if (parsedMesh.hasMatricesIndices) {
  21197. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21198. }
  21199. if (parsedMesh.hasMatricesWeights) {
  21200. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21201. }
  21202. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21203. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21204. mesh._checkDelayState();
  21205. }
  21206. }
  21207. else {
  21208. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21209. }
  21210. // Material
  21211. if (parsedMesh.materialId) {
  21212. mesh.setMaterialByID(parsedMesh.materialId);
  21213. }
  21214. else {
  21215. mesh.material = null;
  21216. }
  21217. // Skeleton
  21218. if (parsedMesh.skeletonId > -1) {
  21219. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21220. if (parsedMesh.numBoneInfluencers) {
  21221. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21222. }
  21223. }
  21224. // Animations
  21225. if (parsedMesh.animations) {
  21226. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21227. var parsedAnimation = parsedMesh.animations[animationIndex];
  21228. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21229. }
  21230. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21231. }
  21232. if (parsedMesh.autoAnimate) {
  21233. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21234. }
  21235. // Layer Mask
  21236. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21237. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21238. }
  21239. else {
  21240. mesh.layerMask = 0x0FFFFFFF;
  21241. }
  21242. //(Deprecated) physics
  21243. if (parsedMesh.physicsImpostor) {
  21244. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21245. mass: parsedMesh.physicsMass,
  21246. friction: parsedMesh.physicsFriction,
  21247. restitution: parsedMesh.physicsRestitution
  21248. }, scene);
  21249. }
  21250. // Instances
  21251. if (parsedMesh.instances) {
  21252. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21253. var parsedInstance = parsedMesh.instances[index];
  21254. var instance = mesh.createInstance(parsedInstance.name);
  21255. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21256. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21257. if (parsedInstance.parentId) {
  21258. instance._waitingParentId = parsedInstance.parentId;
  21259. }
  21260. if (parsedInstance.rotationQuaternion) {
  21261. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21262. }
  21263. else if (parsedInstance.rotation) {
  21264. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21265. }
  21266. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21267. instance.checkCollisions = mesh.checkCollisions;
  21268. if (parsedMesh.animations) {
  21269. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21270. parsedAnimation = parsedMesh.animations[animationIndex];
  21271. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21272. }
  21273. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21274. }
  21275. }
  21276. }
  21277. return mesh;
  21278. };
  21279. /**
  21280. * Creates a ribbon mesh.
  21281. * Please consider using the same method from the MeshBuilder class instead.
  21282. * 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.
  21283. *
  21284. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21285. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21286. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21287. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21288. * 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.
  21289. * 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.
  21290. * 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
  21291. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21292. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21293. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21294. */
  21295. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21296. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21297. pathArray: pathArray,
  21298. closeArray: closeArray,
  21299. closePath: closePath,
  21300. offset: offset,
  21301. updatable: updatable,
  21302. sideOrientation: sideOrientation,
  21303. instance: instance
  21304. }, scene);
  21305. };
  21306. /**
  21307. * Creates a plane polygonal mesh. By default, this is a disc.
  21308. * Please consider using the same method from the MeshBuilder class instead.
  21309. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21310. * 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.
  21311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21314. */
  21315. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21316. var options = {
  21317. radius: radius,
  21318. tessellation: tessellation,
  21319. sideOrientation: sideOrientation,
  21320. updatable: updatable
  21321. };
  21322. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21323. };
  21324. /**
  21325. * Creates a box mesh.
  21326. * Please consider using the same method from the MeshBuilder class instead.
  21327. * The parameter `size` sets the size (float) of each box side (default 1).
  21328. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21329. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21330. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21331. */
  21332. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21333. var options = {
  21334. size: size,
  21335. sideOrientation: sideOrientation,
  21336. updatable: updatable
  21337. };
  21338. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21339. };
  21340. /**
  21341. * Creates a sphere mesh.
  21342. * Please consider using the same method from the MeshBuilder class instead.
  21343. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21344. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21345. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21346. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21347. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21348. */
  21349. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21350. var options = {
  21351. segments: segments,
  21352. diameterX: diameter,
  21353. diameterY: diameter,
  21354. diameterZ: diameter,
  21355. sideOrientation: sideOrientation,
  21356. updatable: updatable
  21357. };
  21358. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21359. };
  21360. /**
  21361. * Creates a cylinder or a cone mesh.
  21362. * Please consider using the same method from the MeshBuilder class instead.
  21363. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21364. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21365. * 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.
  21366. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21367. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21368. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21369. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21370. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21371. */
  21372. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21373. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21374. if (scene !== undefined) {
  21375. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21376. updatable = scene;
  21377. }
  21378. scene = subdivisions;
  21379. subdivisions = 1;
  21380. }
  21381. var options = {
  21382. height: height,
  21383. diameterTop: diameterTop,
  21384. diameterBottom: diameterBottom,
  21385. tessellation: tessellation,
  21386. subdivisions: subdivisions,
  21387. sideOrientation: sideOrientation,
  21388. updatable: updatable
  21389. };
  21390. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21391. };
  21392. // Torus (Code from SharpDX.org)
  21393. /**
  21394. * Creates a torus mesh.
  21395. * Please consider using the same method from the MeshBuilder class instead.
  21396. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21397. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21398. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21399. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21400. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21401. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21402. */
  21403. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21404. var options = {
  21405. diameter: diameter,
  21406. thickness: thickness,
  21407. tessellation: tessellation,
  21408. sideOrientation: sideOrientation,
  21409. updatable: updatable
  21410. };
  21411. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21412. };
  21413. /**
  21414. * Creates a torus knot mesh.
  21415. * Please consider using the same method from the MeshBuilder class instead.
  21416. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21417. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21418. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21419. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21420. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21421. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21423. */
  21424. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21425. var options = {
  21426. radius: radius,
  21427. tube: tube,
  21428. radialSegments: radialSegments,
  21429. tubularSegments: tubularSegments,
  21430. p: p,
  21431. q: q,
  21432. sideOrientation: sideOrientation,
  21433. updatable: updatable
  21434. };
  21435. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21436. };
  21437. /**
  21438. * Creates a line mesh.
  21439. * Please consider using the same method from the MeshBuilder class instead.
  21440. * 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.
  21441. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21442. * The parameter `points` is an array successive Vector3.
  21443. * 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
  21444. * When updating an instance, remember that only point positions can change, not the number of points.
  21445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21446. */
  21447. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21448. var options = {
  21449. points: points,
  21450. updatable: updatable,
  21451. instance: instance
  21452. };
  21453. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21454. };
  21455. /**
  21456. * Creates a dashed line mesh.
  21457. * Please consider using the same method from the MeshBuilder class instead.
  21458. * 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.
  21459. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21460. * The parameter `points` is an array successive Vector3.
  21461. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21462. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21463. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21464. * 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
  21465. * When updating an instance, remember that only point positions can change, not the number of points.
  21466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21467. */
  21468. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21469. var options = {
  21470. points: points,
  21471. dashSize: dashSize,
  21472. gapSize: gapSize,
  21473. dashNb: dashNb,
  21474. updatable: updatable,
  21475. instance: instance
  21476. };
  21477. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21478. };
  21479. /**
  21480. * Creates an extruded shape mesh.
  21481. * 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.
  21482. * Please consider using the same method from the MeshBuilder class instead.
  21483. *
  21484. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21485. * 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
  21486. * extruded along the Z axis.
  21487. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21488. * 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.
  21489. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21490. * 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
  21491. * 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
  21492. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21496. */
  21497. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21498. var options = {
  21499. shape: shape,
  21500. path: path,
  21501. scale: scale,
  21502. rotation: rotation,
  21503. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21504. sideOrientation: sideOrientation,
  21505. instance: instance,
  21506. updatable: updatable
  21507. };
  21508. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21509. };
  21510. /**
  21511. * Creates an custom extruded shape mesh.
  21512. * 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.
  21513. * Please consider using the same method from the MeshBuilder class instead.
  21514. *
  21515. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21516. * 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
  21517. * extruded along the Z axis.
  21518. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21519. * 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
  21520. * and the distance of this point from the begining of the path :
  21521. * ```javascript
  21522. * var rotationFunction = function(i, distance) {
  21523. * // do things
  21524. * return rotationValue; }
  21525. * ```
  21526. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21527. * 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
  21528. * and the distance of this point from the begining of the path :
  21529. * ```javascript
  21530. * var scaleFunction = function(i, distance) {
  21531. * // do things
  21532. * return scaleValue;}
  21533. * ```
  21534. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21535. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21536. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21537. * 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
  21538. * 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
  21539. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21540. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21541. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21542. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21543. */
  21544. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21545. var options = {
  21546. shape: shape,
  21547. path: path,
  21548. scaleFunction: scaleFunction,
  21549. rotationFunction: rotationFunction,
  21550. ribbonCloseArray: ribbonCloseArray,
  21551. ribbonClosePath: ribbonClosePath,
  21552. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21553. sideOrientation: sideOrientation,
  21554. instance: instance,
  21555. updatable: updatable
  21556. };
  21557. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21558. };
  21559. /**
  21560. * Creates lathe mesh.
  21561. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21562. * Please consider using the same method from the MeshBuilder class instead.
  21563. * 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
  21564. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21565. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21566. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21567. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21568. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21569. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21570. */
  21571. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21572. var options = {
  21573. shape: shape,
  21574. radius: radius,
  21575. tessellation: tessellation,
  21576. sideOrientation: sideOrientation,
  21577. updatable: updatable
  21578. };
  21579. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21580. };
  21581. /**
  21582. * Creates a plane mesh.
  21583. * Please consider using the same method from the MeshBuilder class instead.
  21584. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21585. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21586. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21587. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21588. */
  21589. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21590. var options = {
  21591. size: size,
  21592. width: size,
  21593. height: size,
  21594. sideOrientation: sideOrientation,
  21595. updatable: updatable
  21596. };
  21597. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21598. };
  21599. /**
  21600. * Creates a ground mesh.
  21601. * Please consider using the same method from the MeshBuilder class instead.
  21602. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21603. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21604. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21605. */
  21606. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21607. var options = {
  21608. width: width,
  21609. height: height,
  21610. subdivisions: subdivisions,
  21611. updatable: updatable
  21612. };
  21613. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21614. };
  21615. /**
  21616. * Creates a tiled ground mesh.
  21617. * Please consider using the same method from the MeshBuilder class instead.
  21618. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21619. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21620. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21621. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21622. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21623. * numbers of subdivisions on the ground width and height of each tile.
  21624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21625. */
  21626. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21627. var options = {
  21628. xmin: xmin,
  21629. zmin: zmin,
  21630. xmax: xmax,
  21631. zmax: zmax,
  21632. subdivisions: subdivisions,
  21633. precision: precision,
  21634. updatable: updatable
  21635. };
  21636. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21637. };
  21638. /**
  21639. * Creates a ground mesh from a height map.
  21640. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21641. * Please consider using the same method from the MeshBuilder class instead.
  21642. * The parameter `url` sets the URL of the height map image resource.
  21643. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21644. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21645. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21646. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21647. * 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).
  21648. * This function is passed the newly built mesh :
  21649. * ```javascript
  21650. * function(mesh) { // do things
  21651. * return; }
  21652. * ```
  21653. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21654. */
  21655. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21656. var options = {
  21657. width: width,
  21658. height: height,
  21659. subdivisions: subdivisions,
  21660. minHeight: minHeight,
  21661. maxHeight: maxHeight,
  21662. updatable: updatable,
  21663. onReady: onReady
  21664. };
  21665. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21666. };
  21667. /**
  21668. * Creates a tube mesh.
  21669. * 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.
  21670. * Please consider using the same method from the MeshBuilder class instead.
  21671. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21672. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21673. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21674. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21675. * 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.
  21676. * It must return a radius value (positive float) :
  21677. * ```javascript
  21678. * var radiusFunction = function(i, distance) {
  21679. * // do things
  21680. * return radius; }
  21681. * ```
  21682. * 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
  21683. * 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
  21684. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21685. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21687. */
  21688. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21689. var options = {
  21690. path: path,
  21691. radius: radius,
  21692. tessellation: tessellation,
  21693. radiusFunction: radiusFunction,
  21694. arc: 1,
  21695. cap: cap,
  21696. updatable: updatable,
  21697. sideOrientation: sideOrientation,
  21698. instance: instance
  21699. };
  21700. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21701. };
  21702. /**
  21703. * Creates a polyhedron mesh.
  21704. * Please consider using the same method from the MeshBuilder class instead.
  21705. * 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
  21706. * to choose the wanted type.
  21707. * The parameter `size` (positive float, default 1) sets the polygon size.
  21708. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21709. * 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`.
  21710. * 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
  21711. * 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)`).
  21712. * 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
  21713. * 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.
  21714. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21715. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21716. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21717. */
  21718. Mesh.CreatePolyhedron = function (name, options, scene) {
  21719. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21720. };
  21721. /**
  21722. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21723. * Please consider using the same method from the MeshBuilder class instead.
  21724. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21725. * 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`).
  21726. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21727. * 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.
  21728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21729. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21731. */
  21732. Mesh.CreateIcoSphere = function (name, options, scene) {
  21733. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21734. };
  21735. /**
  21736. * Creates a decal mesh.
  21737. * Please consider using the same method from the MeshBuilder class instead.
  21738. * 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.
  21739. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21740. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21741. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21742. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21743. */
  21744. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21745. var options = {
  21746. position: position,
  21747. normal: normal,
  21748. size: size,
  21749. angle: angle
  21750. };
  21751. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21752. };
  21753. // Skeletons
  21754. /**
  21755. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21756. */
  21757. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21758. var source;
  21759. if (!this._sourcePositions) {
  21760. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21761. this._sourcePositions = new Float32Array(source);
  21762. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21763. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21764. }
  21765. }
  21766. return this._sourcePositions;
  21767. };
  21768. /**
  21769. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21770. */
  21771. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21772. var source;
  21773. if (!this._sourceNormals) {
  21774. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21775. this._sourceNormals = new Float32Array(source);
  21776. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21777. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21778. }
  21779. }
  21780. return this._sourceNormals;
  21781. };
  21782. /**
  21783. * Update the vertex buffers by applying transformation from the bones
  21784. * @param {skeleton} skeleton to apply
  21785. */
  21786. Mesh.prototype.applySkeleton = function (skeleton) {
  21787. if (!this.geometry) {
  21788. return;
  21789. }
  21790. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21791. return;
  21792. }
  21793. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21794. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21795. return this;
  21796. }
  21797. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21798. return this;
  21799. }
  21800. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21801. return this;
  21802. }
  21803. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21804. return this;
  21805. }
  21806. if (!this._sourcePositions) {
  21807. var submeshes = this.subMeshes.slice();
  21808. this.setPositionsForCPUSkinning();
  21809. this.subMeshes = submeshes;
  21810. }
  21811. if (!this._sourceNormals) {
  21812. this.setNormalsForCPUSkinning();
  21813. }
  21814. // positionsData checks for not being Float32Array will only pass at most once
  21815. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21816. if (!(positionsData instanceof Float32Array)) {
  21817. positionsData = new Float32Array(positionsData);
  21818. }
  21819. // normalsData checks for not being Float32Array will only pass at most once
  21820. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21821. if (!(normalsData instanceof Float32Array)) {
  21822. normalsData = new Float32Array(normalsData);
  21823. }
  21824. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21825. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21826. var needExtras = this.numBoneInfluencers > 4;
  21827. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21828. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21829. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21830. var tempVector3 = BABYLON.Vector3.Zero();
  21831. var finalMatrix = new BABYLON.Matrix();
  21832. var tempMatrix = new BABYLON.Matrix();
  21833. var matWeightIdx = 0;
  21834. var inf;
  21835. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21836. var weight;
  21837. for (inf = 0; inf < 4; inf++) {
  21838. weight = matricesWeightsData[matWeightIdx + inf];
  21839. if (weight > 0) {
  21840. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21841. finalMatrix.addToSelf(tempMatrix);
  21842. }
  21843. else
  21844. break;
  21845. }
  21846. if (needExtras) {
  21847. for (inf = 0; inf < 4; inf++) {
  21848. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21849. if (weight > 0) {
  21850. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21851. finalMatrix.addToSelf(tempMatrix);
  21852. }
  21853. else
  21854. break;
  21855. }
  21856. }
  21857. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21858. tempVector3.toArray(positionsData, index);
  21859. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21860. tempVector3.toArray(normalsData, index);
  21861. finalMatrix.reset();
  21862. }
  21863. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21864. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21865. return this;
  21866. };
  21867. // Tools
  21868. /**
  21869. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21870. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21871. */
  21872. Mesh.MinMax = function (meshes) {
  21873. var minVector = null;
  21874. var maxVector = null;
  21875. meshes.forEach(function (mesh, index, array) {
  21876. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21877. if (!minVector) {
  21878. minVector = boundingBox.minimumWorld;
  21879. maxVector = boundingBox.maximumWorld;
  21880. }
  21881. else {
  21882. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21883. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21884. }
  21885. });
  21886. return {
  21887. min: minVector,
  21888. max: maxVector
  21889. };
  21890. };
  21891. /**
  21892. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21893. */
  21894. Mesh.Center = function (meshesOrMinMaxVector) {
  21895. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21896. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21897. };
  21898. /**
  21899. * Merge the array of meshes into a single mesh for performance reasons.
  21900. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21901. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21902. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21903. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21904. */
  21905. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21906. if (disposeSource === void 0) { disposeSource = true; }
  21907. var index;
  21908. if (!allow32BitsIndices) {
  21909. var totalVertices = 0;
  21910. // Counting vertices
  21911. for (index = 0; index < meshes.length; index++) {
  21912. if (meshes[index]) {
  21913. totalVertices += meshes[index].getTotalVertices();
  21914. if (totalVertices > 65536) {
  21915. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21916. return null;
  21917. }
  21918. }
  21919. }
  21920. }
  21921. // Merge
  21922. var vertexData;
  21923. var otherVertexData;
  21924. var source;
  21925. for (index = 0; index < meshes.length; index++) {
  21926. if (meshes[index]) {
  21927. meshes[index].computeWorldMatrix(true);
  21928. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21929. otherVertexData.transform(meshes[index].getWorldMatrix());
  21930. if (vertexData) {
  21931. vertexData.merge(otherVertexData);
  21932. }
  21933. else {
  21934. vertexData = otherVertexData;
  21935. source = meshes[index];
  21936. }
  21937. }
  21938. }
  21939. if (!meshSubclass) {
  21940. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21941. }
  21942. vertexData.applyToMesh(meshSubclass);
  21943. // Setting properties
  21944. meshSubclass.material = source.material;
  21945. meshSubclass.checkCollisions = source.checkCollisions;
  21946. // Cleaning
  21947. if (disposeSource) {
  21948. for (index = 0; index < meshes.length; index++) {
  21949. if (meshes[index]) {
  21950. meshes[index].dispose();
  21951. }
  21952. }
  21953. }
  21954. return meshSubclass;
  21955. };
  21956. // Consts
  21957. Mesh._FRONTSIDE = 0;
  21958. Mesh._BACKSIDE = 1;
  21959. Mesh._DOUBLESIDE = 2;
  21960. Mesh._DEFAULTSIDE = 0;
  21961. Mesh._NO_CAP = 0;
  21962. Mesh._CAP_START = 1;
  21963. Mesh._CAP_END = 2;
  21964. Mesh._CAP_ALL = 3;
  21965. return Mesh;
  21966. }(BABYLON.AbstractMesh));
  21967. BABYLON.Mesh = Mesh;
  21968. })(BABYLON || (BABYLON = {}));
  21969. //# sourceMappingURL=babylon.mesh.js.map
  21970. var BABYLON;
  21971. (function (BABYLON) {
  21972. var SubMesh = (function () {
  21973. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21974. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21975. this.materialIndex = materialIndex;
  21976. this.verticesStart = verticesStart;
  21977. this.verticesCount = verticesCount;
  21978. this.indexStart = indexStart;
  21979. this.indexCount = indexCount;
  21980. this._renderId = 0;
  21981. this._mesh = mesh;
  21982. this._renderingMesh = renderingMesh || mesh;
  21983. mesh.subMeshes.push(this);
  21984. this._trianglePlanes = [];
  21985. this._id = mesh.subMeshes.length - 1;
  21986. if (createBoundingBox) {
  21987. this.refreshBoundingInfo();
  21988. mesh.computeWorldMatrix(true);
  21989. }
  21990. }
  21991. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21992. get: function () {
  21993. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21994. },
  21995. enumerable: true,
  21996. configurable: true
  21997. });
  21998. SubMesh.prototype.getBoundingInfo = function () {
  21999. if (this.IsGlobal) {
  22000. return this._mesh.getBoundingInfo();
  22001. }
  22002. return this._boundingInfo;
  22003. };
  22004. SubMesh.prototype.getMesh = function () {
  22005. return this._mesh;
  22006. };
  22007. SubMesh.prototype.getRenderingMesh = function () {
  22008. return this._renderingMesh;
  22009. };
  22010. SubMesh.prototype.getMaterial = function () {
  22011. var rootMaterial = this._renderingMesh.material;
  22012. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22013. var multiMaterial = rootMaterial;
  22014. return multiMaterial.getSubMaterial(this.materialIndex);
  22015. }
  22016. if (!rootMaterial) {
  22017. return this._mesh.getScene().defaultMaterial;
  22018. }
  22019. return rootMaterial;
  22020. };
  22021. // Methods
  22022. SubMesh.prototype.refreshBoundingInfo = function () {
  22023. this._lastColliderWorldVertices = null;
  22024. if (this.IsGlobal) {
  22025. return;
  22026. }
  22027. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22028. if (!data) {
  22029. this._boundingInfo = this._mesh._boundingInfo;
  22030. return;
  22031. }
  22032. var indices = this._renderingMesh.getIndices();
  22033. var extend;
  22034. //is this the only submesh?
  22035. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22036. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22037. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22038. }
  22039. else {
  22040. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22041. }
  22042. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22043. };
  22044. SubMesh.prototype._checkCollision = function (collider) {
  22045. return this.getBoundingInfo()._checkCollision(collider);
  22046. };
  22047. SubMesh.prototype.updateBoundingInfo = function (world) {
  22048. if (!this.getBoundingInfo()) {
  22049. this.refreshBoundingInfo();
  22050. }
  22051. this.getBoundingInfo().update(world);
  22052. };
  22053. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22054. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22055. };
  22056. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22057. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22058. };
  22059. SubMesh.prototype.render = function (enableAlphaMode) {
  22060. this._renderingMesh.render(this, enableAlphaMode);
  22061. };
  22062. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22063. if (!this._linesIndexBuffer) {
  22064. var linesIndices = [];
  22065. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22066. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22067. }
  22068. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22069. this.linesIndexCount = linesIndices.length;
  22070. }
  22071. return this._linesIndexBuffer;
  22072. };
  22073. SubMesh.prototype.canIntersects = function (ray) {
  22074. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22075. };
  22076. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22077. var intersectInfo = null;
  22078. // LineMesh first as it's also a Mesh...
  22079. if (this._mesh instanceof BABYLON.LinesMesh) {
  22080. var lineMesh = this._mesh;
  22081. // Line test
  22082. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22083. var p0 = positions[indices[index]];
  22084. var p1 = positions[indices[index + 1]];
  22085. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22086. if (length < 0) {
  22087. continue;
  22088. }
  22089. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22090. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22091. if (fastCheck) {
  22092. break;
  22093. }
  22094. }
  22095. }
  22096. }
  22097. else {
  22098. // Triangles test
  22099. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22100. var p0 = positions[indices[index]];
  22101. var p1 = positions[indices[index + 1]];
  22102. var p2 = positions[indices[index + 2]];
  22103. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22104. if (currentIntersectInfo) {
  22105. if (currentIntersectInfo.distance < 0) {
  22106. continue;
  22107. }
  22108. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22109. intersectInfo = currentIntersectInfo;
  22110. intersectInfo.faceId = index / 3;
  22111. if (fastCheck) {
  22112. break;
  22113. }
  22114. }
  22115. }
  22116. }
  22117. }
  22118. return intersectInfo;
  22119. };
  22120. // Clone
  22121. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22122. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22123. if (!this.IsGlobal) {
  22124. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22125. }
  22126. return result;
  22127. };
  22128. // Dispose
  22129. SubMesh.prototype.dispose = function () {
  22130. if (this._linesIndexBuffer) {
  22131. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22132. this._linesIndexBuffer = null;
  22133. }
  22134. // Remove from mesh
  22135. var index = this._mesh.subMeshes.indexOf(this);
  22136. this._mesh.subMeshes.splice(index, 1);
  22137. };
  22138. // Statics
  22139. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22140. var minVertexIndex = Number.MAX_VALUE;
  22141. var maxVertexIndex = -Number.MAX_VALUE;
  22142. renderingMesh = renderingMesh || mesh;
  22143. var indices = renderingMesh.getIndices();
  22144. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22145. var vertexIndex = indices[index];
  22146. if (vertexIndex < minVertexIndex)
  22147. minVertexIndex = vertexIndex;
  22148. if (vertexIndex > maxVertexIndex)
  22149. maxVertexIndex = vertexIndex;
  22150. }
  22151. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22152. };
  22153. return SubMesh;
  22154. }());
  22155. BABYLON.SubMesh = SubMesh;
  22156. })(BABYLON || (BABYLON = {}));
  22157. //# sourceMappingURL=babylon.subMesh.js.map
  22158. var BABYLON;
  22159. (function (BABYLON) {
  22160. var MeshBuilder = (function () {
  22161. function MeshBuilder() {
  22162. }
  22163. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22164. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22165. return BABYLON.Mesh.DOUBLESIDE;
  22166. }
  22167. if (orientation === undefined || orientation === null) {
  22168. return BABYLON.Mesh.FRONTSIDE;
  22169. }
  22170. return orientation;
  22171. };
  22172. /**
  22173. * Creates a box mesh.
  22174. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22175. * The parameter `size` sets the size (float) of each box side (default 1).
  22176. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22177. * 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).
  22178. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22182. */
  22183. MeshBuilder.CreateBox = function (name, options, scene) {
  22184. var box = new BABYLON.Mesh(name, scene);
  22185. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22186. box.sideOrientation = options.sideOrientation;
  22187. var vertexData = BABYLON.VertexData.CreateBox(options);
  22188. vertexData.applyToMesh(box, options.updatable);
  22189. return box;
  22190. };
  22191. /**
  22192. * Creates a sphere mesh.
  22193. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22194. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22195. * 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`).
  22196. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22197. * 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
  22198. * 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).
  22199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22202. */
  22203. MeshBuilder.CreateSphere = function (name, options, scene) {
  22204. var sphere = new BABYLON.Mesh(name, scene);
  22205. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22206. sphere.sideOrientation = options.sideOrientation;
  22207. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22208. vertexData.applyToMesh(sphere, options.updatable);
  22209. return sphere;
  22210. };
  22211. /**
  22212. * Creates a plane polygonal mesh. By default, this is a disc.
  22213. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22214. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22215. * 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.
  22216. * 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
  22217. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22218. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22219. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22220. */
  22221. MeshBuilder.CreateDisc = function (name, options, scene) {
  22222. var disc = new BABYLON.Mesh(name, scene);
  22223. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22224. disc.sideOrientation = options.sideOrientation;
  22225. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22226. vertexData.applyToMesh(disc, options.updatable);
  22227. return disc;
  22228. };
  22229. /**
  22230. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22231. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22232. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22233. * 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`).
  22234. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22235. * 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.
  22236. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22237. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22238. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22239. */
  22240. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22241. var sphere = new BABYLON.Mesh(name, scene);
  22242. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22243. sphere.sideOrientation = options.sideOrientation;
  22244. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22245. vertexData.applyToMesh(sphere, options.updatable);
  22246. return sphere;
  22247. };
  22248. ;
  22249. /**
  22250. * Creates a ribbon mesh.
  22251. * 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.
  22252. *
  22253. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22254. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22255. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22256. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22257. * 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.
  22258. * 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.
  22259. * 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
  22260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22261. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22262. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22264. */
  22265. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22266. var pathArray = options.pathArray;
  22267. var closeArray = options.closeArray;
  22268. var closePath = options.closePath;
  22269. var offset = options.offset;
  22270. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22271. var instance = options.instance;
  22272. var updatable = options.updatable;
  22273. if (instance) {
  22274. // positionFunction : ribbon case
  22275. // only pathArray and sideOrientation parameters are taken into account for positions update
  22276. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22277. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22278. var positionFunction = function (positions) {
  22279. var minlg = pathArray[0].length;
  22280. var i = 0;
  22281. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22282. for (var si = 1; si <= ns; si++) {
  22283. for (var p = 0; p < pathArray.length; p++) {
  22284. var path = pathArray[p];
  22285. var l = path.length;
  22286. minlg = (minlg < l) ? minlg : l;
  22287. var j = 0;
  22288. while (j < minlg) {
  22289. positions[i] = path[j].x;
  22290. positions[i + 1] = path[j].y;
  22291. positions[i + 2] = path[j].z;
  22292. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22293. BABYLON.Tmp.Vector3[0].x = path[j].x;
  22294. }
  22295. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  22296. BABYLON.Tmp.Vector3[1].x = path[j].x;
  22297. }
  22298. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  22299. BABYLON.Tmp.Vector3[0].y = path[j].y;
  22300. }
  22301. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  22302. BABYLON.Tmp.Vector3[1].y = path[j].y;
  22303. }
  22304. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  22305. BABYLON.Tmp.Vector3[0].z = path[j].z;
  22306. }
  22307. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  22308. BABYLON.Tmp.Vector3[1].z = path[j].z;
  22309. }
  22310. j++;
  22311. i += 3;
  22312. }
  22313. if (instance._closePath) {
  22314. positions[i] = path[0].x;
  22315. positions[i + 1] = path[0].y;
  22316. positions[i + 2] = path[0].z;
  22317. i += 3;
  22318. }
  22319. }
  22320. }
  22321. };
  22322. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22323. positionFunction(positions);
  22324. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  22325. instance._boundingInfo.update(instance._worldMatrix);
  22326. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22327. if (!(instance.areNormalsFrozen)) {
  22328. var indices = instance.getIndices();
  22329. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22330. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22331. if (instance._closePath) {
  22332. var indexFirst = 0;
  22333. var indexLast = 0;
  22334. for (var p = 0; p < pathArray.length; p++) {
  22335. indexFirst = instance._idx[p] * 3;
  22336. if (p + 1 < pathArray.length) {
  22337. indexLast = (instance._idx[p + 1] - 1) * 3;
  22338. }
  22339. else {
  22340. indexLast = normals.length - 3;
  22341. }
  22342. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  22343. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  22344. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  22345. normals[indexLast] = normals[indexFirst];
  22346. normals[indexLast + 1] = normals[indexFirst + 1];
  22347. normals[indexLast + 2] = normals[indexFirst + 2];
  22348. }
  22349. }
  22350. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22351. }
  22352. return instance;
  22353. }
  22354. else {
  22355. var ribbon = new BABYLON.Mesh(name, scene);
  22356. ribbon.sideOrientation = sideOrientation;
  22357. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  22358. if (closePath) {
  22359. ribbon._idx = vertexData._idx;
  22360. }
  22361. ribbon._closePath = closePath;
  22362. ribbon._closeArray = closeArray;
  22363. vertexData.applyToMesh(ribbon, updatable);
  22364. return ribbon;
  22365. }
  22366. };
  22367. /**
  22368. * Creates a cylinder or a cone mesh.
  22369. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  22370. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22371. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22372. * 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.
  22373. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22374. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22375. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  22376. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  22377. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  22378. * 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).
  22379. * 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
  22380. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  22381. * 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
  22382. * 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.
  22383. * If `enclose` is false, a ring surface is one element.
  22384. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  22385. * 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
  22386. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22388. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22389. */
  22390. MeshBuilder.CreateCylinder = function (name, options, scene) {
  22391. var cylinder = new BABYLON.Mesh(name, scene);
  22392. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22393. cylinder.sideOrientation = options.sideOrientation;
  22394. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  22395. vertexData.applyToMesh(cylinder, options.updatable);
  22396. return cylinder;
  22397. };
  22398. /**
  22399. * Creates a torus mesh.
  22400. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  22401. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22402. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22403. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22404. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22405. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22406. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22407. */
  22408. MeshBuilder.CreateTorus = function (name, options, scene) {
  22409. var torus = new BABYLON.Mesh(name, scene);
  22410. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22411. torus.sideOrientation = options.sideOrientation;
  22412. var vertexData = BABYLON.VertexData.CreateTorus(options);
  22413. vertexData.applyToMesh(torus, options.updatable);
  22414. return torus;
  22415. };
  22416. /**
  22417. * Creates a torus knot mesh.
  22418. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  22419. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22420. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22421. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22422. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22423. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22424. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22426. */
  22427. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  22428. var torusKnot = new BABYLON.Mesh(name, scene);
  22429. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22430. torusKnot.sideOrientation = options.sideOrientation;
  22431. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  22432. vertexData.applyToMesh(torusKnot, options.updatable);
  22433. return torusKnot;
  22434. };
  22435. /**
  22436. * Creates a line system mesh.
  22437. * A line system is a pool of many lines gathered in a single mesh.
  22438. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22439. * 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.
  22440. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22441. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22442. * 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
  22443. * 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
  22444. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22446. */
  22447. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22448. var instance = options.instance;
  22449. var lines = options.lines;
  22450. if (instance) {
  22451. var positionFunction = function (positions) {
  22452. var i = 0;
  22453. for (var l = 0; l < lines.length; l++) {
  22454. var points = lines[l];
  22455. for (var p = 0; p < points.length; p++) {
  22456. positions[i] = points[p].x;
  22457. positions[i + 1] = points[p].y;
  22458. positions[i + 2] = points[p].z;
  22459. i += 3;
  22460. }
  22461. }
  22462. };
  22463. instance.updateMeshPositions(positionFunction, false);
  22464. return instance;
  22465. }
  22466. // line system creation
  22467. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22468. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22469. vertexData.applyToMesh(lineSystem, options.updatable);
  22470. return lineSystem;
  22471. };
  22472. /**
  22473. * Creates a line mesh.
  22474. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22475. * 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.
  22476. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22477. * The parameter `points` is an array successive Vector3.
  22478. * 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
  22479. * When updating an instance, remember that only point positions can change, not the number of points.
  22480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22481. */
  22482. MeshBuilder.CreateLines = function (name, options, scene) {
  22483. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22484. return lines;
  22485. };
  22486. /**
  22487. * Creates a dashed line mesh.
  22488. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22489. * 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.
  22490. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22491. * The parameter `points` is an array successive Vector3.
  22492. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22493. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22494. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22495. * 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
  22496. * When updating an instance, remember that only point positions can change, not the number of points.
  22497. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22498. */
  22499. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22500. var points = options.points;
  22501. var instance = options.instance;
  22502. var gapSize = options.gapSize;
  22503. var dashNb = options.dashNb;
  22504. var dashSize = options.dashSize;
  22505. if (instance) {
  22506. var positionFunction = function (positions) {
  22507. var curvect = BABYLON.Vector3.Zero();
  22508. var nbSeg = positions.length / 6;
  22509. var lg = 0;
  22510. var nb = 0;
  22511. var shft = 0;
  22512. var dashshft = 0;
  22513. var curshft = 0;
  22514. var p = 0;
  22515. var i = 0;
  22516. var j = 0;
  22517. for (i = 0; i < points.length - 1; i++) {
  22518. points[i + 1].subtractToRef(points[i], curvect);
  22519. lg += curvect.length();
  22520. }
  22521. shft = lg / nbSeg;
  22522. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22523. for (i = 0; i < points.length - 1; i++) {
  22524. points[i + 1].subtractToRef(points[i], curvect);
  22525. nb = Math.floor(curvect.length() / shft);
  22526. curvect.normalize();
  22527. j = 0;
  22528. while (j < nb && p < positions.length) {
  22529. curshft = shft * j;
  22530. positions[p] = points[i].x + curshft * curvect.x;
  22531. positions[p + 1] = points[i].y + curshft * curvect.y;
  22532. positions[p + 2] = points[i].z + curshft * curvect.z;
  22533. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22534. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22535. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22536. p += 6;
  22537. j++;
  22538. }
  22539. }
  22540. while (p < positions.length) {
  22541. positions[p] = points[i].x;
  22542. positions[p + 1] = points[i].y;
  22543. positions[p + 2] = points[i].z;
  22544. p += 3;
  22545. }
  22546. };
  22547. instance.updateMeshPositions(positionFunction, false);
  22548. return instance;
  22549. }
  22550. // dashed lines creation
  22551. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22552. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22553. vertexData.applyToMesh(dashedLines, options.updatable);
  22554. dashedLines.dashSize = dashSize;
  22555. dashedLines.gapSize = gapSize;
  22556. return dashedLines;
  22557. };
  22558. /**
  22559. * Creates an extruded shape mesh.
  22560. * 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.
  22561. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22562. *
  22563. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22564. * 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
  22565. * extruded along the Z axis.
  22566. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22567. * 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.
  22568. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22569. * 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
  22570. * 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
  22571. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22572. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22573. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22574. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22576. */
  22577. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22578. var path = options.path;
  22579. var shape = options.shape;
  22580. var scale = options.scale || 1;
  22581. var rotation = options.rotation || 0;
  22582. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22583. var updatable = options.updatable;
  22584. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22585. var instance = options.instance;
  22586. var invertUV = options.invertUV || false;
  22587. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22588. };
  22589. /**
  22590. * Creates an custom extruded shape mesh.
  22591. * 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.
  22592. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22593. *
  22594. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22595. * 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
  22596. * extruded along the Z axis.
  22597. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22598. * 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
  22599. * and the distance of this point from the begining of the path :
  22600. * ```javascript
  22601. * var rotationFunction = function(i, distance) {
  22602. * // do things
  22603. * return rotationValue; }
  22604. * ```
  22605. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22606. * 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
  22607. * and the distance of this point from the begining of the path :
  22608. * ```javascript
  22609. * var scaleFunction = function(i, distance) {
  22610. * // do things
  22611. * return scaleValue;}
  22612. * ```
  22613. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22614. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22615. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22616. * 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
  22617. * 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
  22618. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22619. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22620. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22621. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22623. */
  22624. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22625. var path = options.path;
  22626. var shape = options.shape;
  22627. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22628. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22629. var ribbonCloseArray = options.ribbonCloseArray || false;
  22630. var ribbonClosePath = options.ribbonClosePath || false;
  22631. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22632. var updatable = options.updatable;
  22633. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22634. var instance = options.instance;
  22635. var invertUV = options.invertUV || false;
  22636. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22637. };
  22638. /**
  22639. * Creates lathe mesh.
  22640. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22641. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22642. *
  22643. * 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
  22644. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22645. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22646. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22647. * 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.
  22648. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22649. * 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
  22650. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22651. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22652. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22653. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22654. */
  22655. MeshBuilder.CreateLathe = function (name, options, scene) {
  22656. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22657. var closed = (options.closed === undefined) ? true : options.closed;
  22658. var shape = options.shape;
  22659. var radius = options.radius || 1;
  22660. var tessellation = options.tessellation || 64;
  22661. var updatable = options.updatable;
  22662. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22663. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22664. var pi2 = Math.PI * 2;
  22665. var paths = new Array();
  22666. var invertUV = options.invertUV || false;
  22667. var i = 0;
  22668. var p = 0;
  22669. var step = pi2 / tessellation * arc;
  22670. var rotated;
  22671. var path = new Array();
  22672. ;
  22673. for (i = 0; i <= tessellation; i++) {
  22674. var path = [];
  22675. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22676. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22677. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22678. }
  22679. for (p = 0; p < shape.length; p++) {
  22680. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22681. path.push(rotated);
  22682. }
  22683. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22684. 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));
  22685. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22686. }
  22687. paths.push(path);
  22688. }
  22689. // lathe ribbon
  22690. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22691. return lathe;
  22692. };
  22693. /**
  22694. * Creates a plane mesh.
  22695. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22696. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22697. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22698. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22699. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22700. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22701. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22702. */
  22703. MeshBuilder.CreatePlane = function (name, options, scene) {
  22704. var plane = new BABYLON.Mesh(name, scene);
  22705. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22706. plane.sideOrientation = options.sideOrientation;
  22707. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22708. vertexData.applyToMesh(plane, options.updatable);
  22709. if (options.sourcePlane) {
  22710. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22711. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22712. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22713. plane.rotate(vectorProduct, product);
  22714. }
  22715. return plane;
  22716. };
  22717. /**
  22718. * Creates a ground mesh.
  22719. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22720. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22721. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22723. */
  22724. MeshBuilder.CreateGround = function (name, options, scene) {
  22725. var ground = new BABYLON.GroundMesh(name, scene);
  22726. ground._setReady(false);
  22727. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22728. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22729. ground._width = options.width || 1;
  22730. ground._height = options.height || 1;
  22731. ground._maxX = ground._width / 2;
  22732. ground._maxZ = ground._height / 2;
  22733. ground._minX = -ground._maxX;
  22734. ground._minZ = -ground._maxZ;
  22735. var vertexData = BABYLON.VertexData.CreateGround(options);
  22736. vertexData.applyToMesh(ground, options.updatable);
  22737. ground._setReady(true);
  22738. return ground;
  22739. };
  22740. /**
  22741. * Creates a tiled ground mesh.
  22742. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22743. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22744. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22745. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22746. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22747. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22748. * numbers of subdivisions on the ground width and height of each tile.
  22749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22750. */
  22751. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22752. var tiledGround = new BABYLON.Mesh(name, scene);
  22753. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22754. vertexData.applyToMesh(tiledGround, options.updatable);
  22755. return tiledGround;
  22756. };
  22757. /**
  22758. * Creates a ground mesh from a height map.
  22759. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22760. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22761. * The parameter `url` sets the URL of the height map image resource.
  22762. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22763. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22764. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22765. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22766. * 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).
  22767. * This function is passed the newly built mesh :
  22768. * ```javascript
  22769. * function(mesh) { // do things
  22770. * return; }
  22771. * ```
  22772. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22773. */
  22774. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22775. var width = options.width || 10.0;
  22776. var height = options.height || 10.0;
  22777. var subdivisions = options.subdivisions || 1 | 0;
  22778. var minHeight = options.minHeight || 0.0;
  22779. var maxHeight = options.maxHeight || 10.0;
  22780. var updatable = options.updatable;
  22781. var onReady = options.onReady;
  22782. var ground = new BABYLON.GroundMesh(name, scene);
  22783. ground._subdivisionsX = subdivisions;
  22784. ground._subdivisionsY = subdivisions;
  22785. ground._width = width;
  22786. ground._height = height;
  22787. ground._maxX = ground._width / 2.0;
  22788. ground._maxZ = ground._height / 2.0;
  22789. ground._minX = -ground._maxX;
  22790. ground._minZ = -ground._maxZ;
  22791. ground._setReady(false);
  22792. var onload = function (img) {
  22793. // Getting height map data
  22794. var canvas = document.createElement("canvas");
  22795. var context = canvas.getContext("2d");
  22796. var bufferWidth = img.width;
  22797. var bufferHeight = img.height;
  22798. canvas.width = bufferWidth;
  22799. canvas.height = bufferHeight;
  22800. context.drawImage(img, 0, 0);
  22801. // Create VertexData from map data
  22802. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22803. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22804. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22805. width: width, height: height,
  22806. subdivisions: subdivisions,
  22807. minHeight: minHeight, maxHeight: maxHeight,
  22808. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22809. });
  22810. vertexData.applyToMesh(ground, updatable);
  22811. ground._setReady(true);
  22812. //execute ready callback, if set
  22813. if (onReady) {
  22814. onReady(ground);
  22815. }
  22816. };
  22817. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22818. return ground;
  22819. };
  22820. /**
  22821. * Creates a tube mesh.
  22822. * 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.
  22823. *
  22824. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22825. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22826. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22827. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22828. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22829. * 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.
  22830. * It must return a radius value (positive float) :
  22831. * ```javascript
  22832. * var radiusFunction = function(i, distance) {
  22833. * // do things
  22834. * return radius; }
  22835. * ```
  22836. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22837. * 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
  22838. * 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
  22839. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22840. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22841. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22843. */
  22844. MeshBuilder.CreateTube = function (name, options, scene) {
  22845. var path = options.path;
  22846. var radius = options.radius || 1.0;
  22847. var tessellation = options.tessellation || 64 | 0;
  22848. var radiusFunction = options.radiusFunction;
  22849. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22850. var invertUV = options.invertUV || false;
  22851. var updatable = options.updatable;
  22852. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22853. var instance = options.instance;
  22854. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22855. // tube geometry
  22856. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22857. var tangents = path3D.getTangents();
  22858. var normals = path3D.getNormals();
  22859. var distances = path3D.getDistances();
  22860. var pi2 = Math.PI * 2;
  22861. var step = pi2 / tessellation * arc;
  22862. var returnRadius = function () { return radius; };
  22863. var radiusFunctionFinal = radiusFunction || returnRadius;
  22864. var circlePath;
  22865. var rad;
  22866. var normal;
  22867. var rotated;
  22868. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22869. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22870. for (var i = 0; i < path.length; i++) {
  22871. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22872. circlePath = Array(); // current circle array
  22873. normal = normals[i]; // current normal
  22874. for (var t = 0; t < tessellation; t++) {
  22875. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22876. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22877. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22878. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22879. circlePath[t] = rotated;
  22880. }
  22881. circlePaths[index] = circlePath;
  22882. index++;
  22883. }
  22884. // cap
  22885. var capPath = function (nbPoints, pathIndex) {
  22886. var pointCap = Array();
  22887. for (var i = 0; i < nbPoints; i++) {
  22888. pointCap.push(path[pathIndex]);
  22889. }
  22890. return pointCap;
  22891. };
  22892. switch (cap) {
  22893. case BABYLON.Mesh.NO_CAP:
  22894. break;
  22895. case BABYLON.Mesh.CAP_START:
  22896. circlePaths[0] = capPath(tessellation, 0);
  22897. circlePaths[1] = circlePaths[2].slice(0);
  22898. break;
  22899. case BABYLON.Mesh.CAP_END:
  22900. circlePaths[index] = circlePaths[index - 1].slice(0);
  22901. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22902. break;
  22903. case BABYLON.Mesh.CAP_ALL:
  22904. circlePaths[0] = capPath(tessellation, 0);
  22905. circlePaths[1] = circlePaths[2].slice(0);
  22906. circlePaths[index] = circlePaths[index - 1].slice(0);
  22907. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22908. break;
  22909. default:
  22910. break;
  22911. }
  22912. return circlePaths;
  22913. };
  22914. var path3D;
  22915. var pathArray;
  22916. if (instance) {
  22917. var arc = options.arc || instance.arc;
  22918. path3D = (instance.path3D).update(path);
  22919. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22920. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22921. instance.path3D = path3D;
  22922. instance.pathArray = pathArray;
  22923. instance.arc = arc;
  22924. return instance;
  22925. }
  22926. // tube creation
  22927. path3D = new BABYLON.Path3D(path);
  22928. var newPathArray = new Array();
  22929. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22930. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22931. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22932. tube.pathArray = pathArray;
  22933. tube.path3D = path3D;
  22934. tube.tessellation = tessellation;
  22935. tube.cap = cap;
  22936. tube.arc = options.arc;
  22937. return tube;
  22938. };
  22939. /**
  22940. * Creates a polyhedron mesh.
  22941. *
  22942. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22943. * 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
  22944. * to choose the wanted type.
  22945. * The parameter `size` (positive float, default 1) sets the polygon size.
  22946. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22947. * 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`.
  22948. * 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
  22949. * 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)`).
  22950. * 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
  22951. * 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.
  22952. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22953. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22955. */
  22956. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22957. var polyhedron = new BABYLON.Mesh(name, scene);
  22958. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22959. polyhedron.sideOrientation = options.sideOrientation;
  22960. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22961. vertexData.applyToMesh(polyhedron, options.updatable);
  22962. return polyhedron;
  22963. };
  22964. /**
  22965. * Creates a decal mesh.
  22966. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22967. * 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.
  22968. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22969. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22970. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22971. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22972. */
  22973. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22974. var indices = sourceMesh.getIndices();
  22975. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22976. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22977. var position = options.position || BABYLON.Vector3.Zero();
  22978. var normal = options.normal || BABYLON.Vector3.Up();
  22979. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22980. var angle = options.angle || 0;
  22981. // Getting correct rotation
  22982. if (!normal) {
  22983. var target = new BABYLON.Vector3(0, 0, 1);
  22984. var camera = sourceMesh.getScene().activeCamera;
  22985. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22986. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22987. }
  22988. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22989. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22990. var pitch = Math.atan2(normal.y, len);
  22991. // Matrix
  22992. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22993. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22994. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22995. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22996. var vertexData = new BABYLON.VertexData();
  22997. vertexData.indices = [];
  22998. vertexData.positions = [];
  22999. vertexData.normals = [];
  23000. vertexData.uvs = [];
  23001. var currentVertexDataIndex = 0;
  23002. var extractDecalVector3 = function (indexId) {
  23003. var vertexId = indices[indexId];
  23004. var result = new BABYLON.PositionNormalVertex();
  23005. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23006. // Send vector to decal local world
  23007. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23008. // Get normal
  23009. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23010. return result;
  23011. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23012. var clip = function (vertices, axis) {
  23013. if (vertices.length === 0) {
  23014. return vertices;
  23015. }
  23016. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23017. var clipVertices = function (v0, v1) {
  23018. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23019. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23020. };
  23021. var result = new Array();
  23022. for (var index = 0; index < vertices.length; index += 3) {
  23023. var v1Out;
  23024. var v2Out;
  23025. var v3Out;
  23026. var total = 0;
  23027. var nV1, nV2, nV3, nV4;
  23028. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23029. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23030. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23031. v1Out = d1 > 0;
  23032. v2Out = d2 > 0;
  23033. v3Out = d3 > 0;
  23034. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23035. switch (total) {
  23036. case 0:
  23037. result.push(vertices[index]);
  23038. result.push(vertices[index + 1]);
  23039. result.push(vertices[index + 2]);
  23040. break;
  23041. case 1:
  23042. if (v1Out) {
  23043. nV1 = vertices[index + 1];
  23044. nV2 = vertices[index + 2];
  23045. nV3 = clipVertices(vertices[index], nV1);
  23046. nV4 = clipVertices(vertices[index], nV2);
  23047. }
  23048. if (v2Out) {
  23049. nV1 = vertices[index];
  23050. nV2 = vertices[index + 2];
  23051. nV3 = clipVertices(vertices[index + 1], nV1);
  23052. nV4 = clipVertices(vertices[index + 1], nV2);
  23053. result.push(nV3);
  23054. result.push(nV2.clone());
  23055. result.push(nV1.clone());
  23056. result.push(nV2.clone());
  23057. result.push(nV3.clone());
  23058. result.push(nV4);
  23059. break;
  23060. }
  23061. if (v3Out) {
  23062. nV1 = vertices[index];
  23063. nV2 = vertices[index + 1];
  23064. nV3 = clipVertices(vertices[index + 2], nV1);
  23065. nV4 = clipVertices(vertices[index + 2], nV2);
  23066. }
  23067. result.push(nV1.clone());
  23068. result.push(nV2.clone());
  23069. result.push(nV3);
  23070. result.push(nV4);
  23071. result.push(nV3.clone());
  23072. result.push(nV2.clone());
  23073. break;
  23074. case 2:
  23075. if (!v1Out) {
  23076. nV1 = vertices[index].clone();
  23077. nV2 = clipVertices(nV1, vertices[index + 1]);
  23078. nV3 = clipVertices(nV1, vertices[index + 2]);
  23079. result.push(nV1);
  23080. result.push(nV2);
  23081. result.push(nV3);
  23082. }
  23083. if (!v2Out) {
  23084. nV1 = vertices[index + 1].clone();
  23085. nV2 = clipVertices(nV1, vertices[index + 2]);
  23086. nV3 = clipVertices(nV1, vertices[index]);
  23087. result.push(nV1);
  23088. result.push(nV2);
  23089. result.push(nV3);
  23090. }
  23091. if (!v3Out) {
  23092. nV1 = vertices[index + 2].clone();
  23093. nV2 = clipVertices(nV1, vertices[index]);
  23094. nV3 = clipVertices(nV1, vertices[index + 1]);
  23095. result.push(nV1);
  23096. result.push(nV2);
  23097. result.push(nV3);
  23098. }
  23099. break;
  23100. case 3:
  23101. break;
  23102. }
  23103. }
  23104. return result;
  23105. };
  23106. for (var index = 0; index < indices.length; index += 3) {
  23107. var faceVertices = new Array();
  23108. faceVertices.push(extractDecalVector3(index));
  23109. faceVertices.push(extractDecalVector3(index + 1));
  23110. faceVertices.push(extractDecalVector3(index + 2));
  23111. // Clip
  23112. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23113. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23114. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23115. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23116. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23117. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23118. if (faceVertices.length === 0) {
  23119. continue;
  23120. }
  23121. // Add UVs and get back to world
  23122. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23123. var vertex = faceVertices[vIndex];
  23124. //TODO check for Int32Array
  23125. vertexData.indices.push(currentVertexDataIndex);
  23126. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23127. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23128. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23129. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23130. currentVertexDataIndex++;
  23131. }
  23132. }
  23133. // Return mesh
  23134. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23135. vertexData.applyToMesh(decal);
  23136. decal.position = position.clone();
  23137. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23138. return decal;
  23139. };
  23140. // Privates
  23141. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23142. // extrusion geometry
  23143. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23144. var tangents = path3D.getTangents();
  23145. var normals = path3D.getNormals();
  23146. var binormals = path3D.getBinormals();
  23147. var distances = path3D.getDistances();
  23148. var angle = 0;
  23149. var returnScale = function () { return scale; };
  23150. var returnRotation = function () { return rotation; };
  23151. var rotate = custom ? rotateFunction : returnRotation;
  23152. var scl = custom ? scaleFunction : returnScale;
  23153. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23154. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23155. for (var i = 0; i < curve.length; i++) {
  23156. var shapePath = new Array();
  23157. var angleStep = rotate(i, distances[i]);
  23158. var scaleRatio = scl(i, distances[i]);
  23159. for (var p = 0; p < shape.length; p++) {
  23160. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23161. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23162. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23163. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23164. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23165. shapePath[p] = rotated;
  23166. }
  23167. shapePaths[index] = shapePath;
  23168. angle += angleStep;
  23169. index++;
  23170. }
  23171. // cap
  23172. var capPath = function (shapePath) {
  23173. var pointCap = Array();
  23174. var barycenter = BABYLON.Vector3.Zero();
  23175. var i;
  23176. for (i = 0; i < shapePath.length; i++) {
  23177. barycenter.addInPlace(shapePath[i]);
  23178. }
  23179. barycenter.scaleInPlace(1 / shapePath.length);
  23180. for (i = 0; i < shapePath.length; i++) {
  23181. pointCap.push(barycenter);
  23182. }
  23183. return pointCap;
  23184. };
  23185. switch (cap) {
  23186. case BABYLON.Mesh.NO_CAP:
  23187. break;
  23188. case BABYLON.Mesh.CAP_START:
  23189. shapePaths[0] = capPath(shapePaths[2]);
  23190. shapePaths[1] = shapePaths[2].slice(0);
  23191. break;
  23192. case BABYLON.Mesh.CAP_END:
  23193. shapePaths[index] = shapePaths[index - 1];
  23194. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23195. break;
  23196. case BABYLON.Mesh.CAP_ALL:
  23197. shapePaths[0] = capPath(shapePaths[2]);
  23198. shapePaths[1] = shapePaths[2].slice(0);
  23199. shapePaths[index] = shapePaths[index - 1];
  23200. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23201. break;
  23202. default:
  23203. break;
  23204. }
  23205. return shapePaths;
  23206. };
  23207. var path3D;
  23208. var pathArray;
  23209. if (instance) {
  23210. path3D = (instance.path3D).update(curve);
  23211. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23212. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23213. return instance;
  23214. }
  23215. // extruded shape creation
  23216. path3D = new BABYLON.Path3D(curve);
  23217. var newShapePaths = new Array();
  23218. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23219. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23220. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23221. extrudedGeneric.pathArray = pathArray;
  23222. extrudedGeneric.path3D = path3D;
  23223. extrudedGeneric.cap = cap;
  23224. return extrudedGeneric;
  23225. };
  23226. return MeshBuilder;
  23227. }());
  23228. BABYLON.MeshBuilder = MeshBuilder;
  23229. })(BABYLON || (BABYLON = {}));
  23230. //# sourceMappingURL=babylon.meshBuilder.js.map
  23231. var BABYLON;
  23232. (function (BABYLON) {
  23233. var BaseTexture = (function () {
  23234. function BaseTexture(scene) {
  23235. this.hasAlpha = false;
  23236. this.getAlphaFromRGB = false;
  23237. this.level = 1;
  23238. this.coordinatesIndex = 0;
  23239. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23240. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23241. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23242. this.anisotropicFilteringLevel = 4;
  23243. this.isCube = false;
  23244. this.isRenderTarget = false;
  23245. this.animations = new Array();
  23246. /**
  23247. * An event triggered when the texture is disposed.
  23248. * @type {BABYLON.Observable}
  23249. */
  23250. this.onDisposeObservable = new BABYLON.Observable();
  23251. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23252. this._scene = scene;
  23253. this._scene.textures.push(this);
  23254. this._uid = null;
  23255. }
  23256. Object.defineProperty(BaseTexture.prototype, "uid", {
  23257. get: function () {
  23258. if (!this._uid) {
  23259. this._uid = BABYLON.Tools.RandomId();
  23260. }
  23261. return this._uid;
  23262. },
  23263. enumerable: true,
  23264. configurable: true
  23265. });
  23266. BaseTexture.prototype.toString = function () {
  23267. return this.name;
  23268. };
  23269. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23270. set: function (callback) {
  23271. if (this._onDisposeObserver) {
  23272. this.onDisposeObservable.remove(this._onDisposeObserver);
  23273. }
  23274. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23275. },
  23276. enumerable: true,
  23277. configurable: true
  23278. });
  23279. BaseTexture.prototype.getScene = function () {
  23280. return this._scene;
  23281. };
  23282. BaseTexture.prototype.getTextureMatrix = function () {
  23283. return null;
  23284. };
  23285. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23286. return null;
  23287. };
  23288. BaseTexture.prototype.getInternalTexture = function () {
  23289. return this._texture;
  23290. };
  23291. BaseTexture.prototype.isReady = function () {
  23292. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23293. return true;
  23294. }
  23295. if (this._texture) {
  23296. return this._texture.isReady;
  23297. }
  23298. return false;
  23299. };
  23300. BaseTexture.prototype.getSize = function () {
  23301. if (this._texture._width) {
  23302. return new BABYLON.Size(this._texture._width, this._texture._height);
  23303. }
  23304. if (this._texture._size) {
  23305. return new BABYLON.Size(this._texture._size, this._texture._size);
  23306. }
  23307. return BABYLON.Size.Zero();
  23308. };
  23309. BaseTexture.prototype.getBaseSize = function () {
  23310. if (!this.isReady() || !this._texture)
  23311. return BABYLON.Size.Zero();
  23312. if (this._texture._size) {
  23313. return new BABYLON.Size(this._texture._size, this._texture._size);
  23314. }
  23315. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  23316. };
  23317. BaseTexture.prototype.scale = function (ratio) {
  23318. };
  23319. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23320. get: function () {
  23321. return false;
  23322. },
  23323. enumerable: true,
  23324. configurable: true
  23325. });
  23326. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  23327. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23328. for (var index = 0; index < texturesCache.length; index++) {
  23329. var texturesCacheEntry = texturesCache[index];
  23330. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23331. texturesCache.splice(index, 1);
  23332. return;
  23333. }
  23334. }
  23335. };
  23336. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23337. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23338. for (var index = 0; index < texturesCache.length; index++) {
  23339. var texturesCacheEntry = texturesCache[index];
  23340. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23341. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23342. texturesCacheEntry.references++;
  23343. return texturesCacheEntry;
  23344. }
  23345. }
  23346. }
  23347. return null;
  23348. };
  23349. BaseTexture.prototype.delayLoad = function () {
  23350. };
  23351. BaseTexture.prototype.clone = function () {
  23352. return null;
  23353. };
  23354. BaseTexture.prototype.releaseInternalTexture = function () {
  23355. if (this._texture) {
  23356. this._scene.getEngine().releaseInternalTexture(this._texture);
  23357. delete this._texture;
  23358. }
  23359. };
  23360. BaseTexture.prototype.dispose = function () {
  23361. // Animations
  23362. this.getScene().stopAnimation(this);
  23363. // Remove from scene
  23364. var index = this._scene.textures.indexOf(this);
  23365. if (index >= 0) {
  23366. this._scene.textures.splice(index, 1);
  23367. }
  23368. if (this._texture === undefined) {
  23369. return;
  23370. }
  23371. // Release
  23372. this.releaseInternalTexture();
  23373. // Callback
  23374. this.onDisposeObservable.notifyObservers(this);
  23375. this.onDisposeObservable.clear();
  23376. };
  23377. BaseTexture.prototype.serialize = function () {
  23378. if (!this.name) {
  23379. return null;
  23380. }
  23381. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23382. // Animations
  23383. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23384. return serializationObject;
  23385. };
  23386. __decorate([
  23387. BABYLON.serialize()
  23388. ], BaseTexture.prototype, "name", void 0);
  23389. __decorate([
  23390. BABYLON.serialize()
  23391. ], BaseTexture.prototype, "hasAlpha", void 0);
  23392. __decorate([
  23393. BABYLON.serialize()
  23394. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23395. __decorate([
  23396. BABYLON.serialize()
  23397. ], BaseTexture.prototype, "level", void 0);
  23398. __decorate([
  23399. BABYLON.serialize()
  23400. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23401. __decorate([
  23402. BABYLON.serialize()
  23403. ], BaseTexture.prototype, "coordinatesMode", void 0);
  23404. __decorate([
  23405. BABYLON.serialize()
  23406. ], BaseTexture.prototype, "wrapU", void 0);
  23407. __decorate([
  23408. BABYLON.serialize()
  23409. ], BaseTexture.prototype, "wrapV", void 0);
  23410. __decorate([
  23411. BABYLON.serialize()
  23412. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23413. __decorate([
  23414. BABYLON.serialize()
  23415. ], BaseTexture.prototype, "isCube", void 0);
  23416. __decorate([
  23417. BABYLON.serialize()
  23418. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23419. return BaseTexture;
  23420. }());
  23421. BABYLON.BaseTexture = BaseTexture;
  23422. })(BABYLON || (BABYLON = {}));
  23423. //# sourceMappingURL=babylon.baseTexture.js.map
  23424. var BABYLON;
  23425. (function (BABYLON) {
  23426. var Texture = (function (_super) {
  23427. __extends(Texture, _super);
  23428. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  23429. var _this = this;
  23430. if (noMipmap === void 0) { noMipmap = false; }
  23431. if (invertY === void 0) { invertY = true; }
  23432. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23433. if (onLoad === void 0) { onLoad = null; }
  23434. if (onError === void 0) { onError = null; }
  23435. if (buffer === void 0) { buffer = null; }
  23436. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23437. _super.call(this, scene);
  23438. this.uOffset = 0;
  23439. this.vOffset = 0;
  23440. this.uScale = 1.0;
  23441. this.vScale = 1.0;
  23442. this.uAng = 0;
  23443. this.vAng = 0;
  23444. this.wAng = 0;
  23445. this.name = url;
  23446. this.url = url;
  23447. this._noMipmap = noMipmap;
  23448. this._invertY = invertY;
  23449. this._samplingMode = samplingMode;
  23450. this._buffer = buffer;
  23451. this._deleteBuffer = deleteBuffer;
  23452. if (!url) {
  23453. return;
  23454. }
  23455. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  23456. var load = function () {
  23457. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23458. _this.onLoadObservable.notifyObservers(true);
  23459. }
  23460. if (onLoad) {
  23461. onLoad();
  23462. }
  23463. };
  23464. if (!this._texture) {
  23465. if (!scene.useDelayedTextureLoading) {
  23466. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  23467. if (deleteBuffer) {
  23468. delete this._buffer;
  23469. }
  23470. }
  23471. else {
  23472. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23473. this._delayedOnLoad = load;
  23474. this._delayedOnError = onError;
  23475. }
  23476. }
  23477. else {
  23478. if (this._texture.isReady) {
  23479. BABYLON.Tools.SetImmediate(function () { return load(); });
  23480. }
  23481. else {
  23482. this._texture.onLoadedCallbacks.push(load);
  23483. }
  23484. }
  23485. }
  23486. Object.defineProperty(Texture.prototype, "noMipmap", {
  23487. get: function () {
  23488. return this._noMipmap;
  23489. },
  23490. enumerable: true,
  23491. configurable: true
  23492. });
  23493. Texture.prototype.delayLoad = function () {
  23494. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23495. return;
  23496. }
  23497. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23498. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23499. if (!this._texture) {
  23500. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23501. if (this._deleteBuffer) {
  23502. delete this._buffer;
  23503. }
  23504. }
  23505. };
  23506. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23507. if (!this._texture) {
  23508. return;
  23509. }
  23510. this._samplingMode = samplingMode;
  23511. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23512. };
  23513. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23514. x *= this.uScale;
  23515. y *= this.vScale;
  23516. x -= 0.5 * this.uScale;
  23517. y -= 0.5 * this.vScale;
  23518. z -= 0.5;
  23519. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23520. t.x += 0.5 * this.uScale + this.uOffset;
  23521. t.y += 0.5 * this.vScale + this.vOffset;
  23522. t.z += 0.5;
  23523. };
  23524. Texture.prototype.getTextureMatrix = function () {
  23525. if (this.uOffset === this._cachedUOffset &&
  23526. this.vOffset === this._cachedVOffset &&
  23527. this.uScale === this._cachedUScale &&
  23528. this.vScale === this._cachedVScale &&
  23529. this.uAng === this._cachedUAng &&
  23530. this.vAng === this._cachedVAng &&
  23531. this.wAng === this._cachedWAng) {
  23532. return this._cachedTextureMatrix;
  23533. }
  23534. this._cachedUOffset = this.uOffset;
  23535. this._cachedVOffset = this.vOffset;
  23536. this._cachedUScale = this.uScale;
  23537. this._cachedVScale = this.vScale;
  23538. this._cachedUAng = this.uAng;
  23539. this._cachedVAng = this.vAng;
  23540. this._cachedWAng = this.wAng;
  23541. if (!this._cachedTextureMatrix) {
  23542. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23543. this._rowGenerationMatrix = new BABYLON.Matrix();
  23544. this._t0 = BABYLON.Vector3.Zero();
  23545. this._t1 = BABYLON.Vector3.Zero();
  23546. this._t2 = BABYLON.Vector3.Zero();
  23547. }
  23548. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23549. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23550. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23551. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23552. this._t1.subtractInPlace(this._t0);
  23553. this._t2.subtractInPlace(this._t0);
  23554. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23555. this._cachedTextureMatrix.m[0] = this._t1.x;
  23556. this._cachedTextureMatrix.m[1] = this._t1.y;
  23557. this._cachedTextureMatrix.m[2] = this._t1.z;
  23558. this._cachedTextureMatrix.m[4] = this._t2.x;
  23559. this._cachedTextureMatrix.m[5] = this._t2.y;
  23560. this._cachedTextureMatrix.m[6] = this._t2.z;
  23561. this._cachedTextureMatrix.m[8] = this._t0.x;
  23562. this._cachedTextureMatrix.m[9] = this._t0.y;
  23563. this._cachedTextureMatrix.m[10] = this._t0.z;
  23564. return this._cachedTextureMatrix;
  23565. };
  23566. Texture.prototype.getReflectionTextureMatrix = function () {
  23567. if (this.uOffset === this._cachedUOffset &&
  23568. this.vOffset === this._cachedVOffset &&
  23569. this.uScale === this._cachedUScale &&
  23570. this.vScale === this._cachedVScale &&
  23571. this.coordinatesMode === this._cachedCoordinatesMode) {
  23572. return this._cachedTextureMatrix;
  23573. }
  23574. if (!this._cachedTextureMatrix) {
  23575. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23576. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23577. }
  23578. this._cachedCoordinatesMode = this.coordinatesMode;
  23579. switch (this.coordinatesMode) {
  23580. case Texture.PLANAR_MODE:
  23581. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23582. this._cachedTextureMatrix[0] = this.uScale;
  23583. this._cachedTextureMatrix[5] = this.vScale;
  23584. this._cachedTextureMatrix[12] = this.uOffset;
  23585. this._cachedTextureMatrix[13] = this.vOffset;
  23586. break;
  23587. case Texture.PROJECTION_MODE:
  23588. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23589. this._projectionModeMatrix.m[0] = 0.5;
  23590. this._projectionModeMatrix.m[5] = -0.5;
  23591. this._projectionModeMatrix.m[10] = 0.0;
  23592. this._projectionModeMatrix.m[12] = 0.5;
  23593. this._projectionModeMatrix.m[13] = 0.5;
  23594. this._projectionModeMatrix.m[14] = 1.0;
  23595. this._projectionModeMatrix.m[15] = 1.0;
  23596. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23597. break;
  23598. default:
  23599. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23600. break;
  23601. }
  23602. return this._cachedTextureMatrix;
  23603. };
  23604. Texture.prototype.clone = function () {
  23605. var _this = this;
  23606. return BABYLON.SerializationHelper.Clone(function () {
  23607. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23608. }, this);
  23609. };
  23610. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23611. get: function () {
  23612. if (!this._onLoadObservarble) {
  23613. this._onLoadObservarble = new BABYLON.Observable();
  23614. }
  23615. return this._onLoadObservarble;
  23616. },
  23617. enumerable: true,
  23618. configurable: true
  23619. });
  23620. // Statics
  23621. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23622. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23623. if (onLoad === void 0) { onLoad = null; }
  23624. if (onError === void 0) { onError = null; }
  23625. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23626. };
  23627. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23628. if (parsedTexture.customType) {
  23629. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23630. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23631. }
  23632. if (parsedTexture.isCube) {
  23633. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23634. }
  23635. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23636. return null;
  23637. }
  23638. var texture = BABYLON.SerializationHelper.Parse(function () {
  23639. if (parsedTexture.mirrorPlane) {
  23640. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23641. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23642. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23643. return mirrorTexture;
  23644. }
  23645. else if (parsedTexture.isRenderTarget) {
  23646. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23647. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23648. return renderTargetTexture;
  23649. }
  23650. else {
  23651. var texture;
  23652. if (parsedTexture.base64String) {
  23653. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23654. }
  23655. else {
  23656. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23657. }
  23658. return texture;
  23659. }
  23660. }, parsedTexture, scene);
  23661. // Animations
  23662. if (parsedTexture.animations) {
  23663. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23664. var parsedAnimation = parsedTexture.animations[animationIndex];
  23665. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23666. }
  23667. }
  23668. return texture;
  23669. };
  23670. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  23671. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23672. if (noMipmap === void 0) { noMipmap = false; }
  23673. if (invertY === void 0) { invertY = true; }
  23674. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23675. if (onLoad === void 0) { onLoad = null; }
  23676. if (onError === void 0) { onError = null; }
  23677. if (name.substr(0, 5) !== "data:") {
  23678. name = "data:" + name;
  23679. }
  23680. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  23681. };
  23682. // Constants
  23683. Texture.NEAREST_SAMPLINGMODE = 1;
  23684. Texture.BILINEAR_SAMPLINGMODE = 2;
  23685. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23686. Texture.EXPLICIT_MODE = 0;
  23687. Texture.SPHERICAL_MODE = 1;
  23688. Texture.PLANAR_MODE = 2;
  23689. Texture.CUBIC_MODE = 3;
  23690. Texture.PROJECTION_MODE = 4;
  23691. Texture.SKYBOX_MODE = 5;
  23692. Texture.INVCUBIC_MODE = 6;
  23693. Texture.EQUIRECTANGULAR_MODE = 7;
  23694. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23695. Texture.CLAMP_ADDRESSMODE = 0;
  23696. Texture.WRAP_ADDRESSMODE = 1;
  23697. Texture.MIRROR_ADDRESSMODE = 2;
  23698. __decorate([
  23699. BABYLON.serialize()
  23700. ], Texture.prototype, "url", void 0);
  23701. __decorate([
  23702. BABYLON.serialize()
  23703. ], Texture.prototype, "uOffset", void 0);
  23704. __decorate([
  23705. BABYLON.serialize()
  23706. ], Texture.prototype, "vOffset", void 0);
  23707. __decorate([
  23708. BABYLON.serialize()
  23709. ], Texture.prototype, "uScale", void 0);
  23710. __decorate([
  23711. BABYLON.serialize()
  23712. ], Texture.prototype, "vScale", void 0);
  23713. __decorate([
  23714. BABYLON.serialize()
  23715. ], Texture.prototype, "uAng", void 0);
  23716. __decorate([
  23717. BABYLON.serialize()
  23718. ], Texture.prototype, "vAng", void 0);
  23719. __decorate([
  23720. BABYLON.serialize()
  23721. ], Texture.prototype, "wAng", void 0);
  23722. return Texture;
  23723. }(BABYLON.BaseTexture));
  23724. BABYLON.Texture = Texture;
  23725. })(BABYLON || (BABYLON = {}));
  23726. //# sourceMappingURL=babylon.texture.js.map
  23727. var BABYLON;
  23728. (function (BABYLON) {
  23729. var CubeTexture = (function (_super) {
  23730. __extends(CubeTexture, _super);
  23731. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23732. if (onLoad === void 0) { onLoad = null; }
  23733. if (onError === void 0) { onError = null; }
  23734. _super.call(this, scene);
  23735. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23736. this.name = rootUrl;
  23737. this.url = rootUrl;
  23738. this._noMipmap = noMipmap;
  23739. this.hasAlpha = false;
  23740. if (!rootUrl && !files) {
  23741. return;
  23742. }
  23743. this._texture = this._getFromCache(rootUrl, noMipmap);
  23744. if (!files) {
  23745. if (!extensions) {
  23746. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23747. }
  23748. files = [];
  23749. for (var index = 0; index < extensions.length; index++) {
  23750. files.push(rootUrl + extensions[index]);
  23751. }
  23752. this._extensions = extensions;
  23753. }
  23754. this._files = files;
  23755. if (!this._texture) {
  23756. if (!scene.useDelayedTextureLoading) {
  23757. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23758. }
  23759. else {
  23760. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23761. }
  23762. }
  23763. else if (onLoad) {
  23764. if (this._texture.isReady) {
  23765. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23766. }
  23767. else {
  23768. this._texture.onLoadedCallbacks.push(onLoad);
  23769. }
  23770. }
  23771. this.isCube = true;
  23772. this._textureMatrix = BABYLON.Matrix.Identity();
  23773. }
  23774. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23775. return new CubeTexture("", scene, null, noMipmap, files);
  23776. };
  23777. // Methods
  23778. CubeTexture.prototype.delayLoad = function () {
  23779. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23780. return;
  23781. }
  23782. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23783. this._texture = this._getFromCache(this.url, this._noMipmap);
  23784. if (!this._texture) {
  23785. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23786. }
  23787. };
  23788. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23789. return this._textureMatrix;
  23790. };
  23791. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23792. var texture = BABYLON.SerializationHelper.Parse(function () {
  23793. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23794. }, parsedTexture, scene);
  23795. // Animations
  23796. if (parsedTexture.animations) {
  23797. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23798. var parsedAnimation = parsedTexture.animations[animationIndex];
  23799. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23800. }
  23801. }
  23802. return texture;
  23803. };
  23804. CubeTexture.prototype.clone = function () {
  23805. var _this = this;
  23806. return BABYLON.SerializationHelper.Clone(function () {
  23807. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23808. }, this);
  23809. };
  23810. return CubeTexture;
  23811. }(BABYLON.BaseTexture));
  23812. BABYLON.CubeTexture = CubeTexture;
  23813. })(BABYLON || (BABYLON = {}));
  23814. //# sourceMappingURL=babylon.cubeTexture.js.map
  23815. var BABYLON;
  23816. (function (BABYLON) {
  23817. var RenderTargetTexture = (function (_super) {
  23818. __extends(RenderTargetTexture, _super);
  23819. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23820. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23821. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23822. if (isCube === void 0) { isCube = false; }
  23823. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23824. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23825. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23826. _super.call(this, null, scene, !generateMipMaps);
  23827. this.isCube = isCube;
  23828. /**
  23829. * Use this list to define the list of mesh you want to render.
  23830. */
  23831. this.renderList = new Array();
  23832. this.renderParticles = true;
  23833. this.renderSprites = false;
  23834. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23835. // Events
  23836. /**
  23837. * An event triggered when the texture is unbind.
  23838. * @type {BABYLON.Observable}
  23839. */
  23840. this.onAfterUnbindObservable = new BABYLON.Observable();
  23841. /**
  23842. * An event triggered before rendering the texture
  23843. * @type {BABYLON.Observable}
  23844. */
  23845. this.onBeforeRenderObservable = new BABYLON.Observable();
  23846. /**
  23847. * An event triggered after rendering the texture
  23848. * @type {BABYLON.Observable}
  23849. */
  23850. this.onAfterRenderObservable = new BABYLON.Observable();
  23851. /**
  23852. * An event triggered after the texture clear
  23853. * @type {BABYLON.Observable}
  23854. */
  23855. this.onClearObservable = new BABYLON.Observable();
  23856. this._currentRefreshId = -1;
  23857. this._refreshRate = 1;
  23858. this.name = name;
  23859. this.isRenderTarget = true;
  23860. this._size = size;
  23861. this._generateMipMaps = generateMipMaps;
  23862. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23863. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23864. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23865. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23866. }
  23867. if (isCube) {
  23868. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23869. generateMipMaps: generateMipMaps,
  23870. samplingMode: samplingMode,
  23871. generateDepthBuffer: generateDepthBuffer,
  23872. generateStencilBuffer: generateStencilBuffer
  23873. });
  23874. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23875. this._textureMatrix = BABYLON.Matrix.Identity();
  23876. }
  23877. else {
  23878. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23879. generateMipMaps: generateMipMaps,
  23880. type: type,
  23881. samplingMode: samplingMode,
  23882. generateDepthBuffer: generateDepthBuffer,
  23883. generateStencilBuffer: generateStencilBuffer
  23884. });
  23885. }
  23886. // Rendering groups
  23887. this._renderingManager = new BABYLON.RenderingManager(scene);
  23888. }
  23889. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23890. get: function () {
  23891. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23892. },
  23893. enumerable: true,
  23894. configurable: true
  23895. });
  23896. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23897. get: function () {
  23898. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23899. },
  23900. enumerable: true,
  23901. configurable: true
  23902. });
  23903. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23904. get: function () {
  23905. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23906. },
  23907. enumerable: true,
  23908. configurable: true
  23909. });
  23910. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23911. set: function (callback) {
  23912. if (this._onAfterUnbindObserver) {
  23913. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23914. }
  23915. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23916. },
  23917. enumerable: true,
  23918. configurable: true
  23919. });
  23920. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23921. set: function (callback) {
  23922. if (this._onBeforeRenderObserver) {
  23923. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23924. }
  23925. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23926. },
  23927. enumerable: true,
  23928. configurable: true
  23929. });
  23930. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23931. set: function (callback) {
  23932. if (this._onAfterRenderObserver) {
  23933. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23934. }
  23935. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23936. },
  23937. enumerable: true,
  23938. configurable: true
  23939. });
  23940. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23941. set: function (callback) {
  23942. if (this._onClearObserver) {
  23943. this.onClearObservable.remove(this._onClearObserver);
  23944. }
  23945. this._onClearObserver = this.onClearObservable.add(callback);
  23946. },
  23947. enumerable: true,
  23948. configurable: true
  23949. });
  23950. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23951. this._currentRefreshId = -1;
  23952. };
  23953. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23954. get: function () {
  23955. return this._refreshRate;
  23956. },
  23957. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23958. set: function (value) {
  23959. this._refreshRate = value;
  23960. this.resetRefreshCounter();
  23961. },
  23962. enumerable: true,
  23963. configurable: true
  23964. });
  23965. RenderTargetTexture.prototype._shouldRender = function () {
  23966. if (this._currentRefreshId === -1) {
  23967. this._currentRefreshId = 1;
  23968. return true;
  23969. }
  23970. if (this.refreshRate === this._currentRefreshId) {
  23971. this._currentRefreshId = 1;
  23972. return true;
  23973. }
  23974. this._currentRefreshId++;
  23975. return false;
  23976. };
  23977. RenderTargetTexture.prototype.isReady = function () {
  23978. if (!this.getScene().renderTargetsEnabled) {
  23979. return false;
  23980. }
  23981. return _super.prototype.isReady.call(this);
  23982. };
  23983. RenderTargetTexture.prototype.getRenderSize = function () {
  23984. return this._size;
  23985. };
  23986. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23987. get: function () {
  23988. return true;
  23989. },
  23990. enumerable: true,
  23991. configurable: true
  23992. });
  23993. RenderTargetTexture.prototype.scale = function (ratio) {
  23994. var newSize = this._size * ratio;
  23995. this.resize(newSize, this._generateMipMaps);
  23996. };
  23997. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23998. if (this.isCube) {
  23999. return this._textureMatrix;
  24000. }
  24001. return _super.prototype.getReflectionTextureMatrix.call(this);
  24002. };
  24003. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  24004. this.releaseInternalTexture();
  24005. if (this.isCube) {
  24006. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  24007. }
  24008. else {
  24009. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24010. }
  24011. };
  24012. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24013. var scene = this.getScene();
  24014. if (this.useCameraPostProcesses !== undefined) {
  24015. useCameraPostProcess = this.useCameraPostProcesses;
  24016. }
  24017. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24018. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24019. }
  24020. if (this._waitingRenderList) {
  24021. this.renderList = [];
  24022. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24023. var id = this._waitingRenderList[index];
  24024. this.renderList.push(scene.getMeshByID(id));
  24025. }
  24026. delete this._waitingRenderList;
  24027. }
  24028. // Is predicate defined?
  24029. if (this.renderListPredicate) {
  24030. this.renderList.splice(0); // Clear previous renderList
  24031. var sceneMeshes = this.getScene().meshes;
  24032. for (var index = 0; index < sceneMeshes.length; index++) {
  24033. var mesh = sceneMeshes[index];
  24034. if (this.renderListPredicate(mesh)) {
  24035. this.renderList.push(mesh);
  24036. }
  24037. }
  24038. }
  24039. if (this.renderList && this.renderList.length === 0) {
  24040. return;
  24041. }
  24042. // Prepare renderingManager
  24043. this._renderingManager.reset();
  24044. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24045. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24046. var sceneRenderId = scene.getRenderId();
  24047. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24048. var mesh = currentRenderList[meshIndex];
  24049. if (mesh) {
  24050. if (!mesh.isReady()) {
  24051. // Reset _currentRefreshId
  24052. this.resetRefreshCounter();
  24053. continue;
  24054. }
  24055. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24056. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24057. mesh._activate(sceneRenderId);
  24058. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24059. var subMesh = mesh.subMeshes[subIndex];
  24060. scene._activeIndices.addCount(subMesh.indexCount, false);
  24061. this._renderingManager.dispatch(subMesh);
  24062. }
  24063. }
  24064. }
  24065. }
  24066. if (this.isCube) {
  24067. for (var face = 0; face < 6; face++) {
  24068. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24069. scene.incrementRenderId();
  24070. scene.resetCachedMaterial();
  24071. }
  24072. }
  24073. else {
  24074. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24075. }
  24076. this.onAfterUnbindObservable.notifyObservers(this);
  24077. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24078. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24079. }
  24080. scene.resetCachedMaterial();
  24081. };
  24082. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24083. var scene = this.getScene();
  24084. var engine = scene.getEngine();
  24085. // Bind
  24086. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24087. if (this.isCube) {
  24088. engine.bindFramebuffer(this._texture, faceIndex);
  24089. }
  24090. else {
  24091. engine.bindFramebuffer(this._texture);
  24092. }
  24093. }
  24094. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24095. // Clear
  24096. if (this.onClearObservable.hasObservers()) {
  24097. this.onClearObservable.notifyObservers(engine);
  24098. }
  24099. else {
  24100. engine.clear(scene.clearColor, true, true, true);
  24101. }
  24102. if (!this._doNotChangeAspectRatio) {
  24103. scene.updateTransformMatrix(true);
  24104. }
  24105. // Render
  24106. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24107. if (useCameraPostProcess) {
  24108. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24109. }
  24110. if (!this._doNotChangeAspectRatio) {
  24111. scene.updateTransformMatrix(true);
  24112. }
  24113. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24114. // Dump ?
  24115. if (dumpForDebug) {
  24116. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24117. }
  24118. // Unbind
  24119. if (!this.isCube || faceIndex === 5) {
  24120. if (this.isCube) {
  24121. if (faceIndex === 5) {
  24122. engine.generateMipMapsForCubemap(this._texture);
  24123. }
  24124. }
  24125. engine.unBindFramebuffer(this._texture, this.isCube);
  24126. }
  24127. };
  24128. /**
  24129. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24130. * This allowed control for front to back rendering or reversly depending of the special needs.
  24131. *
  24132. * @param renderingGroupId The rendering group id corresponding to its index
  24133. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24134. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24135. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24136. */
  24137. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24138. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24139. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24140. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24141. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24142. };
  24143. /**
  24144. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24145. *
  24146. * @param renderingGroupId The rendering group id corresponding to its index
  24147. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24148. */
  24149. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24150. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24151. };
  24152. RenderTargetTexture.prototype.clone = function () {
  24153. var textureSize = this.getSize();
  24154. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24155. // Base texture
  24156. newTexture.hasAlpha = this.hasAlpha;
  24157. newTexture.level = this.level;
  24158. // RenderTarget Texture
  24159. newTexture.coordinatesMode = this.coordinatesMode;
  24160. newTexture.renderList = this.renderList.slice(0);
  24161. return newTexture;
  24162. };
  24163. RenderTargetTexture.prototype.serialize = function () {
  24164. if (!this.name) {
  24165. return null;
  24166. }
  24167. var serializationObject = _super.prototype.serialize.call(this);
  24168. serializationObject.renderTargetSize = this.getRenderSize();
  24169. serializationObject.renderList = [];
  24170. for (var index = 0; index < this.renderList.length; index++) {
  24171. serializationObject.renderList.push(this.renderList[index].id);
  24172. }
  24173. return serializationObject;
  24174. };
  24175. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24176. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24177. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24178. return RenderTargetTexture;
  24179. }(BABYLON.Texture));
  24180. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24181. })(BABYLON || (BABYLON = {}));
  24182. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  24183. var BABYLON;
  24184. (function (BABYLON) {
  24185. var ProceduralTexture = (function (_super) {
  24186. __extends(ProceduralTexture, _super);
  24187. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24188. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24189. if (isCube === void 0) { isCube = false; }
  24190. _super.call(this, null, scene, !generateMipMaps);
  24191. this.isCube = isCube;
  24192. this.isEnabled = true;
  24193. this._currentRefreshId = -1;
  24194. this._refreshRate = 1;
  24195. this._vertexBuffers = {};
  24196. this._uniforms = new Array();
  24197. this._samplers = new Array();
  24198. this._textures = new Array();
  24199. this._floats = new Array();
  24200. this._floatsArrays = {};
  24201. this._colors3 = new Array();
  24202. this._colors4 = new Array();
  24203. this._vectors2 = new Array();
  24204. this._vectors3 = new Array();
  24205. this._matrices = new Array();
  24206. this._fallbackTextureUsed = false;
  24207. scene._proceduralTextures.push(this);
  24208. this.name = name;
  24209. this.isRenderTarget = true;
  24210. this._size = size;
  24211. this._generateMipMaps = generateMipMaps;
  24212. this.setFragment(fragment);
  24213. this._fallbackTexture = fallbackTexture;
  24214. var engine = scene.getEngine();
  24215. if (isCube) {
  24216. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24217. this.setFloat("face", 0);
  24218. }
  24219. else {
  24220. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24221. }
  24222. // VBO
  24223. var vertices = [];
  24224. vertices.push(1, 1);
  24225. vertices.push(-1, 1);
  24226. vertices.push(-1, -1);
  24227. vertices.push(1, -1);
  24228. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24229. // Indices
  24230. var indices = [];
  24231. indices.push(0);
  24232. indices.push(1);
  24233. indices.push(2);
  24234. indices.push(0);
  24235. indices.push(2);
  24236. indices.push(3);
  24237. this._indexBuffer = engine.createIndexBuffer(indices);
  24238. }
  24239. ProceduralTexture.prototype.reset = function () {
  24240. if (this._effect === undefined) {
  24241. return;
  24242. }
  24243. var engine = this.getScene().getEngine();
  24244. engine._releaseEffect(this._effect);
  24245. };
  24246. ProceduralTexture.prototype.isReady = function () {
  24247. var _this = this;
  24248. var engine = this.getScene().getEngine();
  24249. var shaders;
  24250. if (!this._fragment) {
  24251. return false;
  24252. }
  24253. if (this._fallbackTextureUsed) {
  24254. return true;
  24255. }
  24256. if (this._fragment.fragmentElement !== undefined) {
  24257. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24258. }
  24259. else {
  24260. shaders = { vertex: "procedural", fragment: this._fragment };
  24261. }
  24262. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24263. _this.releaseInternalTexture();
  24264. if (_this._fallbackTexture) {
  24265. _this._texture = _this._fallbackTexture._texture;
  24266. _this._texture.references++;
  24267. }
  24268. _this._fallbackTextureUsed = true;
  24269. });
  24270. return this._effect.isReady();
  24271. };
  24272. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24273. this._currentRefreshId = -1;
  24274. };
  24275. ProceduralTexture.prototype.setFragment = function (fragment) {
  24276. this._fragment = fragment;
  24277. };
  24278. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24279. get: function () {
  24280. return this._refreshRate;
  24281. },
  24282. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24283. set: function (value) {
  24284. this._refreshRate = value;
  24285. this.resetRefreshCounter();
  24286. },
  24287. enumerable: true,
  24288. configurable: true
  24289. });
  24290. ProceduralTexture.prototype._shouldRender = function () {
  24291. if (!this.isEnabled || !this.isReady() || !this._texture) {
  24292. return false;
  24293. }
  24294. if (this._fallbackTextureUsed) {
  24295. return false;
  24296. }
  24297. if (this._currentRefreshId === -1) {
  24298. this._currentRefreshId = 1;
  24299. return true;
  24300. }
  24301. if (this.refreshRate === this._currentRefreshId) {
  24302. this._currentRefreshId = 1;
  24303. return true;
  24304. }
  24305. this._currentRefreshId++;
  24306. return false;
  24307. };
  24308. ProceduralTexture.prototype.getRenderSize = function () {
  24309. return this._size;
  24310. };
  24311. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  24312. if (this._fallbackTextureUsed) {
  24313. return;
  24314. }
  24315. this.releaseInternalTexture();
  24316. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24317. };
  24318. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  24319. if (this._uniforms.indexOf(uniformName) === -1) {
  24320. this._uniforms.push(uniformName);
  24321. }
  24322. };
  24323. ProceduralTexture.prototype.setTexture = function (name, texture) {
  24324. if (this._samplers.indexOf(name) === -1) {
  24325. this._samplers.push(name);
  24326. }
  24327. this._textures[name] = texture;
  24328. return this;
  24329. };
  24330. ProceduralTexture.prototype.setFloat = function (name, value) {
  24331. this._checkUniform(name);
  24332. this._floats[name] = value;
  24333. return this;
  24334. };
  24335. ProceduralTexture.prototype.setFloats = function (name, value) {
  24336. this._checkUniform(name);
  24337. this._floatsArrays[name] = value;
  24338. return this;
  24339. };
  24340. ProceduralTexture.prototype.setColor3 = function (name, value) {
  24341. this._checkUniform(name);
  24342. this._colors3[name] = value;
  24343. return this;
  24344. };
  24345. ProceduralTexture.prototype.setColor4 = function (name, value) {
  24346. this._checkUniform(name);
  24347. this._colors4[name] = value;
  24348. return this;
  24349. };
  24350. ProceduralTexture.prototype.setVector2 = function (name, value) {
  24351. this._checkUniform(name);
  24352. this._vectors2[name] = value;
  24353. return this;
  24354. };
  24355. ProceduralTexture.prototype.setVector3 = function (name, value) {
  24356. this._checkUniform(name);
  24357. this._vectors3[name] = value;
  24358. return this;
  24359. };
  24360. ProceduralTexture.prototype.setMatrix = function (name, value) {
  24361. this._checkUniform(name);
  24362. this._matrices[name] = value;
  24363. return this;
  24364. };
  24365. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24366. var scene = this.getScene();
  24367. var engine = scene.getEngine();
  24368. // Render
  24369. engine.enableEffect(this._effect);
  24370. engine.setState(false);
  24371. // Texture
  24372. for (var name in this._textures) {
  24373. this._effect.setTexture(name, this._textures[name]);
  24374. }
  24375. // Float
  24376. for (name in this._floats) {
  24377. this._effect.setFloat(name, this._floats[name]);
  24378. }
  24379. // Floats
  24380. for (name in this._floatsArrays) {
  24381. this._effect.setArray(name, this._floatsArrays[name]);
  24382. }
  24383. // Color3
  24384. for (name in this._colors3) {
  24385. this._effect.setColor3(name, this._colors3[name]);
  24386. }
  24387. // Color4
  24388. for (name in this._colors4) {
  24389. var color = this._colors4[name];
  24390. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24391. }
  24392. // Vector2
  24393. for (name in this._vectors2) {
  24394. this._effect.setVector2(name, this._vectors2[name]);
  24395. }
  24396. // Vector3
  24397. for (name in this._vectors3) {
  24398. this._effect.setVector3(name, this._vectors3[name]);
  24399. }
  24400. // Matrix
  24401. for (name in this._matrices) {
  24402. this._effect.setMatrix(name, this._matrices[name]);
  24403. }
  24404. // VBOs
  24405. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  24406. if (this.isCube) {
  24407. for (var face = 0; face < 6; face++) {
  24408. engine.bindFramebuffer(this._texture, face);
  24409. this._effect.setFloat("face", face);
  24410. // Clear
  24411. engine.clear(scene.clearColor, true, true, true);
  24412. // Draw order
  24413. engine.draw(true, 0, 6);
  24414. // Mipmaps
  24415. if (face === 5) {
  24416. engine.generateMipMapsForCubemap(this._texture);
  24417. }
  24418. }
  24419. }
  24420. else {
  24421. engine.bindFramebuffer(this._texture);
  24422. // Clear
  24423. engine.clear(scene.clearColor, true, true, true);
  24424. // Draw order
  24425. engine.draw(true, 0, 6);
  24426. }
  24427. // Unbind
  24428. engine.unBindFramebuffer(this._texture, this.isCube);
  24429. if (this.onGenerated) {
  24430. this.onGenerated();
  24431. }
  24432. };
  24433. ProceduralTexture.prototype.clone = function () {
  24434. var textureSize = this.getSize();
  24435. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  24436. // Base texture
  24437. newTexture.hasAlpha = this.hasAlpha;
  24438. newTexture.level = this.level;
  24439. // RenderTarget Texture
  24440. newTexture.coordinatesMode = this.coordinatesMode;
  24441. return newTexture;
  24442. };
  24443. ProceduralTexture.prototype.dispose = function () {
  24444. var index = this.getScene()._proceduralTextures.indexOf(this);
  24445. if (index >= 0) {
  24446. this.getScene()._proceduralTextures.splice(index, 1);
  24447. }
  24448. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  24449. if (vertexBuffer) {
  24450. vertexBuffer.dispose();
  24451. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  24452. }
  24453. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  24454. this._indexBuffer = null;
  24455. }
  24456. _super.prototype.dispose.call(this);
  24457. };
  24458. return ProceduralTexture;
  24459. }(BABYLON.Texture));
  24460. BABYLON.ProceduralTexture = ProceduralTexture;
  24461. })(BABYLON || (BABYLON = {}));
  24462. //# sourceMappingURL=babylon.proceduralTexture.js.map
  24463. var BABYLON;
  24464. (function (BABYLON) {
  24465. var MirrorTexture = (function (_super) {
  24466. __extends(MirrorTexture, _super);
  24467. function MirrorTexture(name, size, scene, generateMipMaps) {
  24468. var _this = this;
  24469. _super.call(this, name, size, scene, generateMipMaps, true);
  24470. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24471. this._transformMatrix = BABYLON.Matrix.Zero();
  24472. this._mirrorMatrix = BABYLON.Matrix.Zero();
  24473. this.onBeforeRenderObservable.add(function () {
  24474. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24475. _this._savedViewMatrix = scene.getViewMatrix();
  24476. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24477. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24478. scene.clipPlane = _this.mirrorPlane;
  24479. scene.getEngine().cullBackFaces = false;
  24480. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24481. });
  24482. this.onAfterRenderObservable.add(function () {
  24483. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24484. scene.getEngine().cullBackFaces = true;
  24485. scene._mirroredCameraPosition = null;
  24486. delete scene.clipPlane;
  24487. });
  24488. }
  24489. MirrorTexture.prototype.clone = function () {
  24490. var textureSize = this.getSize();
  24491. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24492. // Base texture
  24493. newTexture.hasAlpha = this.hasAlpha;
  24494. newTexture.level = this.level;
  24495. // Mirror Texture
  24496. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24497. newTexture.renderList = this.renderList.slice(0);
  24498. return newTexture;
  24499. };
  24500. MirrorTexture.prototype.serialize = function () {
  24501. if (!this.name) {
  24502. return null;
  24503. }
  24504. var serializationObject = _super.prototype.serialize.call(this);
  24505. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24506. return serializationObject;
  24507. };
  24508. return MirrorTexture;
  24509. }(BABYLON.RenderTargetTexture));
  24510. BABYLON.MirrorTexture = MirrorTexture;
  24511. })(BABYLON || (BABYLON = {}));
  24512. //# sourceMappingURL=babylon.mirrorTexture.js.map
  24513. var BABYLON;
  24514. (function (BABYLON) {
  24515. /**
  24516. * Creates a refraction texture used by refraction channel of the standard material.
  24517. * @param name the texture name
  24518. * @param size size of the underlying texture
  24519. * @param scene root scene
  24520. */
  24521. var RefractionTexture = (function (_super) {
  24522. __extends(RefractionTexture, _super);
  24523. function RefractionTexture(name, size, scene, generateMipMaps) {
  24524. var _this = this;
  24525. _super.call(this, name, size, scene, generateMipMaps, true);
  24526. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24527. this.depth = 2.0;
  24528. this.onBeforeRenderObservable.add(function () {
  24529. scene.clipPlane = _this.refractionPlane;
  24530. });
  24531. this.onAfterRenderObservable.add(function () {
  24532. delete scene.clipPlane;
  24533. });
  24534. }
  24535. RefractionTexture.prototype.clone = function () {
  24536. var textureSize = this.getSize();
  24537. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24538. // Base texture
  24539. newTexture.hasAlpha = this.hasAlpha;
  24540. newTexture.level = this.level;
  24541. // Refraction Texture
  24542. newTexture.refractionPlane = this.refractionPlane.clone();
  24543. newTexture.renderList = this.renderList.slice(0);
  24544. newTexture.depth = this.depth;
  24545. return newTexture;
  24546. };
  24547. RefractionTexture.prototype.serialize = function () {
  24548. if (!this.name) {
  24549. return null;
  24550. }
  24551. var serializationObject = _super.prototype.serialize.call(this);
  24552. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24553. serializationObject.depth = this.depth;
  24554. return serializationObject;
  24555. };
  24556. return RefractionTexture;
  24557. }(BABYLON.RenderTargetTexture));
  24558. BABYLON.RefractionTexture = RefractionTexture;
  24559. })(BABYLON || (BABYLON = {}));
  24560. //# sourceMappingURL=babylon.refractionTexture.js.map
  24561. var BABYLON;
  24562. (function (BABYLON) {
  24563. var DynamicTexture = (function (_super) {
  24564. __extends(DynamicTexture, _super);
  24565. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24567. _super.call(this, null, scene, !generateMipMaps);
  24568. this.name = name;
  24569. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24570. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24571. this._generateMipMaps = generateMipMaps;
  24572. if (options.getContext) {
  24573. this._canvas = options;
  24574. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24575. }
  24576. else {
  24577. this._canvas = document.createElement("canvas");
  24578. if (options.width) {
  24579. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24580. }
  24581. else {
  24582. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24583. }
  24584. }
  24585. var textureSize = this.getSize();
  24586. this._canvas.width = textureSize.width;
  24587. this._canvas.height = textureSize.height;
  24588. this._context = this._canvas.getContext("2d");
  24589. }
  24590. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24591. get: function () {
  24592. return true;
  24593. },
  24594. enumerable: true,
  24595. configurable: true
  24596. });
  24597. DynamicTexture.prototype.scale = function (ratio) {
  24598. var textureSize = this.getSize();
  24599. textureSize.width *= ratio;
  24600. textureSize.height *= ratio;
  24601. this._canvas.width = textureSize.width;
  24602. this._canvas.height = textureSize.height;
  24603. this.releaseInternalTexture();
  24604. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24605. };
  24606. DynamicTexture.prototype.getContext = function () {
  24607. return this._context;
  24608. };
  24609. DynamicTexture.prototype.clear = function () {
  24610. var size = this.getSize();
  24611. this._context.fillRect(0, 0, size.width, size.height);
  24612. };
  24613. DynamicTexture.prototype.update = function (invertY) {
  24614. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24615. };
  24616. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24617. if (update === void 0) { update = true; }
  24618. var size = this.getSize();
  24619. if (clearColor) {
  24620. this._context.fillStyle = clearColor;
  24621. this._context.fillRect(0, 0, size.width, size.height);
  24622. }
  24623. this._context.font = font;
  24624. if (x === null) {
  24625. var textSize = this._context.measureText(text);
  24626. x = (size.width - textSize.width) / 2;
  24627. }
  24628. this._context.fillStyle = color;
  24629. this._context.fillText(text, x, y);
  24630. if (update) {
  24631. this.update(invertY);
  24632. }
  24633. };
  24634. DynamicTexture.prototype.clone = function () {
  24635. var textureSize = this.getSize();
  24636. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24637. // Base texture
  24638. newTexture.hasAlpha = this.hasAlpha;
  24639. newTexture.level = this.level;
  24640. // Dynamic Texture
  24641. newTexture.wrapU = this.wrapU;
  24642. newTexture.wrapV = this.wrapV;
  24643. return newTexture;
  24644. };
  24645. return DynamicTexture;
  24646. }(BABYLON.Texture));
  24647. BABYLON.DynamicTexture = DynamicTexture;
  24648. })(BABYLON || (BABYLON = {}));
  24649. //# sourceMappingURL=babylon.dynamicTexture.js.map
  24650. var BABYLON;
  24651. (function (BABYLON) {
  24652. var VideoTexture = (function (_super) {
  24653. __extends(VideoTexture, _super);
  24654. /**
  24655. * Creates a video texture.
  24656. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24657. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24658. * @param {BABYLON.Scene} scene is obviously the current scene.
  24659. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24660. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24661. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24662. */
  24663. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24664. var _this = this;
  24665. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24666. if (invertY === void 0) { invertY = false; }
  24667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24668. _super.call(this, null, scene, !generateMipMaps, invertY);
  24669. this._autoLaunch = true;
  24670. var urls;
  24671. this.name = name;
  24672. if (urlsOrVideo instanceof HTMLVideoElement) {
  24673. this.video = urlsOrVideo;
  24674. }
  24675. else {
  24676. urls = urlsOrVideo;
  24677. this.video = document.createElement("video");
  24678. this.video.autoplay = false;
  24679. this.video.loop = true;
  24680. }
  24681. this._generateMipMaps = generateMipMaps;
  24682. this._samplingMode = samplingMode;
  24683. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  24684. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24685. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24686. }
  24687. else {
  24688. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24689. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24690. this._generateMipMaps = false;
  24691. }
  24692. if (urls) {
  24693. this.video.addEventListener("canplaythrough", function () {
  24694. _this._createTexture();
  24695. });
  24696. urls.forEach(function (url) {
  24697. var source = document.createElement("source");
  24698. source.src = url;
  24699. _this.video.appendChild(source);
  24700. });
  24701. }
  24702. else {
  24703. this._createTexture();
  24704. }
  24705. this._lastUpdate = BABYLON.Tools.Now;
  24706. }
  24707. VideoTexture.prototype._createTexture = function () {
  24708. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24709. this._texture.isReady = true;
  24710. };
  24711. VideoTexture.prototype.update = function () {
  24712. if (this._autoLaunch) {
  24713. this._autoLaunch = false;
  24714. this.video.play();
  24715. }
  24716. var now = BABYLON.Tools.Now;
  24717. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24718. return false;
  24719. }
  24720. this._lastUpdate = now;
  24721. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24722. return true;
  24723. };
  24724. return VideoTexture;
  24725. }(BABYLON.Texture));
  24726. BABYLON.VideoTexture = VideoTexture;
  24727. })(BABYLON || (BABYLON = {}));
  24728. //# sourceMappingURL=babylon.videoTexture.js.map
  24729. var BABYLON;
  24730. (function (BABYLON) {
  24731. var CustomProceduralTexture = (function (_super) {
  24732. __extends(CustomProceduralTexture, _super);
  24733. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24734. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24735. this._animate = true;
  24736. this._time = 0;
  24737. this._texturePath = texturePath;
  24738. //Try to load json
  24739. this.loadJson(texturePath);
  24740. this.refreshRate = 1;
  24741. }
  24742. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24743. var _this = this;
  24744. var that = this;
  24745. function noConfigFile() {
  24746. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24747. try {
  24748. that.setFragment(that._texturePath);
  24749. }
  24750. catch (ex) {
  24751. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24752. }
  24753. }
  24754. var configFileUrl = jsonUrl + "/config.json";
  24755. var xhr = new XMLHttpRequest();
  24756. xhr.open("GET", configFileUrl, true);
  24757. xhr.addEventListener("load", function () {
  24758. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24759. try {
  24760. _this._config = JSON.parse(xhr.response);
  24761. _this.updateShaderUniforms();
  24762. _this.updateTextures();
  24763. _this.setFragment(_this._texturePath + "/custom");
  24764. _this._animate = _this._config.animate;
  24765. _this.refreshRate = _this._config.refreshrate;
  24766. }
  24767. catch (ex) {
  24768. noConfigFile();
  24769. }
  24770. }
  24771. else {
  24772. noConfigFile();
  24773. }
  24774. }, false);
  24775. xhr.addEventListener("error", function () {
  24776. noConfigFile();
  24777. }, false);
  24778. try {
  24779. xhr.send();
  24780. }
  24781. catch (ex) {
  24782. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24783. }
  24784. };
  24785. CustomProceduralTexture.prototype.isReady = function () {
  24786. if (!_super.prototype.isReady.call(this)) {
  24787. return false;
  24788. }
  24789. for (var name in this._textures) {
  24790. var texture = this._textures[name];
  24791. if (!texture.isReady()) {
  24792. return false;
  24793. }
  24794. }
  24795. return true;
  24796. };
  24797. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24798. if (this._animate) {
  24799. this._time += this.getScene().getAnimationRatio() * 0.03;
  24800. this.updateShaderUniforms();
  24801. }
  24802. _super.prototype.render.call(this, useCameraPostProcess);
  24803. };
  24804. CustomProceduralTexture.prototype.updateTextures = function () {
  24805. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24806. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24807. }
  24808. };
  24809. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24810. if (this._config) {
  24811. for (var j = 0; j < this._config.uniforms.length; j++) {
  24812. var uniform = this._config.uniforms[j];
  24813. switch (uniform.type) {
  24814. case "float":
  24815. this.setFloat(uniform.name, uniform.value);
  24816. break;
  24817. case "color3":
  24818. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24819. break;
  24820. case "color4":
  24821. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24822. break;
  24823. case "vector2":
  24824. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24825. break;
  24826. case "vector3":
  24827. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24828. break;
  24829. }
  24830. }
  24831. }
  24832. this.setFloat("time", this._time);
  24833. };
  24834. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24835. get: function () {
  24836. return this._animate;
  24837. },
  24838. set: function (value) {
  24839. this._animate = value;
  24840. },
  24841. enumerable: true,
  24842. configurable: true
  24843. });
  24844. return CustomProceduralTexture;
  24845. }(BABYLON.ProceduralTexture));
  24846. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24847. })(BABYLON || (BABYLON = {}));
  24848. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  24849. var BABYLON;
  24850. (function (BABYLON) {
  24851. var EffectFallbacks = (function () {
  24852. function EffectFallbacks() {
  24853. this._defines = {};
  24854. this._currentRank = 32;
  24855. this._maxRank = -1;
  24856. }
  24857. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24858. if (!this._defines[rank]) {
  24859. if (rank < this._currentRank) {
  24860. this._currentRank = rank;
  24861. }
  24862. if (rank > this._maxRank) {
  24863. this._maxRank = rank;
  24864. }
  24865. this._defines[rank] = new Array();
  24866. }
  24867. this._defines[rank].push(define);
  24868. };
  24869. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24870. this._meshRank = rank;
  24871. this._mesh = mesh;
  24872. if (rank > this._maxRank) {
  24873. this._maxRank = rank;
  24874. }
  24875. };
  24876. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24877. get: function () {
  24878. return this._currentRank <= this._maxRank;
  24879. },
  24880. enumerable: true,
  24881. configurable: true
  24882. });
  24883. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24884. var currentFallbacks = this._defines[this._currentRank];
  24885. for (var index = 0; index < currentFallbacks.length; index++) {
  24886. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24887. }
  24888. if (this._mesh && this._currentRank === this._meshRank) {
  24889. this._mesh.computeBonesUsingShaders = false;
  24890. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24891. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24892. }
  24893. this._currentRank++;
  24894. return currentDefines;
  24895. };
  24896. return EffectFallbacks;
  24897. }());
  24898. BABYLON.EffectFallbacks = EffectFallbacks;
  24899. var Effect = (function () {
  24900. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24901. var _this = this;
  24902. this._isReady = false;
  24903. this._compilationError = "";
  24904. this._valueCache = {};
  24905. this._engine = engine;
  24906. this.name = baseName;
  24907. this.defines = defines;
  24908. this._uniformsNames = uniformsNames.concat(samplers);
  24909. this._samplers = samplers;
  24910. this._attributesNames = attributesNames;
  24911. this.onError = onError;
  24912. this.onCompiled = onCompiled;
  24913. this._indexParameters = indexParameters;
  24914. var vertexSource;
  24915. var fragmentSource;
  24916. if (baseName.vertexElement) {
  24917. vertexSource = document.getElementById(baseName.vertexElement);
  24918. if (!vertexSource) {
  24919. vertexSource = baseName.vertexElement;
  24920. }
  24921. }
  24922. else {
  24923. vertexSource = baseName.vertex || baseName;
  24924. }
  24925. if (baseName.fragmentElement) {
  24926. fragmentSource = document.getElementById(baseName.fragmentElement);
  24927. if (!fragmentSource) {
  24928. fragmentSource = baseName.fragmentElement;
  24929. }
  24930. }
  24931. else {
  24932. fragmentSource = baseName.fragment || baseName;
  24933. }
  24934. this._loadVertexShader(vertexSource, function (vertexCode) {
  24935. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24936. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24937. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24938. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24939. });
  24940. });
  24941. });
  24942. });
  24943. }
  24944. // Properties
  24945. Effect.prototype.isReady = function () {
  24946. return this._isReady;
  24947. };
  24948. Effect.prototype.getProgram = function () {
  24949. return this._program;
  24950. };
  24951. Effect.prototype.getAttributesNames = function () {
  24952. return this._attributesNames;
  24953. };
  24954. Effect.prototype.getAttributeLocation = function (index) {
  24955. return this._attributes[index];
  24956. };
  24957. Effect.prototype.getAttributeLocationByName = function (name) {
  24958. var index = this._attributesNames.indexOf(name);
  24959. return this._attributes[index];
  24960. };
  24961. Effect.prototype.getAttributesCount = function () {
  24962. return this._attributes.length;
  24963. };
  24964. Effect.prototype.getUniformIndex = function (uniformName) {
  24965. return this._uniformsNames.indexOf(uniformName);
  24966. };
  24967. Effect.prototype.getUniform = function (uniformName) {
  24968. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24969. };
  24970. Effect.prototype.getSamplers = function () {
  24971. return this._samplers;
  24972. };
  24973. Effect.prototype.getCompilationError = function () {
  24974. return this._compilationError;
  24975. };
  24976. Effect.prototype.getVertexShaderSource = function () {
  24977. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  24978. };
  24979. Effect.prototype.getFragmentShaderSource = function () {
  24980. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  24981. };
  24982. // Methods
  24983. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24984. // DOM element ?
  24985. if (vertex instanceof HTMLElement) {
  24986. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24987. callback(vertexCode);
  24988. return;
  24989. }
  24990. // Base64 encoded ?
  24991. if (vertex.substr(0, 7) === "base64:") {
  24992. var vertexBinary = window.atob(vertex.substr(7));
  24993. callback(vertexBinary);
  24994. return;
  24995. }
  24996. // Is in local store ?
  24997. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24998. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24999. return;
  25000. }
  25001. var vertexShaderUrl;
  25002. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25003. vertexShaderUrl = vertex;
  25004. }
  25005. else {
  25006. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25007. }
  25008. // Vertex shader
  25009. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25010. };
  25011. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25012. // DOM element ?
  25013. if (fragment instanceof HTMLElement) {
  25014. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25015. callback(fragmentCode);
  25016. return;
  25017. }
  25018. // Base64 encoded ?
  25019. if (fragment.substr(0, 7) === "base64:") {
  25020. var fragmentBinary = window.atob(fragment.substr(7));
  25021. callback(fragmentBinary);
  25022. return;
  25023. }
  25024. // Is in local store ?
  25025. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25026. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25027. return;
  25028. }
  25029. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25030. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25031. return;
  25032. }
  25033. var fragmentShaderUrl;
  25034. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25035. fragmentShaderUrl = fragment;
  25036. }
  25037. else {
  25038. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25039. }
  25040. // Fragment shader
  25041. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25042. };
  25043. Effect.prototype._dumpShadersName = function () {
  25044. if (this.name.vertexElement) {
  25045. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25046. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25047. }
  25048. else if (this.name.vertex) {
  25049. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25050. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25051. }
  25052. else {
  25053. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25054. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25055. }
  25056. };
  25057. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25058. var _this = this;
  25059. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25060. var match = regex.exec(sourceCode);
  25061. var returnValue = new String(sourceCode);
  25062. while (match != null) {
  25063. var includeFile = match[1];
  25064. if (Effect.IncludesShadersStore[includeFile]) {
  25065. // Substitution
  25066. var includeContent = Effect.IncludesShadersStore[includeFile];
  25067. if (match[2]) {
  25068. var splits = match[3].split(",");
  25069. for (var index = 0; index < splits.length; index += 2) {
  25070. var source = new RegExp(splits[index], "g");
  25071. var dest = splits[index + 1];
  25072. includeContent = includeContent.replace(source, dest);
  25073. }
  25074. }
  25075. if (match[4]) {
  25076. var indexString = match[5];
  25077. if (indexString.indexOf("..") !== -1) {
  25078. var indexSplits = indexString.split("..");
  25079. var minIndex = parseInt(indexSplits[0]);
  25080. var maxIndex = parseInt(indexSplits[1]);
  25081. var sourceIncludeContent = includeContent.slice(0);
  25082. includeContent = "";
  25083. if (isNaN(maxIndex)) {
  25084. maxIndex = this._indexParameters[indexSplits[1]];
  25085. }
  25086. for (var i = minIndex; i <= maxIndex; i++) {
  25087. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  25088. }
  25089. }
  25090. else {
  25091. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25092. }
  25093. }
  25094. // Replace
  25095. returnValue = returnValue.replace(match[0], includeContent);
  25096. }
  25097. else {
  25098. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25099. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25100. Effect.IncludesShadersStore[includeFile] = fileContent;
  25101. _this._processIncludes(returnValue, callback);
  25102. });
  25103. return;
  25104. }
  25105. match = regex.exec(sourceCode);
  25106. }
  25107. callback(returnValue);
  25108. };
  25109. Effect.prototype._processPrecision = function (source) {
  25110. if (source.indexOf("precision highp float") === -1) {
  25111. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25112. source = "precision mediump float;\n" + source;
  25113. }
  25114. else {
  25115. source = "precision highp float;\n" + source;
  25116. }
  25117. }
  25118. else {
  25119. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25120. source = source.replace("precision highp float", "precision mediump float");
  25121. }
  25122. }
  25123. return source;
  25124. };
  25125. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  25126. try {
  25127. var engine = this._engine;
  25128. // Precision
  25129. vertexSourceCode = this._processPrecision(vertexSourceCode);
  25130. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  25131. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  25132. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25133. this._attributes = engine.getAttributes(this._program, attributesNames);
  25134. var index;
  25135. for (index = 0; index < this._samplers.length; index++) {
  25136. var sampler = this.getUniform(this._samplers[index]);
  25137. if (sampler == null) {
  25138. this._samplers.splice(index, 1);
  25139. index--;
  25140. }
  25141. }
  25142. engine.bindSamplers(this);
  25143. this._compilationError = "";
  25144. this._isReady = true;
  25145. if (this.onCompiled) {
  25146. this.onCompiled(this);
  25147. }
  25148. }
  25149. catch (e) {
  25150. this._compilationError = e.message;
  25151. // Let's go through fallbacks then
  25152. BABYLON.Tools.Error("Unable to compile effect: ");
  25153. BABYLON.Tools.Error("Defines: " + defines);
  25154. BABYLON.Tools.Error("Error: " + this._compilationError);
  25155. this._dumpShadersName();
  25156. if (fallbacks && fallbacks.isMoreFallbacks) {
  25157. BABYLON.Tools.Error("Trying next fallback.");
  25158. defines = fallbacks.reduce(defines);
  25159. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25160. }
  25161. else {
  25162. if (this.onError) {
  25163. this.onError(this, this._compilationError);
  25164. }
  25165. }
  25166. }
  25167. };
  25168. Object.defineProperty(Effect.prototype, "isSupported", {
  25169. get: function () {
  25170. return this._compilationError === "";
  25171. },
  25172. enumerable: true,
  25173. configurable: true
  25174. });
  25175. Effect.prototype._bindTexture = function (channel, texture) {
  25176. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25177. };
  25178. Effect.prototype.setTexture = function (channel, texture) {
  25179. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25180. };
  25181. Effect.prototype.setTextureArray = function (channel, textures) {
  25182. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25183. var initialPos = this._samplers.indexOf(channel);
  25184. for (var index = 1; index < textures.length; index++) {
  25185. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25186. }
  25187. }
  25188. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25189. };
  25190. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25191. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25192. };
  25193. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25194. var changed = false;
  25195. var cache = this._valueCache[uniformName];
  25196. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25197. changed = true;
  25198. cache = new BABYLON.Matrix();
  25199. }
  25200. var tm = cache.m;
  25201. var om = matrix.m;
  25202. for (var index = 0; index < 16; index++) {
  25203. if (tm[index] !== om[index]) {
  25204. tm[index] = om[index];
  25205. changed = true;
  25206. }
  25207. }
  25208. this._valueCache[uniformName] = cache;
  25209. return changed;
  25210. };
  25211. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25212. var cache = this._valueCache[uniformName];
  25213. if (!cache) {
  25214. cache = [x, y];
  25215. this._valueCache[uniformName] = cache;
  25216. return true;
  25217. }
  25218. var changed = false;
  25219. if (cache[0] !== x) {
  25220. cache[0] = x;
  25221. changed = true;
  25222. }
  25223. if (cache[1] !== y) {
  25224. cache[1] = y;
  25225. changed = true;
  25226. }
  25227. return changed;
  25228. };
  25229. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25230. var cache = this._valueCache[uniformName];
  25231. if (!cache) {
  25232. cache = [x, y, z];
  25233. this._valueCache[uniformName] = cache;
  25234. return true;
  25235. }
  25236. var changed = false;
  25237. if (cache[0] !== x) {
  25238. cache[0] = x;
  25239. changed = true;
  25240. }
  25241. if (cache[1] !== y) {
  25242. cache[1] = y;
  25243. changed = true;
  25244. }
  25245. if (cache[2] !== z) {
  25246. cache[2] = z;
  25247. changed = true;
  25248. }
  25249. return changed;
  25250. };
  25251. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25252. var cache = this._valueCache[uniformName];
  25253. if (!cache) {
  25254. cache = [x, y, z, w];
  25255. this._valueCache[uniformName] = cache;
  25256. return true;
  25257. }
  25258. var changed = false;
  25259. if (cache[0] !== x) {
  25260. cache[0] = x;
  25261. changed = true;
  25262. }
  25263. if (cache[1] !== y) {
  25264. cache[1] = y;
  25265. changed = true;
  25266. }
  25267. if (cache[2] !== z) {
  25268. cache[2] = z;
  25269. changed = true;
  25270. }
  25271. if (cache[3] !== w) {
  25272. cache[3] = w;
  25273. changed = true;
  25274. }
  25275. return changed;
  25276. };
  25277. Effect.prototype.setIntArray = function (uniformName, array) {
  25278. this._valueCache[uniformName] = null;
  25279. this._engine.setIntArray(this.getUniform(uniformName), array);
  25280. return this;
  25281. };
  25282. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25283. this._valueCache[uniformName] = null;
  25284. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25285. return this;
  25286. };
  25287. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25288. this._valueCache[uniformName] = null;
  25289. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25290. return this;
  25291. };
  25292. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25293. this._valueCache[uniformName] = null;
  25294. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25295. return this;
  25296. };
  25297. Effect.prototype.setFloatArray = function (uniformName, array) {
  25298. this._valueCache[uniformName] = null;
  25299. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25300. return this;
  25301. };
  25302. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25303. this._valueCache[uniformName] = null;
  25304. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25305. return this;
  25306. };
  25307. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25308. this._valueCache[uniformName] = null;
  25309. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25310. return this;
  25311. };
  25312. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25313. this._valueCache[uniformName] = null;
  25314. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25315. return this;
  25316. };
  25317. Effect.prototype.setArray = function (uniformName, array) {
  25318. this._valueCache[uniformName] = null;
  25319. this._engine.setArray(this.getUniform(uniformName), array);
  25320. return this;
  25321. };
  25322. Effect.prototype.setArray2 = function (uniformName, array) {
  25323. this._valueCache[uniformName] = null;
  25324. this._engine.setArray2(this.getUniform(uniformName), array);
  25325. return this;
  25326. };
  25327. Effect.prototype.setArray3 = function (uniformName, array) {
  25328. this._valueCache[uniformName] = null;
  25329. this._engine.setArray3(this.getUniform(uniformName), array);
  25330. return this;
  25331. };
  25332. Effect.prototype.setArray4 = function (uniformName, array) {
  25333. this._valueCache[uniformName] = null;
  25334. this._engine.setArray4(this.getUniform(uniformName), array);
  25335. return this;
  25336. };
  25337. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25338. this._valueCache[uniformName] = null;
  25339. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25340. return this;
  25341. };
  25342. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25343. if (this._cacheMatrix(uniformName, matrix)) {
  25344. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25345. }
  25346. return this;
  25347. };
  25348. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25349. this._valueCache[uniformName] = null;
  25350. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25351. return this;
  25352. };
  25353. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25354. this._valueCache[uniformName] = null;
  25355. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25356. return this;
  25357. };
  25358. Effect.prototype.setFloat = function (uniformName, value) {
  25359. var cache = this._valueCache[uniformName];
  25360. if (cache !== undefined && cache === value)
  25361. return this;
  25362. this._valueCache[uniformName] = value;
  25363. this._engine.setFloat(this.getUniform(uniformName), value);
  25364. return this;
  25365. };
  25366. Effect.prototype.setBool = function (uniformName, bool) {
  25367. var cache = this._valueCache[uniformName];
  25368. if (cache !== undefined && cache === bool)
  25369. return this;
  25370. this._valueCache[uniformName] = bool;
  25371. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25372. return this;
  25373. };
  25374. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25375. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25376. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25377. }
  25378. return this;
  25379. };
  25380. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25381. if (this._cacheFloat2(uniformName, x, y)) {
  25382. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25383. }
  25384. return this;
  25385. };
  25386. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25387. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25388. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25389. }
  25390. return this;
  25391. };
  25392. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25393. if (this._cacheFloat3(uniformName, x, y, z)) {
  25394. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25395. }
  25396. return this;
  25397. };
  25398. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25399. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25400. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25401. }
  25402. return this;
  25403. };
  25404. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25405. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25406. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25407. }
  25408. return this;
  25409. };
  25410. Effect.prototype.setColor3 = function (uniformName, color3) {
  25411. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25412. this._engine.setColor3(this.getUniform(uniformName), color3);
  25413. }
  25414. return this;
  25415. };
  25416. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25417. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25418. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25419. }
  25420. return this;
  25421. };
  25422. Effect.prototype._recombineShader = function (node) {
  25423. if (node.define) {
  25424. if (node.condition) {
  25425. }
  25426. else if (node.ndef) {
  25427. if (this.defines.indexOf("#define " + node.define) !== -1) {
  25428. return null;
  25429. }
  25430. }
  25431. else if (this.defines.indexOf("#define " + node.define) === -1) {
  25432. return null;
  25433. }
  25434. }
  25435. var result = "";
  25436. for (var index = 0; index < node.children.length; index++) {
  25437. var line = node.children[index];
  25438. if (line.children) {
  25439. var combined = this._recombineShader(line) + "\r\n";
  25440. if (combined !== null) {
  25441. result += combined + "\r\n";
  25442. }
  25443. continue;
  25444. }
  25445. result += line + "\r\n";
  25446. }
  25447. return result;
  25448. };
  25449. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  25450. var root = {
  25451. children: []
  25452. };
  25453. var currentNode = root;
  25454. var lines = shaderString.split("\n");
  25455. for (var index = 0; index < lines.length; index++) {
  25456. var line = lines[index].trim();
  25457. // #ifdef
  25458. var pos = line.indexOf("#ifdef ");
  25459. if (pos !== -1) {
  25460. var define = line.substr(pos + 7);
  25461. var newNode = {
  25462. condition: null,
  25463. ndef: false,
  25464. define: define,
  25465. children: [],
  25466. parent: currentNode
  25467. };
  25468. currentNode.children.push(newNode);
  25469. currentNode = newNode;
  25470. continue;
  25471. }
  25472. // #ifndef
  25473. var pos = line.indexOf("#ifndef ");
  25474. if (pos !== -1) {
  25475. var define = line.substr(pos + 8);
  25476. newNode = {
  25477. condition: null,
  25478. define: define,
  25479. ndef: true,
  25480. children: [],
  25481. parent: currentNode
  25482. };
  25483. currentNode.children.push(newNode);
  25484. currentNode = newNode;
  25485. continue;
  25486. }
  25487. // #if
  25488. var pos = line.indexOf("#if ");
  25489. if (pos !== -1) {
  25490. var define = line.substr(pos + 4).trim();
  25491. var conditionPos = define.indexOf(" ");
  25492. newNode = {
  25493. condition: define.substr(conditionPos + 1),
  25494. define: define.substr(0, conditionPos),
  25495. ndef: false,
  25496. children: [],
  25497. parent: currentNode
  25498. };
  25499. currentNode.children.push(newNode);
  25500. currentNode = newNode;
  25501. continue;
  25502. }
  25503. // #endif
  25504. pos = line.indexOf("#endif");
  25505. if (pos !== -1) {
  25506. currentNode = currentNode.parent;
  25507. continue;
  25508. }
  25509. currentNode.children.push(line);
  25510. }
  25511. // Recombine
  25512. return this._recombineShader(root);
  25513. };
  25514. // Statics
  25515. Effect.ShadersStore = {};
  25516. Effect.IncludesShadersStore = {};
  25517. return Effect;
  25518. }());
  25519. BABYLON.Effect = Effect;
  25520. })(BABYLON || (BABYLON = {}));
  25521. //# sourceMappingURL=babylon.effect.js.map
  25522. var BABYLON;
  25523. (function (BABYLON) {
  25524. var MaterialHelper = (function () {
  25525. function MaterialHelper() {
  25526. }
  25527. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25528. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25529. var lightIndex = 0;
  25530. var needNormals = false;
  25531. var needRebuild = false;
  25532. var needShadows = false;
  25533. var lightmapMode = false;
  25534. for (var index = 0; index < scene.lights.length; index++) {
  25535. var light = scene.lights[index];
  25536. if (!light.isEnabled()) {
  25537. continue;
  25538. }
  25539. // Excluded check
  25540. if (light._excludedMeshesIds.length > 0) {
  25541. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25542. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25543. if (excludedMesh) {
  25544. light.excludedMeshes.push(excludedMesh);
  25545. }
  25546. }
  25547. light._excludedMeshesIds = [];
  25548. }
  25549. // Included check
  25550. if (light._includedOnlyMeshesIds.length > 0) {
  25551. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25552. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25553. if (includedOnlyMesh) {
  25554. light.includedOnlyMeshes.push(includedOnlyMesh);
  25555. }
  25556. }
  25557. light._includedOnlyMeshesIds = [];
  25558. }
  25559. if (!light.canAffectMesh(mesh)) {
  25560. continue;
  25561. }
  25562. needNormals = true;
  25563. if (defines["LIGHT" + lightIndex] === undefined) {
  25564. needRebuild = true;
  25565. }
  25566. defines["LIGHT" + lightIndex] = true;
  25567. var type;
  25568. if (light instanceof BABYLON.SpotLight) {
  25569. type = "SPOTLIGHT" + lightIndex;
  25570. }
  25571. else if (light instanceof BABYLON.HemisphericLight) {
  25572. type = "HEMILIGHT" + lightIndex;
  25573. }
  25574. else if (light instanceof BABYLON.PointLight) {
  25575. type = "POINTLIGHT" + lightIndex;
  25576. }
  25577. else {
  25578. type = "DIRLIGHT" + lightIndex;
  25579. }
  25580. if (defines[type] === undefined) {
  25581. needRebuild = true;
  25582. }
  25583. defines[type] = true;
  25584. // Specular
  25585. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25586. defines["SPECULARTERM"] = true;
  25587. }
  25588. // Shadows
  25589. if (scene.shadowsEnabled) {
  25590. var shadowGenerator = light.getShadowGenerator();
  25591. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25592. if (defines["SHADOW" + lightIndex] === undefined) {
  25593. needRebuild = true;
  25594. }
  25595. defines["SHADOW" + lightIndex] = true;
  25596. defines["SHADOWS"] = true;
  25597. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25598. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25599. needRebuild = true;
  25600. }
  25601. defines["SHADOWVSM" + lightIndex] = true;
  25602. }
  25603. if (shadowGenerator.usePoissonSampling) {
  25604. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25605. needRebuild = true;
  25606. }
  25607. defines["SHADOWPCF" + lightIndex] = true;
  25608. }
  25609. needShadows = true;
  25610. }
  25611. }
  25612. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25613. lightmapMode = true;
  25614. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25615. needRebuild = true;
  25616. }
  25617. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25618. needRebuild = true;
  25619. }
  25620. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25621. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25622. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25623. }
  25624. }
  25625. lightIndex++;
  25626. if (lightIndex === maxSimultaneousLights)
  25627. break;
  25628. }
  25629. var caps = scene.getEngine().getCaps();
  25630. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25631. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25632. needRebuild = true;
  25633. }
  25634. defines["SHADOWFULLFLOAT"] = true;
  25635. }
  25636. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25637. needRebuild = true;
  25638. }
  25639. if (lightmapMode) {
  25640. defines["LIGHTMAPEXCLUDED"] = true;
  25641. }
  25642. if (needRebuild) {
  25643. defines.rebuild();
  25644. }
  25645. return needNormals;
  25646. };
  25647. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25648. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25649. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25650. if (!defines["LIGHT" + lightIndex]) {
  25651. break;
  25652. }
  25653. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25654. samplersList.push("shadowSampler" + lightIndex);
  25655. }
  25656. };
  25657. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25658. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25659. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25660. if (!defines["LIGHT" + lightIndex]) {
  25661. break;
  25662. }
  25663. if (lightIndex > 0) {
  25664. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25665. }
  25666. if (defines["SHADOW" + lightIndex]) {
  25667. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25668. }
  25669. if (defines["SHADOWPCF" + lightIndex]) {
  25670. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25671. }
  25672. if (defines["SHADOWVSM" + lightIndex]) {
  25673. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25674. }
  25675. }
  25676. };
  25677. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25678. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25679. fallbacks.addCPUSkinningFallback(0, mesh);
  25680. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25681. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25682. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25683. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25684. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25685. }
  25686. }
  25687. };
  25688. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25689. if (defines["INSTANCES"]) {
  25690. attribs.push("world0");
  25691. attribs.push("world1");
  25692. attribs.push("world2");
  25693. attribs.push("world3");
  25694. }
  25695. };
  25696. // Bindings
  25697. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25698. var shadowGenerator = light.getShadowGenerator();
  25699. if (mesh.receiveShadows && shadowGenerator) {
  25700. if (!light.needCube()) {
  25701. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25702. }
  25703. else {
  25704. if (!depthValuesAlreadySet) {
  25705. depthValuesAlreadySet = true;
  25706. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25707. }
  25708. }
  25709. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25710. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25711. }
  25712. return depthValuesAlreadySet;
  25713. };
  25714. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25715. if (light instanceof BABYLON.PointLight) {
  25716. // Point Light
  25717. light.transferToEffect(effect, "vLightData" + lightIndex);
  25718. }
  25719. else if (light instanceof BABYLON.DirectionalLight) {
  25720. // Directional Light
  25721. light.transferToEffect(effect, "vLightData" + lightIndex);
  25722. }
  25723. else if (light instanceof BABYLON.SpotLight) {
  25724. // Spot Light
  25725. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25726. }
  25727. else if (light instanceof BABYLON.HemisphericLight) {
  25728. // Hemispheric Light
  25729. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25730. }
  25731. };
  25732. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25733. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25734. var lightIndex = 0;
  25735. var depthValuesAlreadySet = false;
  25736. for (var index = 0; index < scene.lights.length; index++) {
  25737. var light = scene.lights[index];
  25738. if (!light.isEnabled()) {
  25739. continue;
  25740. }
  25741. if (!light.canAffectMesh(mesh)) {
  25742. continue;
  25743. }
  25744. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25745. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25746. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25747. if (defines["SPECULARTERM"]) {
  25748. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25749. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25750. }
  25751. // Shadows
  25752. if (scene.shadowsEnabled) {
  25753. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25754. }
  25755. lightIndex++;
  25756. if (lightIndex === maxSimultaneousLights)
  25757. break;
  25758. }
  25759. };
  25760. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25761. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25762. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25763. effect.setColor3("vFogColor", scene.fogColor);
  25764. }
  25765. };
  25766. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25767. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25768. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25769. if (matrices) {
  25770. effect.setMatrices("mBones", matrices);
  25771. }
  25772. }
  25773. };
  25774. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25775. if (defines["LOGARITHMICDEPTH"]) {
  25776. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25777. }
  25778. };
  25779. MaterialHelper.BindClipPlane = function (effect, scene) {
  25780. if (scene.clipPlane) {
  25781. var clipPlane = scene.clipPlane;
  25782. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25783. }
  25784. };
  25785. return MaterialHelper;
  25786. }());
  25787. BABYLON.MaterialHelper = MaterialHelper;
  25788. })(BABYLON || (BABYLON = {}));
  25789. //# sourceMappingURL=babylon.materialHelper.js.map
  25790. var BABYLON;
  25791. (function (BABYLON) {
  25792. var FresnelParameters = (function () {
  25793. function FresnelParameters() {
  25794. this.isEnabled = true;
  25795. this.leftColor = BABYLON.Color3.White();
  25796. this.rightColor = BABYLON.Color3.Black();
  25797. this.bias = 0;
  25798. this.power = 1;
  25799. }
  25800. FresnelParameters.prototype.clone = function () {
  25801. var newFresnelParameters = new FresnelParameters();
  25802. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25803. return newFresnelParameters;
  25804. };
  25805. FresnelParameters.prototype.serialize = function () {
  25806. var serializationObject = {};
  25807. serializationObject.isEnabled = this.isEnabled;
  25808. serializationObject.leftColor = this.leftColor;
  25809. serializationObject.rightColor = this.rightColor;
  25810. serializationObject.bias = this.bias;
  25811. serializationObject.power = this.power;
  25812. return serializationObject;
  25813. };
  25814. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25815. var fresnelParameters = new FresnelParameters();
  25816. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25817. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25818. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25819. fresnelParameters.bias = parsedFresnelParameters.bias;
  25820. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25821. return fresnelParameters;
  25822. };
  25823. return FresnelParameters;
  25824. }());
  25825. BABYLON.FresnelParameters = FresnelParameters;
  25826. })(BABYLON || (BABYLON = {}));
  25827. //# sourceMappingURL=babylon.fresnelParameters.js.map
  25828. var BABYLON;
  25829. (function (BABYLON) {
  25830. var MaterialDefines = (function () {
  25831. function MaterialDefines() {
  25832. }
  25833. MaterialDefines.prototype.rebuild = function () {
  25834. if (this._keys) {
  25835. delete this._keys;
  25836. }
  25837. this._keys = Object.keys(this);
  25838. };
  25839. MaterialDefines.prototype.isEqual = function (other) {
  25840. if (this._keys.length !== other._keys.length) {
  25841. return false;
  25842. }
  25843. for (var index = 0; index < this._keys.length; index++) {
  25844. var prop = this._keys[index];
  25845. if (this[prop] !== other[prop]) {
  25846. return false;
  25847. }
  25848. }
  25849. return true;
  25850. };
  25851. MaterialDefines.prototype.cloneTo = function (other) {
  25852. if (this._keys.length !== other._keys.length) {
  25853. other._keys = this._keys.slice(0);
  25854. }
  25855. for (var index = 0; index < this._keys.length; index++) {
  25856. var prop = this._keys[index];
  25857. other[prop] = this[prop];
  25858. }
  25859. };
  25860. MaterialDefines.prototype.reset = function () {
  25861. for (var index = 0; index < this._keys.length; index++) {
  25862. var prop = this._keys[index];
  25863. if (typeof (this[prop]) === "number") {
  25864. this[prop] = 0;
  25865. }
  25866. else {
  25867. this[prop] = false;
  25868. }
  25869. }
  25870. };
  25871. MaterialDefines.prototype.toString = function () {
  25872. var result = "";
  25873. for (var index = 0; index < this._keys.length; index++) {
  25874. var prop = this._keys[index];
  25875. if (typeof (this[prop]) === "number") {
  25876. result += "#define " + prop + " " + this[prop] + "\n";
  25877. }
  25878. else if (this[prop]) {
  25879. result += "#define " + prop + "\n";
  25880. }
  25881. }
  25882. return result;
  25883. };
  25884. return MaterialDefines;
  25885. }());
  25886. BABYLON.MaterialDefines = MaterialDefines;
  25887. var Material = (function () {
  25888. function Material(name, scene, doNotAdd) {
  25889. this.checkReadyOnEveryCall = false;
  25890. this.checkReadyOnlyOnce = false;
  25891. this.state = "";
  25892. this.alpha = 1.0;
  25893. this.backFaceCulling = true;
  25894. this.doNotSerialize = false;
  25895. /**
  25896. * An event triggered when the material is disposed.
  25897. * @type {BABYLON.Observable}
  25898. */
  25899. this.onDisposeObservable = new BABYLON.Observable();
  25900. /**
  25901. * An event triggered when the material is bound.
  25902. * @type {BABYLON.Observable}
  25903. */
  25904. this.onBindObservable = new BABYLON.Observable();
  25905. /**
  25906. * An event triggered when the material is unbound.
  25907. * @type {BABYLON.Observable}
  25908. */
  25909. this.onUnBindObservable = new BABYLON.Observable();
  25910. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25911. this.disableDepthWrite = false;
  25912. this.fogEnabled = true;
  25913. this.pointSize = 1.0;
  25914. this.zOffset = 0;
  25915. this._wasPreviouslyReady = false;
  25916. this._fillMode = Material.TriangleFillMode;
  25917. this.name = name;
  25918. this.id = name;
  25919. this._scene = scene;
  25920. if (scene.useRightHandedSystem) {
  25921. this.sideOrientation = Material.ClockWiseSideOrientation;
  25922. }
  25923. else {
  25924. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25925. }
  25926. if (!doNotAdd) {
  25927. scene.materials.push(this);
  25928. }
  25929. }
  25930. Object.defineProperty(Material, "TriangleFillMode", {
  25931. get: function () {
  25932. return Material._TriangleFillMode;
  25933. },
  25934. enumerable: true,
  25935. configurable: true
  25936. });
  25937. Object.defineProperty(Material, "WireFrameFillMode", {
  25938. get: function () {
  25939. return Material._WireFrameFillMode;
  25940. },
  25941. enumerable: true,
  25942. configurable: true
  25943. });
  25944. Object.defineProperty(Material, "PointFillMode", {
  25945. get: function () {
  25946. return Material._PointFillMode;
  25947. },
  25948. enumerable: true,
  25949. configurable: true
  25950. });
  25951. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25952. get: function () {
  25953. return Material._ClockWiseSideOrientation;
  25954. },
  25955. enumerable: true,
  25956. configurable: true
  25957. });
  25958. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25959. get: function () {
  25960. return Material._CounterClockWiseSideOrientation;
  25961. },
  25962. enumerable: true,
  25963. configurable: true
  25964. });
  25965. Object.defineProperty(Material.prototype, "onDispose", {
  25966. set: function (callback) {
  25967. if (this._onDisposeObserver) {
  25968. this.onDisposeObservable.remove(this._onDisposeObserver);
  25969. }
  25970. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25971. },
  25972. enumerable: true,
  25973. configurable: true
  25974. });
  25975. Object.defineProperty(Material.prototype, "onBind", {
  25976. set: function (callback) {
  25977. if (this._onBindObserver) {
  25978. this.onBindObservable.remove(this._onBindObserver);
  25979. }
  25980. this._onBindObserver = this.onBindObservable.add(callback);
  25981. },
  25982. enumerable: true,
  25983. configurable: true
  25984. });
  25985. Object.defineProperty(Material.prototype, "wireframe", {
  25986. get: function () {
  25987. return this._fillMode === Material.WireFrameFillMode;
  25988. },
  25989. set: function (value) {
  25990. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25991. },
  25992. enumerable: true,
  25993. configurable: true
  25994. });
  25995. Object.defineProperty(Material.prototype, "pointsCloud", {
  25996. get: function () {
  25997. return this._fillMode === Material.PointFillMode;
  25998. },
  25999. set: function (value) {
  26000. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26001. },
  26002. enumerable: true,
  26003. configurable: true
  26004. });
  26005. Object.defineProperty(Material.prototype, "fillMode", {
  26006. get: function () {
  26007. return this._fillMode;
  26008. },
  26009. set: function (value) {
  26010. this._fillMode = value;
  26011. },
  26012. enumerable: true,
  26013. configurable: true
  26014. });
  26015. /**
  26016. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26017. * subclasses should override adding information pertainent to themselves
  26018. */
  26019. Material.prototype.toString = function (fullDetails) {
  26020. var ret = "Name: " + this.name;
  26021. if (fullDetails) {
  26022. }
  26023. return ret;
  26024. };
  26025. Object.defineProperty(Material.prototype, "isFrozen", {
  26026. get: function () {
  26027. return this.checkReadyOnlyOnce;
  26028. },
  26029. enumerable: true,
  26030. configurable: true
  26031. });
  26032. Material.prototype.freeze = function () {
  26033. this.checkReadyOnlyOnce = true;
  26034. };
  26035. Material.prototype.unfreeze = function () {
  26036. this.checkReadyOnlyOnce = false;
  26037. };
  26038. Material.prototype.isReady = function (mesh, useInstances) {
  26039. return true;
  26040. };
  26041. Material.prototype.getEffect = function () {
  26042. return this._effect;
  26043. };
  26044. Material.prototype.getScene = function () {
  26045. return this._scene;
  26046. };
  26047. Material.prototype.needAlphaBlending = function () {
  26048. return (this.alpha < 1.0);
  26049. };
  26050. Material.prototype.needAlphaTesting = function () {
  26051. return false;
  26052. };
  26053. Material.prototype.getAlphaTestTexture = function () {
  26054. return null;
  26055. };
  26056. Material.prototype.markDirty = function () {
  26057. this._wasPreviouslyReady = false;
  26058. };
  26059. Material.prototype._preBind = function () {
  26060. var engine = this._scene.getEngine();
  26061. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26062. engine.enableEffect(this._effect);
  26063. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26064. };
  26065. Material.prototype.bind = function (world, mesh) {
  26066. this._scene._cachedMaterial = this;
  26067. this.onBindObservable.notifyObservers(mesh);
  26068. if (this.disableDepthWrite) {
  26069. var engine = this._scene.getEngine();
  26070. this._cachedDepthWriteState = engine.getDepthWrite();
  26071. engine.setDepthWrite(false);
  26072. }
  26073. };
  26074. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26075. };
  26076. Material.prototype.unbind = function () {
  26077. this.onUnBindObservable.notifyObservers(this);
  26078. if (this.disableDepthWrite) {
  26079. var engine = this._scene.getEngine();
  26080. engine.setDepthWrite(this._cachedDepthWriteState);
  26081. }
  26082. };
  26083. Material.prototype.clone = function (name) {
  26084. return null;
  26085. };
  26086. Material.prototype.getBindedMeshes = function () {
  26087. var result = new Array();
  26088. for (var index = 0; index < this._scene.meshes.length; index++) {
  26089. var mesh = this._scene.meshes[index];
  26090. if (mesh.material === this) {
  26091. result.push(mesh);
  26092. }
  26093. }
  26094. return result;
  26095. };
  26096. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26097. // Animations
  26098. this.getScene().stopAnimation(this);
  26099. // Remove from scene
  26100. var index = this._scene.materials.indexOf(this);
  26101. if (index >= 0) {
  26102. this._scene.materials.splice(index, 1);
  26103. }
  26104. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26105. if (forceDisposeEffect && this._effect) {
  26106. this._scene.getEngine()._releaseEffect(this._effect);
  26107. this._effect = null;
  26108. }
  26109. // Remove from meshes
  26110. for (index = 0; index < this._scene.meshes.length; index++) {
  26111. var mesh = this._scene.meshes[index];
  26112. if (mesh.material === this) {
  26113. mesh.material = null;
  26114. }
  26115. }
  26116. // Callback
  26117. this.onDisposeObservable.notifyObservers(this);
  26118. this.onDisposeObservable.clear();
  26119. this.onBindObservable.clear();
  26120. this.onUnBindObservable.clear();
  26121. };
  26122. Material.prototype.serialize = function () {
  26123. return BABYLON.SerializationHelper.Serialize(this);
  26124. };
  26125. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26126. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26127. multiMaterial.id = parsedMultiMaterial.id;
  26128. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26129. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26130. var subMatId = parsedMultiMaterial.materials[matIndex];
  26131. if (subMatId) {
  26132. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26133. }
  26134. else {
  26135. multiMaterial.subMaterials.push(null);
  26136. }
  26137. }
  26138. return multiMaterial;
  26139. };
  26140. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26141. if (!parsedMaterial.customType) {
  26142. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26143. }
  26144. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26145. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26146. ;
  26147. };
  26148. Material._TriangleFillMode = 0;
  26149. Material._WireFrameFillMode = 1;
  26150. Material._PointFillMode = 2;
  26151. Material._ClockWiseSideOrientation = 0;
  26152. Material._CounterClockWiseSideOrientation = 1;
  26153. __decorate([
  26154. BABYLON.serialize()
  26155. ], Material.prototype, "id", void 0);
  26156. __decorate([
  26157. BABYLON.serialize()
  26158. ], Material.prototype, "name", void 0);
  26159. __decorate([
  26160. BABYLON.serialize()
  26161. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26162. __decorate([
  26163. BABYLON.serialize()
  26164. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26165. __decorate([
  26166. BABYLON.serialize()
  26167. ], Material.prototype, "state", void 0);
  26168. __decorate([
  26169. BABYLON.serialize()
  26170. ], Material.prototype, "alpha", void 0);
  26171. __decorate([
  26172. BABYLON.serialize()
  26173. ], Material.prototype, "backFaceCulling", void 0);
  26174. __decorate([
  26175. BABYLON.serialize()
  26176. ], Material.prototype, "sideOrientation", void 0);
  26177. __decorate([
  26178. BABYLON.serialize()
  26179. ], Material.prototype, "alphaMode", void 0);
  26180. __decorate([
  26181. BABYLON.serialize()
  26182. ], Material.prototype, "disableDepthWrite", void 0);
  26183. __decorate([
  26184. BABYLON.serialize()
  26185. ], Material.prototype, "fogEnabled", void 0);
  26186. __decorate([
  26187. BABYLON.serialize()
  26188. ], Material.prototype, "pointSize", void 0);
  26189. __decorate([
  26190. BABYLON.serialize()
  26191. ], Material.prototype, "zOffset", void 0);
  26192. __decorate([
  26193. BABYLON.serialize()
  26194. ], Material.prototype, "wireframe", null);
  26195. __decorate([
  26196. BABYLON.serialize()
  26197. ], Material.prototype, "pointsCloud", null);
  26198. __decorate([
  26199. BABYLON.serialize()
  26200. ], Material.prototype, "fillMode", null);
  26201. return Material;
  26202. }());
  26203. BABYLON.Material = Material;
  26204. })(BABYLON || (BABYLON = {}));
  26205. //# sourceMappingURL=babylon.material.js.map
  26206. var BABYLON;
  26207. (function (BABYLON) {
  26208. var StandardMaterialDefines = (function (_super) {
  26209. __extends(StandardMaterialDefines, _super);
  26210. function StandardMaterialDefines() {
  26211. _super.call(this);
  26212. this.DIFFUSE = false;
  26213. this.AMBIENT = false;
  26214. this.OPACITY = false;
  26215. this.OPACITYRGB = false;
  26216. this.REFLECTION = false;
  26217. this.EMISSIVE = false;
  26218. this.SPECULAR = false;
  26219. this.BUMP = false;
  26220. this.PARALLAX = false;
  26221. this.PARALLAXOCCLUSION = false;
  26222. this.SPECULAROVERALPHA = false;
  26223. this.CLIPPLANE = false;
  26224. this.ALPHATEST = false;
  26225. this.ALPHAFROMDIFFUSE = false;
  26226. this.POINTSIZE = false;
  26227. this.FOG = false;
  26228. this.SPECULARTERM = false;
  26229. this.DIFFUSEFRESNEL = false;
  26230. this.OPACITYFRESNEL = false;
  26231. this.REFLECTIONFRESNEL = false;
  26232. this.REFRACTIONFRESNEL = false;
  26233. this.EMISSIVEFRESNEL = false;
  26234. this.FRESNEL = false;
  26235. this.NORMAL = false;
  26236. this.UV1 = false;
  26237. this.UV2 = false;
  26238. this.VERTEXCOLOR = false;
  26239. this.VERTEXALPHA = false;
  26240. this.NUM_BONE_INFLUENCERS = 0;
  26241. this.BonesPerMesh = 0;
  26242. this.INSTANCES = false;
  26243. this.GLOSSINESS = false;
  26244. this.ROUGHNESS = false;
  26245. this.EMISSIVEASILLUMINATION = false;
  26246. this.LINKEMISSIVEWITHDIFFUSE = false;
  26247. this.REFLECTIONFRESNELFROMSPECULAR = false;
  26248. this.LIGHTMAP = false;
  26249. this.USELIGHTMAPASSHADOWMAP = false;
  26250. this.REFLECTIONMAP_3D = false;
  26251. this.REFLECTIONMAP_SPHERICAL = false;
  26252. this.REFLECTIONMAP_PLANAR = false;
  26253. this.REFLECTIONMAP_CUBIC = false;
  26254. this.REFLECTIONMAP_PROJECTION = false;
  26255. this.REFLECTIONMAP_SKYBOX = false;
  26256. this.REFLECTIONMAP_EXPLICIT = false;
  26257. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26258. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26259. this.INVERTCUBICMAP = false;
  26260. this.LOGARITHMICDEPTH = false;
  26261. this.REFRACTION = false;
  26262. this.REFRACTIONMAP_3D = false;
  26263. this.REFLECTIONOVERALPHA = false;
  26264. this.INVERTNORMALMAPX = false;
  26265. this.INVERTNORMALMAPY = false;
  26266. this.SHADOWFULLFLOAT = false;
  26267. this.CAMERACOLORGRADING = false;
  26268. this.CAMERACOLORCURVES = false;
  26269. this.rebuild();
  26270. }
  26271. return StandardMaterialDefines;
  26272. }(BABYLON.MaterialDefines));
  26273. var StandardMaterial = (function (_super) {
  26274. __extends(StandardMaterial, _super);
  26275. function StandardMaterial(name, scene) {
  26276. var _this = this;
  26277. _super.call(this, name, scene);
  26278. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26279. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26280. this.specularColor = new BABYLON.Color3(1, 1, 1);
  26281. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26282. this.specularPower = 64;
  26283. this.useAlphaFromDiffuseTexture = false;
  26284. this.useEmissiveAsIllumination = false;
  26285. this.linkEmissiveWithDiffuse = false;
  26286. this.useReflectionFresnelFromSpecular = false;
  26287. this.useSpecularOverAlpha = false;
  26288. this.useReflectionOverAlpha = false;
  26289. this.disableLighting = false;
  26290. this.useParallax = false;
  26291. this.useParallaxOcclusion = false;
  26292. this.parallaxScaleBias = 0.05;
  26293. this.roughness = 0;
  26294. this.indexOfRefraction = 0.98;
  26295. this.invertRefractionY = true;
  26296. this.useLightmapAsShadowmap = false;
  26297. this.useGlossinessFromSpecularMapAlpha = false;
  26298. this.maxSimultaneousLights = 4;
  26299. /**
  26300. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26301. */
  26302. this.invertNormalMapX = false;
  26303. /**
  26304. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26305. */
  26306. this.invertNormalMapY = false;
  26307. /**
  26308. * Color Grading 2D Lookup Texture.
  26309. * This allows special effects like sepia, black and white to sixties rendering style.
  26310. */
  26311. this.cameraColorGradingTexture = null;
  26312. /**
  26313. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26314. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26315. * 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;
  26316. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26317. */
  26318. this.cameraColorCurves = null;
  26319. this._renderTargets = new BABYLON.SmartArray(16);
  26320. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26321. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26322. this._defines = new StandardMaterialDefines();
  26323. this._cachedDefines = new StandardMaterialDefines();
  26324. this._cachedDefines.BonesPerMesh = -1;
  26325. this.getRenderTargetTextures = function () {
  26326. _this._renderTargets.reset();
  26327. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  26328. _this._renderTargets.push(_this.reflectionTexture);
  26329. }
  26330. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  26331. _this._renderTargets.push(_this.refractionTexture);
  26332. }
  26333. return _this._renderTargets;
  26334. };
  26335. }
  26336. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26337. get: function () {
  26338. return this._useLogarithmicDepth;
  26339. },
  26340. set: function (value) {
  26341. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26342. },
  26343. enumerable: true,
  26344. configurable: true
  26345. });
  26346. StandardMaterial.prototype.needAlphaBlending = function () {
  26347. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  26348. };
  26349. StandardMaterial.prototype.needAlphaTesting = function () {
  26350. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  26351. };
  26352. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26353. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  26354. };
  26355. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26356. return this.diffuseTexture;
  26357. };
  26358. // Methods
  26359. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  26360. if (!mesh) {
  26361. return true;
  26362. }
  26363. if (this._defines.INSTANCES !== useInstances) {
  26364. return false;
  26365. }
  26366. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  26367. return true;
  26368. }
  26369. return false;
  26370. };
  26371. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  26372. if (this.isFrozen) {
  26373. if (this._wasPreviouslyReady) {
  26374. return true;
  26375. }
  26376. }
  26377. var scene = this.getScene();
  26378. var engine = scene.getEngine();
  26379. var needUVs = false;
  26380. var needNormals = false;
  26381. this._defines.reset();
  26382. // Lights
  26383. if (scene.lightsEnabled && !this.disableLighting) {
  26384. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26385. }
  26386. if (!this.checkReadyOnEveryCall) {
  26387. if (this._renderId === scene.getRenderId()) {
  26388. if (this._checkCache(scene, mesh, useInstances)) {
  26389. return true;
  26390. }
  26391. }
  26392. }
  26393. // Textures
  26394. if (scene.texturesEnabled) {
  26395. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26396. if (!this.diffuseTexture.isReady()) {
  26397. return false;
  26398. }
  26399. else {
  26400. needUVs = true;
  26401. this._defines.DIFFUSE = true;
  26402. }
  26403. }
  26404. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26405. if (!this.ambientTexture.isReady()) {
  26406. return false;
  26407. }
  26408. else {
  26409. needUVs = true;
  26410. this._defines.AMBIENT = true;
  26411. }
  26412. }
  26413. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26414. if (!this.opacityTexture.isReady()) {
  26415. return false;
  26416. }
  26417. else {
  26418. needUVs = true;
  26419. this._defines.OPACITY = true;
  26420. if (this.opacityTexture.getAlphaFromRGB) {
  26421. this._defines.OPACITYRGB = true;
  26422. }
  26423. }
  26424. }
  26425. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26426. if (!this.reflectionTexture.isReady()) {
  26427. return false;
  26428. }
  26429. else {
  26430. needNormals = true;
  26431. this._defines.REFLECTION = true;
  26432. if (this.roughness > 0) {
  26433. this._defines.ROUGHNESS = true;
  26434. }
  26435. if (this.useReflectionOverAlpha) {
  26436. this._defines.REFLECTIONOVERALPHA = true;
  26437. }
  26438. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  26439. this._defines.INVERTCUBICMAP = true;
  26440. }
  26441. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  26442. switch (this.reflectionTexture.coordinatesMode) {
  26443. case BABYLON.Texture.CUBIC_MODE:
  26444. case BABYLON.Texture.INVCUBIC_MODE:
  26445. this._defines.REFLECTIONMAP_CUBIC = true;
  26446. break;
  26447. case BABYLON.Texture.EXPLICIT_MODE:
  26448. this._defines.REFLECTIONMAP_EXPLICIT = true;
  26449. break;
  26450. case BABYLON.Texture.PLANAR_MODE:
  26451. this._defines.REFLECTIONMAP_PLANAR = true;
  26452. break;
  26453. case BABYLON.Texture.PROJECTION_MODE:
  26454. this._defines.REFLECTIONMAP_PROJECTION = true;
  26455. break;
  26456. case BABYLON.Texture.SKYBOX_MODE:
  26457. this._defines.REFLECTIONMAP_SKYBOX = true;
  26458. break;
  26459. case BABYLON.Texture.SPHERICAL_MODE:
  26460. this._defines.REFLECTIONMAP_SPHERICAL = true;
  26461. break;
  26462. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26463. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  26464. break;
  26465. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26466. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  26467. break;
  26468. }
  26469. }
  26470. }
  26471. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26472. if (!this.emissiveTexture.isReady()) {
  26473. return false;
  26474. }
  26475. else {
  26476. needUVs = true;
  26477. this._defines.EMISSIVE = true;
  26478. }
  26479. }
  26480. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26481. if (!this.lightmapTexture.isReady()) {
  26482. return false;
  26483. }
  26484. else {
  26485. needUVs = true;
  26486. this._defines.LIGHTMAP = true;
  26487. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  26488. }
  26489. }
  26490. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26491. if (!this.specularTexture.isReady()) {
  26492. return false;
  26493. }
  26494. else {
  26495. needUVs = true;
  26496. this._defines.SPECULAR = true;
  26497. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  26498. }
  26499. }
  26500. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26501. if (!this.bumpTexture.isReady()) {
  26502. return false;
  26503. }
  26504. else {
  26505. needUVs = true;
  26506. this._defines.BUMP = true;
  26507. if (this.useParallax) {
  26508. this._defines.PARALLAX = true;
  26509. if (this.useParallaxOcclusion) {
  26510. this._defines.PARALLAXOCCLUSION = true;
  26511. }
  26512. }
  26513. if (this.invertNormalMapX) {
  26514. this._defines.INVERTNORMALMAPX = true;
  26515. }
  26516. if (this.invertNormalMapY) {
  26517. this._defines.INVERTNORMALMAPY = true;
  26518. }
  26519. }
  26520. }
  26521. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26522. if (!this.refractionTexture.isReady()) {
  26523. return false;
  26524. }
  26525. else {
  26526. needUVs = true;
  26527. this._defines.REFRACTION = true;
  26528. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26529. }
  26530. }
  26531. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26532. if (!this.cameraColorGradingTexture.isReady()) {
  26533. return false;
  26534. }
  26535. else {
  26536. this._defines.CAMERACOLORGRADING = true;
  26537. }
  26538. }
  26539. }
  26540. // Effect
  26541. if (scene.clipPlane) {
  26542. this._defines.CLIPPLANE = true;
  26543. }
  26544. if (engine.getAlphaTesting()) {
  26545. this._defines.ALPHATEST = true;
  26546. }
  26547. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26548. this._defines.ALPHAFROMDIFFUSE = true;
  26549. }
  26550. if (this.useEmissiveAsIllumination) {
  26551. this._defines.EMISSIVEASILLUMINATION = true;
  26552. }
  26553. if (this.linkEmissiveWithDiffuse) {
  26554. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26555. }
  26556. if (this.useLogarithmicDepth) {
  26557. this._defines.LOGARITHMICDEPTH = true;
  26558. }
  26559. if (this.cameraColorCurves) {
  26560. this._defines.CAMERACOLORCURVES = true;
  26561. }
  26562. // Point size
  26563. if (this.pointsCloud || scene.forcePointsCloud) {
  26564. this._defines.POINTSIZE = true;
  26565. }
  26566. // Fog
  26567. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26568. this._defines.FOG = true;
  26569. }
  26570. if (StandardMaterial.FresnelEnabled) {
  26571. // Fresnel
  26572. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26573. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26574. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26575. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26576. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26577. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26578. this._defines.DIFFUSEFRESNEL = true;
  26579. }
  26580. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26581. this._defines.OPACITYFRESNEL = true;
  26582. }
  26583. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26584. this._defines.REFLECTIONFRESNEL = true;
  26585. if (this.useReflectionFresnelFromSpecular) {
  26586. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26587. }
  26588. }
  26589. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26590. this._defines.REFRACTIONFRESNEL = true;
  26591. }
  26592. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26593. this._defines.EMISSIVEFRESNEL = true;
  26594. }
  26595. needNormals = true;
  26596. this._defines.FRESNEL = true;
  26597. }
  26598. }
  26599. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26600. this._defines.SPECULAROVERALPHA = true;
  26601. }
  26602. // Attribs
  26603. if (mesh) {
  26604. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26605. this._defines.NORMAL = true;
  26606. }
  26607. if (needUVs) {
  26608. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26609. this._defines.UV1 = true;
  26610. }
  26611. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26612. this._defines.UV2 = true;
  26613. }
  26614. }
  26615. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26616. this._defines.VERTEXCOLOR = true;
  26617. if (mesh.hasVertexAlpha) {
  26618. this._defines.VERTEXALPHA = true;
  26619. }
  26620. }
  26621. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26622. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26623. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26624. }
  26625. // Instances
  26626. if (useInstances) {
  26627. this._defines.INSTANCES = true;
  26628. }
  26629. }
  26630. // Get correct effect
  26631. if (!this._defines.isEqual(this._cachedDefines)) {
  26632. this._defines.cloneTo(this._cachedDefines);
  26633. scene.resetCachedMaterial();
  26634. // Fallbacks
  26635. var fallbacks = new BABYLON.EffectFallbacks();
  26636. if (this._defines.REFLECTION) {
  26637. fallbacks.addFallback(0, "REFLECTION");
  26638. }
  26639. if (this._defines.SPECULAR) {
  26640. fallbacks.addFallback(0, "SPECULAR");
  26641. }
  26642. if (this._defines.BUMP) {
  26643. fallbacks.addFallback(0, "BUMP");
  26644. }
  26645. if (this._defines.PARALLAX) {
  26646. fallbacks.addFallback(1, "PARALLAX");
  26647. }
  26648. if (this._defines.PARALLAXOCCLUSION) {
  26649. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26650. }
  26651. if (this._defines.SPECULAROVERALPHA) {
  26652. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26653. }
  26654. if (this._defines.FOG) {
  26655. fallbacks.addFallback(1, "FOG");
  26656. }
  26657. if (this._defines.POINTSIZE) {
  26658. fallbacks.addFallback(0, "POINTSIZE");
  26659. }
  26660. if (this._defines.LOGARITHMICDEPTH) {
  26661. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26662. }
  26663. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26664. if (this._defines.SPECULARTERM) {
  26665. fallbacks.addFallback(0, "SPECULARTERM");
  26666. }
  26667. if (this._defines.DIFFUSEFRESNEL) {
  26668. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26669. }
  26670. if (this._defines.OPACITYFRESNEL) {
  26671. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26672. }
  26673. if (this._defines.REFLECTIONFRESNEL) {
  26674. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26675. }
  26676. if (this._defines.EMISSIVEFRESNEL) {
  26677. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26678. }
  26679. if (this._defines.FRESNEL) {
  26680. fallbacks.addFallback(4, "FRESNEL");
  26681. }
  26682. //Attributes
  26683. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26684. if (this._defines.NORMAL) {
  26685. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26686. }
  26687. if (this._defines.UV1) {
  26688. attribs.push(BABYLON.VertexBuffer.UVKind);
  26689. }
  26690. if (this._defines.UV2) {
  26691. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26692. }
  26693. if (this._defines.VERTEXCOLOR) {
  26694. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26695. }
  26696. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26697. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26698. var shaderName = "default";
  26699. var join = this._defines.toString();
  26700. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26701. "vFogInfos", "vFogColor", "pointSize",
  26702. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26703. "mBones",
  26704. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26705. "depthValues",
  26706. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26707. "logarithmicDepthConstant"
  26708. ];
  26709. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26710. if (this._defines.CAMERACOLORCURVES) {
  26711. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26712. }
  26713. if (this._defines.CAMERACOLORGRADING) {
  26714. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26715. }
  26716. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26717. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26718. }
  26719. if (!this._effect.isReady()) {
  26720. return false;
  26721. }
  26722. this._renderId = scene.getRenderId();
  26723. this._wasPreviouslyReady = true;
  26724. if (mesh) {
  26725. if (!mesh._materialDefines) {
  26726. mesh._materialDefines = new StandardMaterialDefines();
  26727. }
  26728. this._defines.cloneTo(mesh._materialDefines);
  26729. }
  26730. return true;
  26731. };
  26732. StandardMaterial.prototype.unbind = function () {
  26733. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26734. this._effect.setTexture("reflection2DSampler", null);
  26735. }
  26736. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26737. this._effect.setTexture("refraction2DSampler", null);
  26738. }
  26739. _super.prototype.unbind.call(this);
  26740. };
  26741. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26742. this._effect.setMatrix("world", world);
  26743. };
  26744. StandardMaterial.prototype.bind = function (world, mesh) {
  26745. var scene = this.getScene();
  26746. // Matrices
  26747. this.bindOnlyWorldMatrix(world);
  26748. // Bones
  26749. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26750. if (scene.getCachedMaterial() !== this) {
  26751. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26752. if (StandardMaterial.FresnelEnabled) {
  26753. // Fresnel
  26754. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26755. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26756. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26757. }
  26758. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26759. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26760. }
  26761. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26762. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26763. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26764. }
  26765. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26766. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26767. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26768. }
  26769. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26770. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26771. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26772. }
  26773. }
  26774. // Textures
  26775. if (scene.texturesEnabled) {
  26776. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26777. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26778. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26779. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26780. }
  26781. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26782. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26783. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26784. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26785. }
  26786. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26787. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26788. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26789. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26790. }
  26791. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26792. if (this.reflectionTexture.isCube) {
  26793. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26794. }
  26795. else {
  26796. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26797. }
  26798. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26799. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26800. }
  26801. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26802. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26803. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26804. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26805. }
  26806. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26807. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26808. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26809. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26810. }
  26811. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26812. this._effect.setTexture("specularSampler", this.specularTexture);
  26813. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26814. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26815. }
  26816. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26817. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26818. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26819. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26820. }
  26821. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26822. var depth = 1.0;
  26823. if (this.refractionTexture.isCube) {
  26824. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26825. }
  26826. else {
  26827. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26828. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26829. if (this.refractionTexture.depth) {
  26830. depth = this.refractionTexture.depth;
  26831. }
  26832. }
  26833. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26834. }
  26835. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26836. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26837. }
  26838. }
  26839. // Clip plane
  26840. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26841. // Point size
  26842. if (this.pointsCloud) {
  26843. this._effect.setFloat("pointSize", this.pointSize);
  26844. }
  26845. // Colors
  26846. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26847. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26848. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26849. if (this._defines.SPECULARTERM) {
  26850. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26851. }
  26852. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26853. }
  26854. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26855. // Diffuse
  26856. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26857. // Lights
  26858. if (scene.lightsEnabled && !this.disableLighting) {
  26859. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26860. }
  26861. // View
  26862. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26863. this._effect.setMatrix("view", scene.getViewMatrix());
  26864. }
  26865. // Fog
  26866. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26867. // Log. depth
  26868. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26869. // Color Curves
  26870. if (this.cameraColorCurves) {
  26871. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26872. }
  26873. }
  26874. _super.prototype.bind.call(this, world, mesh);
  26875. };
  26876. StandardMaterial.prototype.getAnimatables = function () {
  26877. var results = [];
  26878. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26879. results.push(this.diffuseTexture);
  26880. }
  26881. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26882. results.push(this.ambientTexture);
  26883. }
  26884. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26885. results.push(this.opacityTexture);
  26886. }
  26887. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26888. results.push(this.reflectionTexture);
  26889. }
  26890. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26891. results.push(this.emissiveTexture);
  26892. }
  26893. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26894. results.push(this.specularTexture);
  26895. }
  26896. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26897. results.push(this.bumpTexture);
  26898. }
  26899. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26900. results.push(this.lightmapTexture);
  26901. }
  26902. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26903. results.push(this.refractionTexture);
  26904. }
  26905. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26906. results.push(this.cameraColorGradingTexture);
  26907. }
  26908. return results;
  26909. };
  26910. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26911. if (forceDisposeTextures) {
  26912. if (this.diffuseTexture) {
  26913. this.diffuseTexture.dispose();
  26914. }
  26915. if (this.ambientTexture) {
  26916. this.ambientTexture.dispose();
  26917. }
  26918. if (this.opacityTexture) {
  26919. this.opacityTexture.dispose();
  26920. }
  26921. if (this.reflectionTexture) {
  26922. this.reflectionTexture.dispose();
  26923. }
  26924. if (this.emissiveTexture) {
  26925. this.emissiveTexture.dispose();
  26926. }
  26927. if (this.specularTexture) {
  26928. this.specularTexture.dispose();
  26929. }
  26930. if (this.bumpTexture) {
  26931. this.bumpTexture.dispose();
  26932. }
  26933. if (this.lightmapTexture) {
  26934. this.lightmapTexture.dispose();
  26935. }
  26936. if (this.refractionTexture) {
  26937. this.refractionTexture.dispose();
  26938. }
  26939. if (this.cameraColorGradingTexture) {
  26940. this.cameraColorGradingTexture.dispose();
  26941. }
  26942. }
  26943. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26944. };
  26945. StandardMaterial.prototype.clone = function (name) {
  26946. var _this = this;
  26947. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  26948. };
  26949. StandardMaterial.prototype.serialize = function () {
  26950. return BABYLON.SerializationHelper.Serialize(this);
  26951. };
  26952. // Statics
  26953. StandardMaterial.Parse = function (source, scene, rootUrl) {
  26954. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  26955. };
  26956. // Flags used to enable or disable a type of texture for all Standard Materials
  26957. StandardMaterial.DiffuseTextureEnabled = true;
  26958. StandardMaterial.AmbientTextureEnabled = true;
  26959. StandardMaterial.OpacityTextureEnabled = true;
  26960. StandardMaterial.ReflectionTextureEnabled = true;
  26961. StandardMaterial.EmissiveTextureEnabled = true;
  26962. StandardMaterial.SpecularTextureEnabled = true;
  26963. StandardMaterial.BumpTextureEnabled = true;
  26964. StandardMaterial.FresnelEnabled = true;
  26965. StandardMaterial.LightmapTextureEnabled = true;
  26966. StandardMaterial.RefractionTextureEnabled = true;
  26967. StandardMaterial.ColorGradingTextureEnabled = true;
  26968. __decorate([
  26969. BABYLON.serializeAsTexture()
  26970. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  26971. __decorate([
  26972. BABYLON.serializeAsTexture()
  26973. ], StandardMaterial.prototype, "ambientTexture", void 0);
  26974. __decorate([
  26975. BABYLON.serializeAsTexture()
  26976. ], StandardMaterial.prototype, "opacityTexture", void 0);
  26977. __decorate([
  26978. BABYLON.serializeAsTexture()
  26979. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  26980. __decorate([
  26981. BABYLON.serializeAsTexture()
  26982. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  26983. __decorate([
  26984. BABYLON.serializeAsTexture()
  26985. ], StandardMaterial.prototype, "specularTexture", void 0);
  26986. __decorate([
  26987. BABYLON.serializeAsTexture()
  26988. ], StandardMaterial.prototype, "bumpTexture", void 0);
  26989. __decorate([
  26990. BABYLON.serializeAsTexture()
  26991. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  26992. __decorate([
  26993. BABYLON.serializeAsTexture()
  26994. ], StandardMaterial.prototype, "refractionTexture", void 0);
  26995. __decorate([
  26996. BABYLON.serializeAsColor3("ambient")
  26997. ], StandardMaterial.prototype, "ambientColor", void 0);
  26998. __decorate([
  26999. BABYLON.serializeAsColor3("diffuse")
  27000. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27001. __decorate([
  27002. BABYLON.serializeAsColor3("specular")
  27003. ], StandardMaterial.prototype, "specularColor", void 0);
  27004. __decorate([
  27005. BABYLON.serializeAsColor3("emissive")
  27006. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27007. __decorate([
  27008. BABYLON.serialize()
  27009. ], StandardMaterial.prototype, "specularPower", void 0);
  27010. __decorate([
  27011. BABYLON.serialize()
  27012. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27013. __decorate([
  27014. BABYLON.serialize()
  27015. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27016. __decorate([
  27017. BABYLON.serialize()
  27018. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27019. __decorate([
  27020. BABYLON.serialize()
  27021. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27022. __decorate([
  27023. BABYLON.serialize()
  27024. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27025. __decorate([
  27026. BABYLON.serialize()
  27027. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27028. __decorate([
  27029. BABYLON.serialize()
  27030. ], StandardMaterial.prototype, "disableLighting", void 0);
  27031. __decorate([
  27032. BABYLON.serialize()
  27033. ], StandardMaterial.prototype, "useParallax", void 0);
  27034. __decorate([
  27035. BABYLON.serialize()
  27036. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27037. __decorate([
  27038. BABYLON.serialize()
  27039. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27040. __decorate([
  27041. BABYLON.serialize()
  27042. ], StandardMaterial.prototype, "roughness", void 0);
  27043. __decorate([
  27044. BABYLON.serialize()
  27045. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27046. __decorate([
  27047. BABYLON.serialize()
  27048. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27049. __decorate([
  27050. BABYLON.serialize()
  27051. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27052. __decorate([
  27053. BABYLON.serializeAsFresnelParameters()
  27054. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27055. __decorate([
  27056. BABYLON.serializeAsFresnelParameters()
  27057. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27058. __decorate([
  27059. BABYLON.serializeAsFresnelParameters()
  27060. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27061. __decorate([
  27062. BABYLON.serializeAsFresnelParameters()
  27063. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27064. __decorate([
  27065. BABYLON.serializeAsFresnelParameters()
  27066. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27067. __decorate([
  27068. BABYLON.serialize()
  27069. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27070. __decorate([
  27071. BABYLON.serialize()
  27072. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27073. __decorate([
  27074. BABYLON.serialize()
  27075. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27076. __decorate([
  27077. BABYLON.serialize()
  27078. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27079. __decorate([
  27080. BABYLON.serializeAsTexture()
  27081. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27082. __decorate([
  27083. BABYLON.serializeAsColorCurves()
  27084. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27085. __decorate([
  27086. BABYLON.serialize()
  27087. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27088. return StandardMaterial;
  27089. }(BABYLON.Material));
  27090. BABYLON.StandardMaterial = StandardMaterial;
  27091. })(BABYLON || (BABYLON = {}));
  27092. //# sourceMappingURL=babylon.standardMaterial.js.map
  27093. var BABYLON;
  27094. (function (BABYLON) {
  27095. var MultiMaterial = (function (_super) {
  27096. __extends(MultiMaterial, _super);
  27097. function MultiMaterial(name, scene) {
  27098. _super.call(this, name, scene, true);
  27099. this.subMaterials = new Array();
  27100. scene.multiMaterials.push(this);
  27101. }
  27102. // Properties
  27103. MultiMaterial.prototype.getSubMaterial = function (index) {
  27104. if (index < 0 || index >= this.subMaterials.length) {
  27105. return this.getScene().defaultMaterial;
  27106. }
  27107. return this.subMaterials[index];
  27108. };
  27109. // Methods
  27110. MultiMaterial.prototype.isReady = function (mesh) {
  27111. for (var index = 0; index < this.subMaterials.length; index++) {
  27112. var subMaterial = this.subMaterials[index];
  27113. if (subMaterial) {
  27114. if (!this.subMaterials[index].isReady(mesh)) {
  27115. return false;
  27116. }
  27117. }
  27118. }
  27119. return true;
  27120. };
  27121. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27122. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27123. for (var index = 0; index < this.subMaterials.length; index++) {
  27124. var subMaterial = null;
  27125. if (cloneChildren) {
  27126. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27127. }
  27128. else {
  27129. subMaterial = this.subMaterials[index];
  27130. }
  27131. newMultiMaterial.subMaterials.push(subMaterial);
  27132. }
  27133. return newMultiMaterial;
  27134. };
  27135. MultiMaterial.prototype.serialize = function () {
  27136. var serializationObject = {};
  27137. serializationObject.name = this.name;
  27138. serializationObject.id = this.id;
  27139. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27140. serializationObject.materials = [];
  27141. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27142. var subMat = this.subMaterials[matIndex];
  27143. if (subMat) {
  27144. serializationObject.materials.push(subMat.id);
  27145. }
  27146. else {
  27147. serializationObject.materials.push(null);
  27148. }
  27149. }
  27150. return serializationObject;
  27151. };
  27152. return MultiMaterial;
  27153. }(BABYLON.Material));
  27154. BABYLON.MultiMaterial = MultiMaterial;
  27155. })(BABYLON || (BABYLON = {}));
  27156. //# sourceMappingURL=babylon.multiMaterial.js.map
  27157. var BABYLON;
  27158. (function (BABYLON) {
  27159. var SceneLoader = (function () {
  27160. function SceneLoader() {
  27161. }
  27162. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27163. get: function () {
  27164. return 0;
  27165. },
  27166. enumerable: true,
  27167. configurable: true
  27168. });
  27169. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27170. get: function () {
  27171. return 1;
  27172. },
  27173. enumerable: true,
  27174. configurable: true
  27175. });
  27176. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  27177. get: function () {
  27178. return 2;
  27179. },
  27180. enumerable: true,
  27181. configurable: true
  27182. });
  27183. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  27184. get: function () {
  27185. return 3;
  27186. },
  27187. enumerable: true,
  27188. configurable: true
  27189. });
  27190. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  27191. get: function () {
  27192. return SceneLoader._ForceFullSceneLoadingForIncremental;
  27193. },
  27194. set: function (value) {
  27195. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  27196. },
  27197. enumerable: true,
  27198. configurable: true
  27199. });
  27200. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  27201. get: function () {
  27202. return SceneLoader._ShowLoadingScreen;
  27203. },
  27204. set: function (value) {
  27205. SceneLoader._ShowLoadingScreen = value;
  27206. },
  27207. enumerable: true,
  27208. configurable: true
  27209. });
  27210. Object.defineProperty(SceneLoader, "loggingLevel", {
  27211. get: function () {
  27212. return SceneLoader._loggingLevel;
  27213. },
  27214. set: function (value) {
  27215. SceneLoader._loggingLevel = value;
  27216. },
  27217. enumerable: true,
  27218. configurable: true
  27219. });
  27220. SceneLoader._getDefaultPlugin = function () {
  27221. return SceneLoader._registeredPlugins[".babylon"];
  27222. };
  27223. SceneLoader._getPluginForExtension = function (extension) {
  27224. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  27225. if (registeredPlugin) {
  27226. return registeredPlugin;
  27227. }
  27228. return SceneLoader._getDefaultPlugin();
  27229. };
  27230. SceneLoader._getPluginForFilename = function (sceneFilename) {
  27231. if (sceneFilename.name) {
  27232. sceneFilename = sceneFilename.name;
  27233. }
  27234. var dotPosition = sceneFilename.lastIndexOf(".");
  27235. var queryStringPosition = sceneFilename.indexOf("?");
  27236. if (queryStringPosition === -1) {
  27237. queryStringPosition = sceneFilename.length;
  27238. }
  27239. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  27240. return SceneLoader._getPluginForExtension(extension);
  27241. };
  27242. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  27243. SceneLoader._getDirectLoad = function (sceneFilename) {
  27244. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  27245. return sceneFilename.substr(5);
  27246. }
  27247. return null;
  27248. };
  27249. // Public functions
  27250. SceneLoader.GetPluginForExtension = function (extension) {
  27251. return SceneLoader._getPluginForExtension(extension).plugin;
  27252. };
  27253. SceneLoader.RegisterPlugin = function (plugin) {
  27254. if (typeof plugin.extensions === "string") {
  27255. var extension = plugin.extensions;
  27256. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27257. plugin: plugin,
  27258. isBinary: false
  27259. };
  27260. }
  27261. else {
  27262. var extensions = plugin.extensions;
  27263. Object.keys(extensions).forEach(function (extension) {
  27264. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27265. plugin: plugin,
  27266. isBinary: extensions[extension].isBinary
  27267. };
  27268. });
  27269. }
  27270. };
  27271. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27272. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27273. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27274. return;
  27275. }
  27276. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27277. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27278. return;
  27279. }
  27280. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27281. var loadingToken = {};
  27282. scene._addPendingData(loadingToken);
  27283. var manifestChecked = function (success) {
  27284. scene.database = database;
  27285. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27286. var plugin = registeredPlugin.plugin;
  27287. var useArrayBuffer = registeredPlugin.isBinary;
  27288. var importMeshFromData = function (data) {
  27289. var meshes = [];
  27290. var particleSystems = [];
  27291. var skeletons = [];
  27292. try {
  27293. if (plugin.importMesh) {
  27294. var syncedPlugin = plugin;
  27295. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  27296. if (onerror) {
  27297. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27298. }
  27299. scene._removePendingData(loadingToken);
  27300. return;
  27301. }
  27302. if (onsuccess) {
  27303. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27304. onsuccess(meshes, particleSystems, skeletons);
  27305. scene._removePendingData(loadingToken);
  27306. }
  27307. }
  27308. else {
  27309. var asyncedPlugin = plugin;
  27310. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  27311. if (onsuccess) {
  27312. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27313. onsuccess(meshes, particleSystems, skeletons);
  27314. scene._removePendingData(loadingToken);
  27315. }
  27316. }, function () {
  27317. if (onerror) {
  27318. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27319. }
  27320. scene._removePendingData(loadingToken);
  27321. });
  27322. }
  27323. }
  27324. catch (e) {
  27325. if (onerror) {
  27326. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  27327. }
  27328. scene._removePendingData(loadingToken);
  27329. }
  27330. };
  27331. if (directLoad) {
  27332. importMeshFromData(directLoad);
  27333. return;
  27334. }
  27335. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  27336. importMeshFromData(data);
  27337. }, progressCallBack, database, useArrayBuffer);
  27338. };
  27339. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  27340. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27341. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27342. }
  27343. else {
  27344. // If the scene is a data stream or offline support is not enabled, it's a direct load
  27345. manifestChecked(true);
  27346. }
  27347. };
  27348. /**
  27349. * Load a scene
  27350. * @param rootUrl a string that defines the root url for scene and resources
  27351. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27352. * @param engine is the instance of BABYLON.Engine to use to create the scene
  27353. */
  27354. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  27355. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  27356. };
  27357. /**
  27358. * Append a scene
  27359. * @param rootUrl a string that defines the root url for scene and resources
  27360. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27361. * @param scene is the instance of BABYLON.Scene to append to
  27362. */
  27363. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27364. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27365. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27366. return;
  27367. }
  27368. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27369. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27370. var plugin = registeredPlugin.plugin;
  27371. var useArrayBuffer = registeredPlugin.isBinary;
  27372. var database;
  27373. var loadingToken = {};
  27374. scene._addPendingData(loadingToken);
  27375. if (SceneLoader.ShowLoadingScreen) {
  27376. scene.getEngine().displayLoadingUI();
  27377. }
  27378. var loadSceneFromData = function (data) {
  27379. scene.database = database;
  27380. if (plugin.load) {
  27381. var syncedPlugin = plugin;
  27382. if (!syncedPlugin.load(scene, data, rootUrl)) {
  27383. if (onerror) {
  27384. onerror(scene);
  27385. }
  27386. scene._removePendingData(loadingToken);
  27387. scene.getEngine().hideLoadingUI();
  27388. return;
  27389. }
  27390. if (onsuccess) {
  27391. onsuccess(scene);
  27392. }
  27393. scene._removePendingData(loadingToken);
  27394. }
  27395. else {
  27396. var asyncedPlugin = plugin;
  27397. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  27398. if (onsuccess) {
  27399. onsuccess(scene);
  27400. }
  27401. scene._removePendingData(loadingToken);
  27402. }, function () {
  27403. if (onerror) {
  27404. onerror(scene);
  27405. }
  27406. scene._removePendingData(loadingToken);
  27407. scene.getEngine().hideLoadingUI();
  27408. });
  27409. }
  27410. if (SceneLoader.ShowLoadingScreen) {
  27411. scene.executeWhenReady(function () {
  27412. scene.getEngine().hideLoadingUI();
  27413. });
  27414. }
  27415. };
  27416. var manifestChecked = function (success) {
  27417. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  27418. };
  27419. if (directLoad) {
  27420. loadSceneFromData(directLoad);
  27421. return;
  27422. }
  27423. if (rootUrl.indexOf("file:") === -1) {
  27424. if (scene.getEngine().enableOfflineSupport) {
  27425. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27426. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27427. }
  27428. else {
  27429. manifestChecked(true);
  27430. }
  27431. }
  27432. else {
  27433. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  27434. }
  27435. };
  27436. // Flags
  27437. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  27438. SceneLoader._ShowLoadingScreen = true;
  27439. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  27440. // Members
  27441. SceneLoader._registeredPlugins = {};
  27442. return SceneLoader;
  27443. }());
  27444. BABYLON.SceneLoader = SceneLoader;
  27445. ;
  27446. })(BABYLON || (BABYLON = {}));
  27447. //# sourceMappingURL=babylon.sceneLoader.js.map
  27448. var BABYLON;
  27449. (function (BABYLON) {
  27450. var Internals;
  27451. (function (Internals) {
  27452. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  27453. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27454. var parsedMaterial = parsedData.materials[index];
  27455. if (parsedMaterial.id === id) {
  27456. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27457. }
  27458. }
  27459. return null;
  27460. };
  27461. var isDescendantOf = function (mesh, names, hierarchyIds) {
  27462. names = (names instanceof Array) ? names : [names];
  27463. for (var i in names) {
  27464. if (mesh.name === names[i]) {
  27465. hierarchyIds.push(mesh.id);
  27466. return true;
  27467. }
  27468. }
  27469. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  27470. hierarchyIds.push(mesh.id);
  27471. return true;
  27472. }
  27473. return false;
  27474. };
  27475. var logOperation = function (operation, producer) {
  27476. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  27477. };
  27478. BABYLON.SceneLoader.RegisterPlugin({
  27479. extensions: ".babylon",
  27480. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  27481. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27482. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27483. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27484. // and avoid problems with multiple concurrent .babylon loads.
  27485. var log = "importMesh has failed JSON parse";
  27486. try {
  27487. var parsedData = JSON.parse(data);
  27488. log = "";
  27489. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27490. var loadedSkeletonsIds = [];
  27491. var loadedMaterialsIds = [];
  27492. var hierarchyIds = [];
  27493. var index;
  27494. var cache;
  27495. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27496. var parsedMesh = parsedData.meshes[index];
  27497. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  27498. if (meshesNames instanceof Array) {
  27499. // Remove found mesh name from list.
  27500. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  27501. }
  27502. //Geometry?
  27503. if (parsedMesh.geometryId) {
  27504. //does the file contain geometries?
  27505. if (parsedData.geometries) {
  27506. //find the correct geometry and add it to the scene
  27507. var found = false;
  27508. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  27509. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  27510. return;
  27511. }
  27512. else {
  27513. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  27514. if (parsedGeometryData.id === parsedMesh.geometryId) {
  27515. switch (geometryType) {
  27516. case "boxes":
  27517. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  27518. break;
  27519. case "spheres":
  27520. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  27521. break;
  27522. case "cylinders":
  27523. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27524. break;
  27525. case "toruses":
  27526. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27527. break;
  27528. case "grounds":
  27529. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27530. break;
  27531. case "planes":
  27532. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27533. break;
  27534. case "torusKnots":
  27535. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27536. break;
  27537. case "vertexData":
  27538. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27539. break;
  27540. }
  27541. found = true;
  27542. }
  27543. });
  27544. }
  27545. });
  27546. if (!found) {
  27547. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27548. }
  27549. }
  27550. }
  27551. // Material ?
  27552. if (parsedMesh.materialId) {
  27553. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27554. if (!materialFound && parsedData.multiMaterials) {
  27555. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27556. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27557. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27558. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27559. var subMatId = parsedMultiMaterial.materials[matIndex];
  27560. loadedMaterialsIds.push(subMatId);
  27561. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27562. log += "\n\tMaterial " + mat.toString(fullDetails);
  27563. }
  27564. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27565. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27566. materialFound = true;
  27567. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27568. break;
  27569. }
  27570. }
  27571. }
  27572. if (!materialFound) {
  27573. loadedMaterialsIds.push(parsedMesh.materialId);
  27574. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27575. if (!mat) {
  27576. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27577. }
  27578. else {
  27579. log += "\n\tMaterial " + mat.toString(fullDetails);
  27580. }
  27581. }
  27582. }
  27583. // Skeleton ?
  27584. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27585. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27586. if (!skeletonAlreadyLoaded) {
  27587. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27588. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27589. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27590. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27591. skeletons.push(skeleton);
  27592. loadedSkeletonsIds.push(parsedSkeleton.id);
  27593. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27594. }
  27595. }
  27596. }
  27597. }
  27598. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27599. meshes.push(mesh);
  27600. log += "\n\tMesh " + mesh.toString(fullDetails);
  27601. }
  27602. }
  27603. // Connecting parents
  27604. var currentMesh;
  27605. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27606. currentMesh = scene.meshes[index];
  27607. if (currentMesh._waitingParentId) {
  27608. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27609. currentMesh._waitingParentId = undefined;
  27610. }
  27611. }
  27612. // freeze and compute world matrix application
  27613. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27614. currentMesh = scene.meshes[index];
  27615. if (currentMesh._waitingFreezeWorldMatrix) {
  27616. currentMesh.freezeWorldMatrix();
  27617. currentMesh._waitingFreezeWorldMatrix = undefined;
  27618. }
  27619. else {
  27620. currentMesh.computeWorldMatrix(true);
  27621. }
  27622. }
  27623. // Particles
  27624. if (parsedData.particleSystems) {
  27625. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27626. var parsedParticleSystem = parsedData.particleSystems[index];
  27627. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27628. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27629. }
  27630. }
  27631. }
  27632. return true;
  27633. }
  27634. catch (err) {
  27635. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27636. log = null;
  27637. throw err;
  27638. }
  27639. finally {
  27640. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27641. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27642. }
  27643. }
  27644. },
  27645. load: function (scene, data, rootUrl) {
  27646. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27647. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27648. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27649. // and avoid problems with multiple concurrent .babylon loads.
  27650. var log = "importScene has failed JSON parse";
  27651. try {
  27652. var parsedData = JSON.parse(data);
  27653. log = "";
  27654. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27655. // Scene
  27656. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27657. scene.autoClear = parsedData.autoClear;
  27658. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27659. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27660. if (parsedData.gravity) {
  27661. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27662. }
  27663. // Fog
  27664. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27665. scene.fogMode = parsedData.fogMode;
  27666. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27667. scene.fogStart = parsedData.fogStart;
  27668. scene.fogEnd = parsedData.fogEnd;
  27669. scene.fogDensity = parsedData.fogDensity;
  27670. log += "\tFog mode for scene: ";
  27671. switch (scene.fogMode) {
  27672. // getters not compiling, so using hardcoded
  27673. case 1:
  27674. log += "exp\n";
  27675. break;
  27676. case 2:
  27677. log += "exp2\n";
  27678. break;
  27679. case 3:
  27680. log += "linear\n";
  27681. break;
  27682. }
  27683. }
  27684. //Physics
  27685. if (parsedData.physicsEnabled) {
  27686. var physicsPlugin;
  27687. if (parsedData.physicsEngine === "cannon") {
  27688. physicsPlugin = new BABYLON.CannonJSPlugin();
  27689. }
  27690. else if (parsedData.physicsEngine === "oimo") {
  27691. physicsPlugin = new BABYLON.OimoJSPlugin();
  27692. }
  27693. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27694. //else - default engine, which is currently oimo
  27695. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27696. scene.enablePhysics(physicsGravity, physicsPlugin);
  27697. }
  27698. // Metadata
  27699. if (parsedData.metadata !== undefined) {
  27700. scene.metadata = parsedData.metadata;
  27701. }
  27702. //collisions, if defined. otherwise, default is true
  27703. if (parsedData.collisionsEnabled != undefined) {
  27704. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27705. }
  27706. scene.workerCollisions = !!parsedData.workerCollisions;
  27707. var index;
  27708. var cache;
  27709. // Lights
  27710. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27711. var parsedLight = parsedData.lights[index];
  27712. var light = BABYLON.Light.Parse(parsedLight, scene);
  27713. log += (index === 0 ? "\n\tLights:" : "");
  27714. log += "\n\t\t" + light.toString(fullDetails);
  27715. }
  27716. // Animations
  27717. if (parsedData.animations) {
  27718. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27719. var parsedAnimation = parsedData.animations[index];
  27720. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27721. scene.animations.push(animation);
  27722. log += (index === 0 ? "\n\tAnimations:" : "");
  27723. log += "\n\t\t" + animation.toString(fullDetails);
  27724. }
  27725. }
  27726. if (parsedData.autoAnimate) {
  27727. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27728. }
  27729. // Materials
  27730. if (parsedData.materials) {
  27731. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27732. var parsedMaterial = parsedData.materials[index];
  27733. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27734. log += (index === 0 ? "\n\tMaterials:" : "");
  27735. log += "\n\t\t" + mat.toString(fullDetails);
  27736. }
  27737. }
  27738. if (parsedData.multiMaterials) {
  27739. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27740. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27741. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27742. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27743. log += "\n\t\t" + mmat.toString(fullDetails);
  27744. }
  27745. }
  27746. // Skeletons
  27747. if (parsedData.skeletons) {
  27748. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27749. var parsedSkeleton = parsedData.skeletons[index];
  27750. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27751. log += (index === 0 ? "\n\tSkeletons:" : "");
  27752. log += "\n\t\t" + skeleton.toString(fullDetails);
  27753. }
  27754. }
  27755. // Geometries
  27756. var geometries = parsedData.geometries;
  27757. if (geometries) {
  27758. // Boxes
  27759. var boxes = geometries.boxes;
  27760. if (boxes) {
  27761. for (index = 0, cache = boxes.length; index < cache; index++) {
  27762. var parsedBox = boxes[index];
  27763. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27764. }
  27765. }
  27766. // Spheres
  27767. var spheres = geometries.spheres;
  27768. if (spheres) {
  27769. for (index = 0, cache = spheres.length; index < cache; index++) {
  27770. var parsedSphere = spheres[index];
  27771. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27772. }
  27773. }
  27774. // Cylinders
  27775. var cylinders = geometries.cylinders;
  27776. if (cylinders) {
  27777. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27778. var parsedCylinder = cylinders[index];
  27779. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27780. }
  27781. }
  27782. // Toruses
  27783. var toruses = geometries.toruses;
  27784. if (toruses) {
  27785. for (index = 0, cache = toruses.length; index < cache; index++) {
  27786. var parsedTorus = toruses[index];
  27787. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27788. }
  27789. }
  27790. // Grounds
  27791. var grounds = geometries.grounds;
  27792. if (grounds) {
  27793. for (index = 0, cache = grounds.length; index < cache; index++) {
  27794. var parsedGround = grounds[index];
  27795. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27796. }
  27797. }
  27798. // Planes
  27799. var planes = geometries.planes;
  27800. if (planes) {
  27801. for (index = 0, cache = planes.length; index < cache; index++) {
  27802. var parsedPlane = planes[index];
  27803. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27804. }
  27805. }
  27806. // TorusKnots
  27807. var torusKnots = geometries.torusKnots;
  27808. if (torusKnots) {
  27809. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27810. var parsedTorusKnot = torusKnots[index];
  27811. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27812. }
  27813. }
  27814. // VertexData
  27815. var vertexData = geometries.vertexData;
  27816. if (vertexData) {
  27817. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27818. var parsedVertexData = vertexData[index];
  27819. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27820. }
  27821. }
  27822. }
  27823. // Meshes
  27824. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27825. var parsedMesh = parsedData.meshes[index];
  27826. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27827. log += (index === 0 ? "\n\tMeshes:" : "");
  27828. log += "\n\t\t" + mesh.toString(fullDetails);
  27829. }
  27830. // Cameras
  27831. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27832. var parsedCamera = parsedData.cameras[index];
  27833. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27834. log += (index === 0 ? "\n\tCameras:" : "");
  27835. log += "\n\t\t" + camera.toString(fullDetails);
  27836. }
  27837. if (parsedData.activeCameraID) {
  27838. scene.setActiveCameraByID(parsedData.activeCameraID);
  27839. }
  27840. // Browsing all the graph to connect the dots
  27841. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27842. var camera = scene.cameras[index];
  27843. if (camera._waitingParentId) {
  27844. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27845. camera._waitingParentId = undefined;
  27846. }
  27847. }
  27848. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27849. var light = scene.lights[index];
  27850. if (light._waitingParentId) {
  27851. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27852. light._waitingParentId = undefined;
  27853. }
  27854. }
  27855. // Sounds
  27856. var loadedSounds = [];
  27857. var loadedSound;
  27858. if (BABYLON.AudioEngine && parsedData.sounds) {
  27859. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27860. var parsedSound = parsedData.sounds[index];
  27861. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27862. if (!parsedSound.url)
  27863. parsedSound.url = parsedSound.name;
  27864. if (!loadedSounds[parsedSound.url]) {
  27865. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27866. loadedSounds[parsedSound.url] = loadedSound;
  27867. }
  27868. else {
  27869. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27870. }
  27871. }
  27872. else {
  27873. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27874. }
  27875. }
  27876. }
  27877. loadedSounds = [];
  27878. // Connect parents & children and parse actions
  27879. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27880. var mesh = scene.meshes[index];
  27881. if (mesh._waitingParentId) {
  27882. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27883. mesh._waitingParentId = undefined;
  27884. }
  27885. if (mesh._waitingActions) {
  27886. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27887. mesh._waitingActions = undefined;
  27888. }
  27889. }
  27890. // freeze world matrix application
  27891. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27892. var currentMesh = scene.meshes[index];
  27893. if (currentMesh._waitingFreezeWorldMatrix) {
  27894. currentMesh.freezeWorldMatrix();
  27895. currentMesh._waitingFreezeWorldMatrix = undefined;
  27896. }
  27897. else {
  27898. currentMesh.computeWorldMatrix(true);
  27899. }
  27900. }
  27901. // Particles Systems
  27902. if (parsedData.particleSystems) {
  27903. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27904. var parsedParticleSystem = parsedData.particleSystems[index];
  27905. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27906. }
  27907. }
  27908. // Lens flares
  27909. if (parsedData.lensFlareSystems) {
  27910. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27911. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27912. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27913. }
  27914. }
  27915. // Shadows
  27916. if (parsedData.shadowGenerators) {
  27917. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27918. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27919. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27920. }
  27921. }
  27922. // Actions (scene)
  27923. if (parsedData.actions) {
  27924. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27925. }
  27926. // Finish
  27927. return true;
  27928. }
  27929. catch (err) {
  27930. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27931. log = null;
  27932. throw err;
  27933. }
  27934. finally {
  27935. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27936. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27937. }
  27938. }
  27939. }
  27940. });
  27941. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27942. })(BABYLON || (BABYLON = {}));
  27943. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  27944. var BABYLON;
  27945. (function (BABYLON) {
  27946. var SpriteManager = (function () {
  27947. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  27948. if (epsilon === void 0) { epsilon = 0.01; }
  27949. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27950. this.name = name;
  27951. this.sprites = new Array();
  27952. this.renderingGroupId = 0;
  27953. this.layerMask = 0x0FFFFFFF;
  27954. this.fogEnabled = true;
  27955. this.isPickable = false;
  27956. /**
  27957. * An event triggered when the manager is disposed.
  27958. * @type {BABYLON.Observable}
  27959. */
  27960. this.onDisposeObservable = new BABYLON.Observable();
  27961. this._vertexBuffers = {};
  27962. this._capacity = capacity;
  27963. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  27964. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27965. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27966. if (cellSize.width && cellSize.height) {
  27967. this.cellWidth = cellSize.width;
  27968. this.cellHeight = cellSize.height;
  27969. }
  27970. else if (cellSize !== undefined) {
  27971. this.cellWidth = cellSize;
  27972. this.cellHeight = cellSize;
  27973. }
  27974. else {
  27975. return;
  27976. }
  27977. this._epsilon = epsilon;
  27978. this._scene = scene;
  27979. this._scene.spriteManagers.push(this);
  27980. var indices = [];
  27981. var index = 0;
  27982. for (var count = 0; count < capacity; count++) {
  27983. indices.push(index);
  27984. indices.push(index + 1);
  27985. indices.push(index + 2);
  27986. indices.push(index);
  27987. indices.push(index + 2);
  27988. indices.push(index + 3);
  27989. index += 4;
  27990. }
  27991. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27992. // VBO
  27993. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  27994. this._vertexData = new Float32Array(capacity * 16 * 4);
  27995. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  27996. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  27997. var options = this._buffer.createVertexBuffer("options", 4, 4);
  27998. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  27999. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28000. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28001. this._vertexBuffers["options"] = options;
  28002. this._vertexBuffers["cellInfo"] = cellInfo;
  28003. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28004. // Effects
  28005. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28006. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28007. }
  28008. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28009. set: function (callback) {
  28010. if (this._onDisposeObserver) {
  28011. this.onDisposeObservable.remove(this._onDisposeObserver);
  28012. }
  28013. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28014. },
  28015. enumerable: true,
  28016. configurable: true
  28017. });
  28018. Object.defineProperty(SpriteManager.prototype, "texture", {
  28019. get: function () {
  28020. return this._spriteTexture;
  28021. },
  28022. set: function (value) {
  28023. this._spriteTexture = value;
  28024. },
  28025. enumerable: true,
  28026. configurable: true
  28027. });
  28028. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28029. var arrayOffset = index * 16;
  28030. if (offsetX === 0)
  28031. offsetX = this._epsilon;
  28032. else if (offsetX === 1)
  28033. offsetX = 1 - this._epsilon;
  28034. if (offsetY === 0)
  28035. offsetY = this._epsilon;
  28036. else if (offsetY === 1)
  28037. offsetY = 1 - this._epsilon;
  28038. this._vertexData[arrayOffset] = sprite.position.x;
  28039. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28040. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28041. this._vertexData[arrayOffset + 3] = sprite.angle;
  28042. this._vertexData[arrayOffset + 4] = sprite.width;
  28043. this._vertexData[arrayOffset + 5] = sprite.height;
  28044. this._vertexData[arrayOffset + 6] = offsetX;
  28045. this._vertexData[arrayOffset + 7] = offsetY;
  28046. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28047. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28048. var offset = (sprite.cellIndex / rowSize) >> 0;
  28049. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28050. this._vertexData[arrayOffset + 11] = offset;
  28051. // Color
  28052. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28053. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28054. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28055. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28056. };
  28057. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28058. var count = Math.min(this._capacity, this.sprites.length);
  28059. var min = BABYLON.Vector3.Zero();
  28060. var max = BABYLON.Vector3.Zero();
  28061. var distance = Number.MAX_VALUE;
  28062. var currentSprite;
  28063. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28064. var cameraView = camera.getViewMatrix();
  28065. for (var index = 0; index < count; index++) {
  28066. var sprite = this.sprites[index];
  28067. if (!sprite) {
  28068. continue;
  28069. }
  28070. if (predicate) {
  28071. if (!predicate(sprite)) {
  28072. continue;
  28073. }
  28074. }
  28075. else if (!sprite.isPickable) {
  28076. continue;
  28077. }
  28078. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28079. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28080. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28081. if (ray.intersectsBoxMinMax(min, max)) {
  28082. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28083. if (distance > currentDistance) {
  28084. distance = currentDistance;
  28085. currentSprite = sprite;
  28086. if (fastCheck) {
  28087. break;
  28088. }
  28089. }
  28090. }
  28091. }
  28092. if (currentSprite) {
  28093. var result = new BABYLON.PickingInfo();
  28094. result.hit = true;
  28095. result.pickedSprite = currentSprite;
  28096. result.distance = distance;
  28097. return result;
  28098. }
  28099. return null;
  28100. };
  28101. SpriteManager.prototype.render = function () {
  28102. // Check
  28103. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28104. return;
  28105. var engine = this._scene.getEngine();
  28106. var baseSize = this._spriteTexture.getBaseSize();
  28107. // Sprites
  28108. var deltaTime = engine.getDeltaTime();
  28109. var max = Math.min(this._capacity, this.sprites.length);
  28110. var rowSize = baseSize.width / this.cellWidth;
  28111. var offset = 0;
  28112. for (var index = 0; index < max; index++) {
  28113. var sprite = this.sprites[index];
  28114. if (!sprite) {
  28115. continue;
  28116. }
  28117. sprite._animate(deltaTime);
  28118. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28119. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28120. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28121. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28122. }
  28123. this._buffer.update(this._vertexData);
  28124. // Render
  28125. var effect = this._effectBase;
  28126. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28127. effect = this._effectFog;
  28128. }
  28129. engine.enableEffect(effect);
  28130. var viewMatrix = this._scene.getViewMatrix();
  28131. effect.setTexture("diffuseSampler", this._spriteTexture);
  28132. effect.setMatrix("view", viewMatrix);
  28133. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28134. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28135. // Fog
  28136. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28137. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28138. effect.setColor3("vFogColor", this._scene.fogColor);
  28139. }
  28140. // VBOs
  28141. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28142. // Draw order
  28143. engine.setDepthFunctionToLessOrEqual();
  28144. effect.setBool("alphaTest", true);
  28145. engine.setColorWrite(false);
  28146. engine.draw(true, 0, max * 6);
  28147. engine.setColorWrite(true);
  28148. effect.setBool("alphaTest", false);
  28149. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28150. engine.draw(true, 0, max * 6);
  28151. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28152. };
  28153. SpriteManager.prototype.dispose = function () {
  28154. if (this._buffer) {
  28155. this._buffer.dispose();
  28156. this._buffer = null;
  28157. }
  28158. if (this._indexBuffer) {
  28159. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28160. this._indexBuffer = null;
  28161. }
  28162. if (this._spriteTexture) {
  28163. this._spriteTexture.dispose();
  28164. this._spriteTexture = null;
  28165. }
  28166. // Remove from scene
  28167. var index = this._scene.spriteManagers.indexOf(this);
  28168. this._scene.spriteManagers.splice(index, 1);
  28169. // Callback
  28170. this.onDisposeObservable.notifyObservers(this);
  28171. this.onDisposeObservable.clear();
  28172. };
  28173. return SpriteManager;
  28174. }());
  28175. BABYLON.SpriteManager = SpriteManager;
  28176. })(BABYLON || (BABYLON = {}));
  28177. //# sourceMappingURL=babylon.spriteManager.js.map
  28178. var BABYLON;
  28179. (function (BABYLON) {
  28180. var Sprite = (function () {
  28181. function Sprite(name, manager) {
  28182. this.name = name;
  28183. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28184. this.width = 1.0;
  28185. this.height = 1.0;
  28186. this.angle = 0;
  28187. this.cellIndex = 0;
  28188. this.invertU = 0;
  28189. this.invertV = 0;
  28190. this.animations = new Array();
  28191. this.isPickable = false;
  28192. this._animationStarted = false;
  28193. this._loopAnimation = false;
  28194. this._fromIndex = 0;
  28195. this._toIndex = 0;
  28196. this._delay = 0;
  28197. this._direction = 1;
  28198. this._frameCount = 0;
  28199. this._time = 0;
  28200. this._manager = manager;
  28201. this._manager.sprites.push(this);
  28202. this.position = BABYLON.Vector3.Zero();
  28203. }
  28204. Object.defineProperty(Sprite.prototype, "size", {
  28205. get: function () {
  28206. return this.width;
  28207. },
  28208. set: function (value) {
  28209. this.width = value;
  28210. this.height = value;
  28211. },
  28212. enumerable: true,
  28213. configurable: true
  28214. });
  28215. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  28216. this._fromIndex = from;
  28217. this._toIndex = to;
  28218. this._loopAnimation = loop;
  28219. this._delay = delay;
  28220. this._animationStarted = true;
  28221. this._direction = from < to ? 1 : -1;
  28222. this.cellIndex = from;
  28223. this._time = 0;
  28224. this._onAnimationEnd = onAnimationEnd;
  28225. };
  28226. Sprite.prototype.stopAnimation = function () {
  28227. this._animationStarted = false;
  28228. };
  28229. Sprite.prototype._animate = function (deltaTime) {
  28230. if (!this._animationStarted)
  28231. return;
  28232. this._time += deltaTime;
  28233. if (this._time > this._delay) {
  28234. this._time = this._time % this._delay;
  28235. this.cellIndex += this._direction;
  28236. if (this.cellIndex === this._toIndex) {
  28237. if (this._loopAnimation) {
  28238. this.cellIndex = this._fromIndex;
  28239. }
  28240. else {
  28241. this._animationStarted = false;
  28242. if (this._onAnimationEnd) {
  28243. this._onAnimationEnd();
  28244. }
  28245. if (this.disposeWhenFinishedAnimating) {
  28246. this.dispose();
  28247. }
  28248. }
  28249. }
  28250. }
  28251. };
  28252. Sprite.prototype.dispose = function () {
  28253. for (var i = 0; i < this._manager.sprites.length; i++) {
  28254. if (this._manager.sprites[i] == this) {
  28255. this._manager.sprites.splice(i, 1);
  28256. }
  28257. }
  28258. };
  28259. return Sprite;
  28260. }());
  28261. BABYLON.Sprite = Sprite;
  28262. })(BABYLON || (BABYLON = {}));
  28263. //# sourceMappingURL=babylon.sprite.js.map
  28264. var BABYLON;
  28265. (function (BABYLON) {
  28266. var Layer = (function () {
  28267. function Layer(name, imgUrl, scene, isBackground, color) {
  28268. this.name = name;
  28269. this.scale = new BABYLON.Vector2(1, 1);
  28270. this.offset = new BABYLON.Vector2(0, 0);
  28271. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  28272. this._vertexBuffers = {};
  28273. // Events
  28274. /**
  28275. * An event triggered when the layer is disposed.
  28276. * @type {BABYLON.Observable}
  28277. */
  28278. this.onDisposeObservable = new BABYLON.Observable();
  28279. /**
  28280. * An event triggered before rendering the scene
  28281. * @type {BABYLON.Observable}
  28282. */
  28283. this.onBeforeRenderObservable = new BABYLON.Observable();
  28284. /**
  28285. * An event triggered after rendering the scene
  28286. * @type {BABYLON.Observable}
  28287. */
  28288. this.onAfterRenderObservable = new BABYLON.Observable();
  28289. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  28290. this.isBackground = isBackground === undefined ? true : isBackground;
  28291. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  28292. this._scene = scene;
  28293. this._scene.layers.push(this);
  28294. var engine = scene.getEngine();
  28295. // VBO
  28296. var vertices = [];
  28297. vertices.push(1, 1);
  28298. vertices.push(-1, 1);
  28299. vertices.push(-1, -1);
  28300. vertices.push(1, -1);
  28301. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28302. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  28303. // Indices
  28304. var indices = [];
  28305. indices.push(0);
  28306. indices.push(1);
  28307. indices.push(2);
  28308. indices.push(0);
  28309. indices.push(2);
  28310. indices.push(3);
  28311. this._indexBuffer = engine.createIndexBuffer(indices);
  28312. // Effects
  28313. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  28314. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  28315. }
  28316. Object.defineProperty(Layer.prototype, "onDispose", {
  28317. set: function (callback) {
  28318. if (this._onDisposeObserver) {
  28319. this.onDisposeObservable.remove(this._onDisposeObserver);
  28320. }
  28321. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28322. },
  28323. enumerable: true,
  28324. configurable: true
  28325. });
  28326. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  28327. set: function (callback) {
  28328. if (this._onBeforeRenderObserver) {
  28329. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28330. }
  28331. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28332. },
  28333. enumerable: true,
  28334. configurable: true
  28335. });
  28336. Object.defineProperty(Layer.prototype, "onAfterRender", {
  28337. set: function (callback) {
  28338. if (this._onAfterRenderObserver) {
  28339. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28340. }
  28341. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28342. },
  28343. enumerable: true,
  28344. configurable: true
  28345. });
  28346. Layer.prototype.render = function () {
  28347. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  28348. // Check
  28349. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  28350. return;
  28351. var engine = this._scene.getEngine();
  28352. this.onBeforeRenderObservable.notifyObservers(this);
  28353. // Render
  28354. engine.enableEffect(currentEffect);
  28355. engine.setState(false);
  28356. // Texture
  28357. currentEffect.setTexture("textureSampler", this.texture);
  28358. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  28359. // Color
  28360. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  28361. // Scale / offset
  28362. currentEffect.setVector2("offset", this.offset);
  28363. currentEffect.setVector2("scale", this.scale);
  28364. // VBOs
  28365. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  28366. // Draw order
  28367. if (!this.alphaTest) {
  28368. engine.setAlphaMode(this.alphaBlendingMode);
  28369. engine.draw(true, 0, 6);
  28370. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28371. }
  28372. else {
  28373. engine.draw(true, 0, 6);
  28374. }
  28375. this.onAfterRenderObservable.notifyObservers(this);
  28376. };
  28377. Layer.prototype.dispose = function () {
  28378. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28379. if (vertexBuffer) {
  28380. vertexBuffer.dispose();
  28381. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28382. }
  28383. if (this._indexBuffer) {
  28384. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28385. this._indexBuffer = null;
  28386. }
  28387. if (this.texture) {
  28388. this.texture.dispose();
  28389. this.texture = null;
  28390. }
  28391. // Remove from scene
  28392. var index = this._scene.layers.indexOf(this);
  28393. this._scene.layers.splice(index, 1);
  28394. // Callback
  28395. this.onDisposeObservable.notifyObservers(this);
  28396. this.onDisposeObservable.clear();
  28397. this.onAfterRenderObservable.clear();
  28398. this.onBeforeRenderObservable.clear();
  28399. };
  28400. return Layer;
  28401. }());
  28402. BABYLON.Layer = Layer;
  28403. })(BABYLON || (BABYLON = {}));
  28404. //# sourceMappingURL=babylon.layer.js.map
  28405. var BABYLON;
  28406. (function (BABYLON) {
  28407. var Particle = (function () {
  28408. function Particle() {
  28409. this.position = BABYLON.Vector3.Zero();
  28410. this.direction = BABYLON.Vector3.Zero();
  28411. this.color = new BABYLON.Color4(0, 0, 0, 0);
  28412. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  28413. this.lifeTime = 1.0;
  28414. this.age = 0;
  28415. this.size = 0;
  28416. this.angle = 0;
  28417. this.angularSpeed = 0;
  28418. }
  28419. Particle.prototype.copyTo = function (other) {
  28420. other.position.copyFrom(this.position);
  28421. other.direction.copyFrom(this.direction);
  28422. other.color.copyFrom(this.color);
  28423. other.colorStep.copyFrom(this.colorStep);
  28424. other.lifeTime = this.lifeTime;
  28425. other.age = this.age;
  28426. other.size = this.size;
  28427. other.angle = this.angle;
  28428. other.angularSpeed = this.angularSpeed;
  28429. };
  28430. return Particle;
  28431. }());
  28432. BABYLON.Particle = Particle;
  28433. })(BABYLON || (BABYLON = {}));
  28434. //# sourceMappingURL=babylon.particle.js.map
  28435. var BABYLON;
  28436. (function (BABYLON) {
  28437. var randomNumber = function (min, max) {
  28438. if (min === max) {
  28439. return (min);
  28440. }
  28441. var random = Math.random();
  28442. return ((random * (max - min)) + min);
  28443. };
  28444. var ParticleSystem = (function () {
  28445. function ParticleSystem(name, capacity, scene, customEffect) {
  28446. var _this = this;
  28447. this.name = name;
  28448. // Members
  28449. this.animations = [];
  28450. this.renderingGroupId = 0;
  28451. this.emitter = null;
  28452. this.emitRate = 10;
  28453. this.manualEmitCount = -1;
  28454. this.updateSpeed = 0.01;
  28455. this.targetStopDuration = 0;
  28456. this.disposeOnStop = false;
  28457. this.minEmitPower = 1;
  28458. this.maxEmitPower = 1;
  28459. this.minLifeTime = 1;
  28460. this.maxLifeTime = 1;
  28461. this.minSize = 1;
  28462. this.maxSize = 1;
  28463. this.minAngularSpeed = 0;
  28464. this.maxAngularSpeed = 0;
  28465. this.layerMask = 0x0FFFFFFF;
  28466. /**
  28467. * An event triggered when the system is disposed.
  28468. * @type {BABYLON.Observable}
  28469. */
  28470. this.onDisposeObservable = new BABYLON.Observable();
  28471. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  28472. this.forceDepthWrite = false;
  28473. this.gravity = BABYLON.Vector3.Zero();
  28474. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  28475. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  28476. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  28477. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  28478. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28479. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28480. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  28481. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28482. this.particles = new Array();
  28483. this._stockParticles = new Array();
  28484. this._newPartsExcess = 0;
  28485. this._vertexBuffers = {};
  28486. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  28487. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  28488. this._scaledDirection = BABYLON.Vector3.Zero();
  28489. this._scaledGravity = BABYLON.Vector3.Zero();
  28490. this._currentRenderId = -1;
  28491. this._started = false;
  28492. this._stopped = false;
  28493. this._actualFrame = 0;
  28494. this.id = name;
  28495. this._capacity = capacity;
  28496. this._scene = scene;
  28497. this._customEffect = customEffect;
  28498. scene.particleSystems.push(this);
  28499. var indices = [];
  28500. var index = 0;
  28501. for (var count = 0; count < capacity; count++) {
  28502. indices.push(index);
  28503. indices.push(index + 1);
  28504. indices.push(index + 2);
  28505. indices.push(index);
  28506. indices.push(index + 2);
  28507. indices.push(index + 3);
  28508. index += 4;
  28509. }
  28510. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28511. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  28512. this._vertexData = new Float32Array(capacity * 11 * 4);
  28513. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  28514. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  28515. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  28516. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  28517. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28518. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28519. this._vertexBuffers["options"] = options;
  28520. // Default behaviors
  28521. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  28522. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  28523. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  28524. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  28525. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  28526. };
  28527. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  28528. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  28529. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  28530. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  28531. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  28532. };
  28533. this.updateFunction = function (particles) {
  28534. for (var index = 0; index < particles.length; index++) {
  28535. var particle = particles[index];
  28536. particle.age += _this._scaledUpdateSpeed;
  28537. if (particle.age >= particle.lifeTime) {
  28538. _this.recycleParticle(particle);
  28539. index--;
  28540. continue;
  28541. }
  28542. else {
  28543. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28544. particle.color.addInPlace(_this._scaledColorStep);
  28545. if (particle.color.a < 0)
  28546. particle.color.a = 0;
  28547. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28548. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28549. particle.position.addInPlace(_this._scaledDirection);
  28550. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28551. particle.direction.addInPlace(_this._scaledGravity);
  28552. }
  28553. }
  28554. };
  28555. }
  28556. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28557. set: function (callback) {
  28558. if (this._onDisposeObserver) {
  28559. this.onDisposeObservable.remove(this._onDisposeObserver);
  28560. }
  28561. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28562. },
  28563. enumerable: true,
  28564. configurable: true
  28565. });
  28566. ParticleSystem.prototype.recycleParticle = function (particle) {
  28567. var lastParticle = this.particles.pop();
  28568. if (lastParticle !== particle) {
  28569. lastParticle.copyTo(particle);
  28570. this._stockParticles.push(lastParticle);
  28571. }
  28572. };
  28573. ParticleSystem.prototype.getCapacity = function () {
  28574. return this._capacity;
  28575. };
  28576. ParticleSystem.prototype.isAlive = function () {
  28577. return this._alive;
  28578. };
  28579. ParticleSystem.prototype.isStarted = function () {
  28580. return this._started;
  28581. };
  28582. ParticleSystem.prototype.start = function () {
  28583. this._started = true;
  28584. this._stopped = false;
  28585. this._actualFrame = 0;
  28586. };
  28587. ParticleSystem.prototype.stop = function () {
  28588. this._stopped = true;
  28589. };
  28590. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28591. var offset = index * 11;
  28592. this._vertexData[offset] = particle.position.x;
  28593. this._vertexData[offset + 1] = particle.position.y;
  28594. this._vertexData[offset + 2] = particle.position.z;
  28595. this._vertexData[offset + 3] = particle.color.r;
  28596. this._vertexData[offset + 4] = particle.color.g;
  28597. this._vertexData[offset + 5] = particle.color.b;
  28598. this._vertexData[offset + 6] = particle.color.a;
  28599. this._vertexData[offset + 7] = particle.angle;
  28600. this._vertexData[offset + 8] = particle.size;
  28601. this._vertexData[offset + 9] = offsetX;
  28602. this._vertexData[offset + 10] = offsetY;
  28603. };
  28604. ParticleSystem.prototype._update = function (newParticles) {
  28605. // Update current
  28606. this._alive = this.particles.length > 0;
  28607. this.updateFunction(this.particles);
  28608. // Add new ones
  28609. var worldMatrix;
  28610. if (this.emitter.position) {
  28611. worldMatrix = this.emitter.getWorldMatrix();
  28612. }
  28613. else {
  28614. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28615. }
  28616. var particle;
  28617. for (var index = 0; index < newParticles; index++) {
  28618. if (this.particles.length === this._capacity) {
  28619. break;
  28620. }
  28621. if (this._stockParticles.length !== 0) {
  28622. particle = this._stockParticles.pop();
  28623. particle.age = 0;
  28624. }
  28625. else {
  28626. particle = new BABYLON.Particle();
  28627. }
  28628. this.particles.push(particle);
  28629. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28630. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28631. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28632. particle.size = randomNumber(this.minSize, this.maxSize);
  28633. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28634. this.startPositionFunction(worldMatrix, particle.position, particle);
  28635. var step = randomNumber(0, 1.0);
  28636. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28637. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28638. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28639. }
  28640. };
  28641. ParticleSystem.prototype._getEffect = function () {
  28642. if (this._customEffect) {
  28643. return this._customEffect;
  28644. }
  28645. ;
  28646. var defines = [];
  28647. if (this._scene.clipPlane) {
  28648. defines.push("#define CLIPPLANE");
  28649. }
  28650. // Effect
  28651. var join = defines.join("\n");
  28652. if (this._cachedDefines !== join) {
  28653. this._cachedDefines = join;
  28654. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28655. }
  28656. return this._effect;
  28657. };
  28658. ParticleSystem.prototype.animate = function () {
  28659. if (!this._started)
  28660. return;
  28661. var effect = this._getEffect();
  28662. // Check
  28663. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28664. return;
  28665. if (this._currentRenderId === this._scene.getRenderId()) {
  28666. return;
  28667. }
  28668. this._currentRenderId = this._scene.getRenderId();
  28669. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28670. // determine the number of particles we need to create
  28671. var newParticles;
  28672. if (this.manualEmitCount > -1) {
  28673. newParticles = this.manualEmitCount;
  28674. this._newPartsExcess = 0;
  28675. this.manualEmitCount = 0;
  28676. }
  28677. else {
  28678. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28679. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28680. }
  28681. if (this._newPartsExcess > 1.0) {
  28682. newParticles += this._newPartsExcess >> 0;
  28683. this._newPartsExcess -= this._newPartsExcess >> 0;
  28684. }
  28685. this._alive = false;
  28686. if (!this._stopped) {
  28687. this._actualFrame += this._scaledUpdateSpeed;
  28688. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28689. this.stop();
  28690. }
  28691. else {
  28692. newParticles = 0;
  28693. }
  28694. this._update(newParticles);
  28695. // Stopped?
  28696. if (this._stopped) {
  28697. if (!this._alive) {
  28698. this._started = false;
  28699. if (this.disposeOnStop) {
  28700. this._scene._toBeDisposed.push(this);
  28701. }
  28702. }
  28703. }
  28704. // Update VBO
  28705. var offset = 0;
  28706. for (var index = 0; index < this.particles.length; index++) {
  28707. var particle = this.particles[index];
  28708. this._appendParticleVertex(offset++, particle, 0, 0);
  28709. this._appendParticleVertex(offset++, particle, 1, 0);
  28710. this._appendParticleVertex(offset++, particle, 1, 1);
  28711. this._appendParticleVertex(offset++, particle, 0, 1);
  28712. }
  28713. this._vertexBuffer.update(this._vertexData);
  28714. };
  28715. ParticleSystem.prototype.render = function () {
  28716. var effect = this._getEffect();
  28717. // Check
  28718. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28719. return 0;
  28720. var engine = this._scene.getEngine();
  28721. // Render
  28722. engine.enableEffect(effect);
  28723. engine.setState(false);
  28724. var viewMatrix = this._scene.getViewMatrix();
  28725. effect.setTexture("diffuseSampler", this.particleTexture);
  28726. effect.setMatrix("view", viewMatrix);
  28727. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28728. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28729. if (this._scene.clipPlane) {
  28730. var clipPlane = this._scene.clipPlane;
  28731. var invView = viewMatrix.clone();
  28732. invView.invert();
  28733. effect.setMatrix("invView", invView);
  28734. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28735. }
  28736. // VBOs
  28737. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28738. // Draw order
  28739. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28740. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28741. }
  28742. else {
  28743. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28744. }
  28745. if (this.forceDepthWrite) {
  28746. engine.setDepthWrite(true);
  28747. }
  28748. engine.draw(true, 0, this.particles.length * 6);
  28749. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28750. return this.particles.length;
  28751. };
  28752. ParticleSystem.prototype.dispose = function () {
  28753. if (this._vertexBuffer) {
  28754. this._vertexBuffer.dispose();
  28755. this._vertexBuffer = null;
  28756. }
  28757. if (this._indexBuffer) {
  28758. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28759. this._indexBuffer = null;
  28760. }
  28761. if (this.particleTexture) {
  28762. this.particleTexture.dispose();
  28763. this.particleTexture = null;
  28764. }
  28765. // Remove from scene
  28766. var index = this._scene.particleSystems.indexOf(this);
  28767. this._scene.particleSystems.splice(index, 1);
  28768. // Callback
  28769. this.onDisposeObservable.notifyObservers(this);
  28770. this.onDisposeObservable.clear();
  28771. };
  28772. // Clone
  28773. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28774. var result = new ParticleSystem(name, this._capacity, this._scene);
  28775. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28776. if (newEmitter === undefined) {
  28777. newEmitter = this.emitter;
  28778. }
  28779. result.emitter = newEmitter;
  28780. if (this.particleTexture) {
  28781. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28782. }
  28783. result.start();
  28784. return result;
  28785. };
  28786. ParticleSystem.prototype.serialize = function () {
  28787. var serializationObject = {};
  28788. serializationObject.name = this.name;
  28789. serializationObject.id = this.id;
  28790. // Emitter
  28791. if (this.emitter.position) {
  28792. serializationObject.emitterId = this.emitter.id;
  28793. }
  28794. else {
  28795. serializationObject.emitter = this.emitter.asArray();
  28796. }
  28797. serializationObject.capacity = this.getCapacity();
  28798. if (this.particleTexture) {
  28799. serializationObject.textureName = this.particleTexture.name;
  28800. }
  28801. // Animations
  28802. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28803. // Particle system
  28804. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28805. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28806. serializationObject.minSize = this.minSize;
  28807. serializationObject.maxSize = this.maxSize;
  28808. serializationObject.minEmitPower = this.minEmitPower;
  28809. serializationObject.maxEmitPower = this.maxEmitPower;
  28810. serializationObject.minLifeTime = this.minLifeTime;
  28811. serializationObject.maxLifeTime = this.maxLifeTime;
  28812. serializationObject.emitRate = this.emitRate;
  28813. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28814. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28815. serializationObject.gravity = this.gravity.asArray();
  28816. serializationObject.direction1 = this.direction1.asArray();
  28817. serializationObject.direction2 = this.direction2.asArray();
  28818. serializationObject.color1 = this.color1.asArray();
  28819. serializationObject.color2 = this.color2.asArray();
  28820. serializationObject.colorDead = this.colorDead.asArray();
  28821. serializationObject.updateSpeed = this.updateSpeed;
  28822. serializationObject.targetStopDuration = this.targetStopDuration;
  28823. serializationObject.textureMask = this.textureMask.asArray();
  28824. serializationObject.blendMode = this.blendMode;
  28825. return serializationObject;
  28826. };
  28827. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28828. var name = parsedParticleSystem.name;
  28829. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28830. if (parsedParticleSystem.id) {
  28831. particleSystem.id = parsedParticleSystem.id;
  28832. }
  28833. // Texture
  28834. if (parsedParticleSystem.textureName) {
  28835. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28836. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28837. }
  28838. // Emitter
  28839. if (parsedParticleSystem.emitterId) {
  28840. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28841. }
  28842. else {
  28843. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28844. }
  28845. // Animations
  28846. if (parsedParticleSystem.animations) {
  28847. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28848. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28849. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28850. }
  28851. }
  28852. if (parsedParticleSystem.autoAnimate) {
  28853. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28854. }
  28855. // Particle system
  28856. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28857. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28858. particleSystem.minSize = parsedParticleSystem.minSize;
  28859. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28860. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28861. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28862. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28863. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28864. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28865. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28866. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28867. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28868. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28869. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28870. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28871. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28872. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28873. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28874. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28875. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28876. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28877. if (!parsedParticleSystem.preventAutoStart) {
  28878. particleSystem.start();
  28879. }
  28880. return particleSystem;
  28881. };
  28882. // Statics
  28883. ParticleSystem.BLENDMODE_ONEONE = 0;
  28884. ParticleSystem.BLENDMODE_STANDARD = 1;
  28885. return ParticleSystem;
  28886. }());
  28887. BABYLON.ParticleSystem = ParticleSystem;
  28888. })(BABYLON || (BABYLON = {}));
  28889. //# sourceMappingURL=babylon.particleSystem.js.map
  28890. var BABYLON;
  28891. (function (BABYLON) {
  28892. var AnimationRange = (function () {
  28893. function AnimationRange(name, from, to) {
  28894. this.name = name;
  28895. this.from = from;
  28896. this.to = to;
  28897. }
  28898. AnimationRange.prototype.clone = function () {
  28899. return new AnimationRange(this.name, this.from, this.to);
  28900. };
  28901. return AnimationRange;
  28902. }());
  28903. BABYLON.AnimationRange = AnimationRange;
  28904. /**
  28905. * Composed of a frame, and an action function
  28906. */
  28907. var AnimationEvent = (function () {
  28908. function AnimationEvent(frame, action, onlyOnce) {
  28909. this.frame = frame;
  28910. this.action = action;
  28911. this.onlyOnce = onlyOnce;
  28912. this.isDone = false;
  28913. }
  28914. return AnimationEvent;
  28915. }());
  28916. BABYLON.AnimationEvent = AnimationEvent;
  28917. var PathCursor = (function () {
  28918. function PathCursor(path) {
  28919. this.path = path;
  28920. this._onchange = new Array();
  28921. this.value = 0;
  28922. this.animations = new Array();
  28923. }
  28924. PathCursor.prototype.getPoint = function () {
  28925. var point = this.path.getPointAtLengthPosition(this.value);
  28926. return new BABYLON.Vector3(point.x, 0, point.y);
  28927. };
  28928. PathCursor.prototype.moveAhead = function (step) {
  28929. if (step === void 0) { step = 0.002; }
  28930. this.move(step);
  28931. return this;
  28932. };
  28933. PathCursor.prototype.moveBack = function (step) {
  28934. if (step === void 0) { step = 0.002; }
  28935. this.move(-step);
  28936. return this;
  28937. };
  28938. PathCursor.prototype.move = function (step) {
  28939. if (Math.abs(step) > 1) {
  28940. throw "step size should be less than 1.";
  28941. }
  28942. this.value += step;
  28943. this.ensureLimits();
  28944. this.raiseOnChange();
  28945. return this;
  28946. };
  28947. PathCursor.prototype.ensureLimits = function () {
  28948. while (this.value > 1) {
  28949. this.value -= 1;
  28950. }
  28951. while (this.value < 0) {
  28952. this.value += 1;
  28953. }
  28954. return this;
  28955. };
  28956. // used by animation engine
  28957. PathCursor.prototype.markAsDirty = function (propertyName) {
  28958. this.ensureLimits();
  28959. this.raiseOnChange();
  28960. return this;
  28961. };
  28962. PathCursor.prototype.raiseOnChange = function () {
  28963. var _this = this;
  28964. this._onchange.forEach(function (f) { return f(_this); });
  28965. return this;
  28966. };
  28967. PathCursor.prototype.onchange = function (f) {
  28968. this._onchange.push(f);
  28969. return this;
  28970. };
  28971. return PathCursor;
  28972. }());
  28973. BABYLON.PathCursor = PathCursor;
  28974. var Animation = (function () {
  28975. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28976. this.name = name;
  28977. this.targetProperty = targetProperty;
  28978. this.framePerSecond = framePerSecond;
  28979. this.dataType = dataType;
  28980. this.loopMode = loopMode;
  28981. this.enableBlending = enableBlending;
  28982. this._offsetsCache = {};
  28983. this._highLimitsCache = {};
  28984. this._stopped = false;
  28985. this._blendingFactor = 0;
  28986. // The set of event that will be linked to this animation
  28987. this._events = new Array();
  28988. this.allowMatricesInterpolation = false;
  28989. this.blendingSpeed = 0.01;
  28990. this._ranges = {};
  28991. this.targetPropertyPath = targetProperty.split(".");
  28992. this.dataType = dataType;
  28993. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28994. }
  28995. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28996. var dataType = undefined;
  28997. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28998. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28999. }
  29000. else if (from instanceof BABYLON.Quaternion) {
  29001. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29002. }
  29003. else if (from instanceof BABYLON.Vector3) {
  29004. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29005. }
  29006. else if (from instanceof BABYLON.Vector2) {
  29007. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29008. }
  29009. else if (from instanceof BABYLON.Color3) {
  29010. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29011. }
  29012. else if (from instanceof BABYLON.Size) {
  29013. dataType = Animation.ANIMATIONTYPE_SIZE;
  29014. }
  29015. if (dataType == undefined) {
  29016. return null;
  29017. }
  29018. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29019. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29020. animation.setKeys(keys);
  29021. if (easingFunction !== undefined) {
  29022. animation.setEasingFunction(easingFunction);
  29023. }
  29024. return animation;
  29025. };
  29026. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29027. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29028. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29029. };
  29030. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29031. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29032. node.animations.push(animation);
  29033. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29034. };
  29035. // Methods
  29036. /**
  29037. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29038. */
  29039. Animation.prototype.toString = function (fullDetails) {
  29040. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29041. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29042. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29043. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29044. if (fullDetails) {
  29045. ret += ", Ranges: {";
  29046. var first = true;
  29047. for (var name in this._ranges) {
  29048. if (first) {
  29049. ret += ", ";
  29050. first = false;
  29051. }
  29052. ret += name;
  29053. }
  29054. ret += "}";
  29055. }
  29056. return ret;
  29057. };
  29058. /**
  29059. * Add an event to this animation.
  29060. */
  29061. Animation.prototype.addEvent = function (event) {
  29062. this._events.push(event);
  29063. };
  29064. /**
  29065. * Remove all events found at the given frame
  29066. * @param frame
  29067. */
  29068. Animation.prototype.removeEvents = function (frame) {
  29069. for (var index = 0; index < this._events.length; index++) {
  29070. if (this._events[index].frame === frame) {
  29071. this._events.splice(index, 1);
  29072. index--;
  29073. }
  29074. }
  29075. };
  29076. Animation.prototype.createRange = function (name, from, to) {
  29077. // check name not already in use; could happen for bones after serialized
  29078. if (!this._ranges[name]) {
  29079. this._ranges[name] = new AnimationRange(name, from, to);
  29080. }
  29081. };
  29082. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29083. if (deleteFrames === void 0) { deleteFrames = true; }
  29084. if (this._ranges[name]) {
  29085. if (deleteFrames) {
  29086. var from = this._ranges[name].from;
  29087. var to = this._ranges[name].to;
  29088. // this loop MUST go high to low for multiple splices to work
  29089. for (var key = this._keys.length - 1; key >= 0; key--) {
  29090. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29091. this._keys.splice(key, 1);
  29092. }
  29093. }
  29094. }
  29095. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29096. }
  29097. };
  29098. Animation.prototype.getRange = function (name) {
  29099. return this._ranges[name];
  29100. };
  29101. Animation.prototype.reset = function () {
  29102. this._offsetsCache = {};
  29103. this._highLimitsCache = {};
  29104. this.currentFrame = 0;
  29105. this._blendingFactor = 0;
  29106. this._originalBlendValue = null;
  29107. };
  29108. Animation.prototype.isStopped = function () {
  29109. return this._stopped;
  29110. };
  29111. Animation.prototype.getKeys = function () {
  29112. return this._keys;
  29113. };
  29114. Animation.prototype.getHighestFrame = function () {
  29115. var ret = 0;
  29116. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29117. if (ret < this._keys[key].frame) {
  29118. ret = this._keys[key].frame;
  29119. }
  29120. }
  29121. return ret;
  29122. };
  29123. Animation.prototype.getEasingFunction = function () {
  29124. return this._easingFunction;
  29125. };
  29126. Animation.prototype.setEasingFunction = function (easingFunction) {
  29127. this._easingFunction = easingFunction;
  29128. };
  29129. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29130. return startValue + (endValue - startValue) * gradient;
  29131. };
  29132. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29133. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29134. };
  29135. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29136. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29137. };
  29138. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29139. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29140. };
  29141. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29142. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29143. };
  29144. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29145. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29146. };
  29147. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29148. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29149. };
  29150. Animation.prototype.clone = function () {
  29151. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29152. if (this._keys) {
  29153. clone.setKeys(this._keys);
  29154. }
  29155. if (this._ranges) {
  29156. clone._ranges = {};
  29157. for (var name in this._ranges) {
  29158. clone._ranges[name] = this._ranges[name].clone();
  29159. }
  29160. }
  29161. return clone;
  29162. };
  29163. Animation.prototype.setKeys = function (values) {
  29164. this._keys = values.slice(0);
  29165. this._offsetsCache = {};
  29166. this._highLimitsCache = {};
  29167. };
  29168. Animation.prototype._getKeyValue = function (value) {
  29169. if (typeof value === "function") {
  29170. return value();
  29171. }
  29172. return value;
  29173. };
  29174. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  29175. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  29176. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  29177. }
  29178. this.currentFrame = currentFrame;
  29179. // Try to get a hash to find the right key
  29180. 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));
  29181. if (this._keys[startKey].frame >= currentFrame) {
  29182. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  29183. startKey--;
  29184. }
  29185. }
  29186. for (var key = startKey; key < this._keys.length; key++) {
  29187. if (this._keys[key + 1].frame >= currentFrame) {
  29188. var startValue = this._getKeyValue(this._keys[key].value);
  29189. var endValue = this._getKeyValue(this._keys[key + 1].value);
  29190. // gradient : percent of currentFrame between the frame inf and the frame sup
  29191. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  29192. // check for easingFunction and correction of gradient
  29193. if (this._easingFunction != null) {
  29194. gradient = this._easingFunction.ease(gradient);
  29195. }
  29196. switch (this.dataType) {
  29197. // Float
  29198. case Animation.ANIMATIONTYPE_FLOAT:
  29199. switch (loopMode) {
  29200. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29201. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29202. return this.floatInterpolateFunction(startValue, endValue, gradient);
  29203. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29204. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  29205. }
  29206. break;
  29207. // Quaternion
  29208. case Animation.ANIMATIONTYPE_QUATERNION:
  29209. var quaternion = null;
  29210. switch (loopMode) {
  29211. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29212. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29213. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  29214. break;
  29215. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29216. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29217. break;
  29218. }
  29219. return quaternion;
  29220. // Vector3
  29221. case Animation.ANIMATIONTYPE_VECTOR3:
  29222. switch (loopMode) {
  29223. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29224. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29225. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  29226. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29227. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29228. }
  29229. // Vector2
  29230. case Animation.ANIMATIONTYPE_VECTOR2:
  29231. switch (loopMode) {
  29232. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29233. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29234. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  29235. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29236. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29237. }
  29238. // Size
  29239. case Animation.ANIMATIONTYPE_SIZE:
  29240. switch (loopMode) {
  29241. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29242. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29243. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  29244. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29245. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29246. }
  29247. // Color3
  29248. case Animation.ANIMATIONTYPE_COLOR3:
  29249. switch (loopMode) {
  29250. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29251. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29252. return this.color3InterpolateFunction(startValue, endValue, gradient);
  29253. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29254. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29255. }
  29256. // Matrix
  29257. case Animation.ANIMATIONTYPE_MATRIX:
  29258. switch (loopMode) {
  29259. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29260. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29261. if (this.allowMatricesInterpolation) {
  29262. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  29263. }
  29264. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29265. return startValue;
  29266. }
  29267. default:
  29268. break;
  29269. }
  29270. break;
  29271. }
  29272. }
  29273. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  29274. };
  29275. Animation.prototype.setValue = function (currentValue, blend) {
  29276. if (blend === void 0) { blend = false; }
  29277. // Set value
  29278. var path;
  29279. var destination;
  29280. if (this.targetPropertyPath.length > 1) {
  29281. var property = this._target[this.targetPropertyPath[0]];
  29282. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  29283. property = property[this.targetPropertyPath[index]];
  29284. }
  29285. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  29286. destination = property;
  29287. }
  29288. else {
  29289. path = this.targetPropertyPath[0];
  29290. destination = this._target;
  29291. }
  29292. // Blending
  29293. if (this.enableBlending && this._blendingFactor <= 1.0) {
  29294. if (!this._originalBlendValue) {
  29295. if (destination[path].clone) {
  29296. this._originalBlendValue = destination[path].clone();
  29297. }
  29298. else {
  29299. this._originalBlendValue = destination[path];
  29300. }
  29301. }
  29302. if (this._originalBlendValue.prototype) {
  29303. if (this._originalBlendValue.prototype.Lerp) {
  29304. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  29305. }
  29306. else {
  29307. destination[path] = currentValue;
  29308. }
  29309. }
  29310. else if (this._originalBlendValue.m) {
  29311. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  29312. }
  29313. else {
  29314. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  29315. }
  29316. this._blendingFactor += this.blendingSpeed;
  29317. }
  29318. else {
  29319. destination[path] = currentValue;
  29320. }
  29321. if (this._target.markAsDirty) {
  29322. this._target.markAsDirty(this.targetProperty);
  29323. }
  29324. };
  29325. Animation.prototype.goToFrame = function (frame) {
  29326. if (frame < this._keys[0].frame) {
  29327. frame = this._keys[0].frame;
  29328. }
  29329. else if (frame > this._keys[this._keys.length - 1].frame) {
  29330. frame = this._keys[this._keys.length - 1].frame;
  29331. }
  29332. var currentValue = this._interpolate(frame, 0, this.loopMode);
  29333. this.setValue(currentValue);
  29334. };
  29335. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  29336. if (blend === void 0) { blend = false; }
  29337. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  29338. this._stopped = true;
  29339. return false;
  29340. }
  29341. var returnValue = true;
  29342. // Adding a start key at frame 0 if missing
  29343. if (this._keys[0].frame !== 0) {
  29344. var newKey = { frame: 0, value: this._keys[0].value };
  29345. this._keys.splice(0, 0, newKey);
  29346. }
  29347. // Check limits
  29348. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  29349. from = this._keys[0].frame;
  29350. }
  29351. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  29352. to = this._keys[this._keys.length - 1].frame;
  29353. }
  29354. //to and from cannot be the same key
  29355. if (from === to) {
  29356. from++;
  29357. }
  29358. // Compute ratio
  29359. var range = to - from;
  29360. var offsetValue;
  29361. // ratio represents the frame delta between from and to
  29362. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  29363. var highLimitValue = 0;
  29364. if (ratio > range && !loop) {
  29365. returnValue = false;
  29366. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  29367. }
  29368. else {
  29369. // Get max value if required
  29370. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  29371. var keyOffset = to.toString() + from.toString();
  29372. if (!this._offsetsCache[keyOffset]) {
  29373. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29374. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29375. switch (this.dataType) {
  29376. // Float
  29377. case Animation.ANIMATIONTYPE_FLOAT:
  29378. this._offsetsCache[keyOffset] = toValue - fromValue;
  29379. break;
  29380. // Quaternion
  29381. case Animation.ANIMATIONTYPE_QUATERNION:
  29382. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29383. break;
  29384. // Vector3
  29385. case Animation.ANIMATIONTYPE_VECTOR3:
  29386. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29387. // Vector2
  29388. case Animation.ANIMATIONTYPE_VECTOR2:
  29389. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29390. // Size
  29391. case Animation.ANIMATIONTYPE_SIZE:
  29392. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29393. // Color3
  29394. case Animation.ANIMATIONTYPE_COLOR3:
  29395. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29396. default:
  29397. break;
  29398. }
  29399. this._highLimitsCache[keyOffset] = toValue;
  29400. }
  29401. highLimitValue = this._highLimitsCache[keyOffset];
  29402. offsetValue = this._offsetsCache[keyOffset];
  29403. }
  29404. }
  29405. if (offsetValue === undefined) {
  29406. switch (this.dataType) {
  29407. // Float
  29408. case Animation.ANIMATIONTYPE_FLOAT:
  29409. offsetValue = 0;
  29410. break;
  29411. // Quaternion
  29412. case Animation.ANIMATIONTYPE_QUATERNION:
  29413. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  29414. break;
  29415. // Vector3
  29416. case Animation.ANIMATIONTYPE_VECTOR3:
  29417. offsetValue = BABYLON.Vector3.Zero();
  29418. break;
  29419. // Vector2
  29420. case Animation.ANIMATIONTYPE_VECTOR2:
  29421. offsetValue = BABYLON.Vector2.Zero();
  29422. break;
  29423. // Size
  29424. case Animation.ANIMATIONTYPE_SIZE:
  29425. offsetValue = BABYLON.Size.Zero();
  29426. break;
  29427. // Color3
  29428. case Animation.ANIMATIONTYPE_COLOR3:
  29429. offsetValue = BABYLON.Color3.Black();
  29430. }
  29431. }
  29432. // Compute value
  29433. var repeatCount = (ratio / range) >> 0;
  29434. var currentFrame = returnValue ? from + ratio % range : to;
  29435. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29436. // Set value
  29437. this.setValue(currentValue);
  29438. // Check events
  29439. for (var index = 0; index < this._events.length; index++) {
  29440. if (currentFrame >= this._events[index].frame) {
  29441. var event = this._events[index];
  29442. if (!event.isDone) {
  29443. // If event should be done only once, remove it.
  29444. if (event.onlyOnce) {
  29445. this._events.splice(index, 1);
  29446. index--;
  29447. }
  29448. event.isDone = true;
  29449. event.action();
  29450. } // Don't do anything if the event has already be done.
  29451. }
  29452. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29453. // reset event, the animation is looping
  29454. this._events[index].isDone = false;
  29455. }
  29456. }
  29457. if (!returnValue) {
  29458. this._stopped = true;
  29459. }
  29460. return returnValue;
  29461. };
  29462. Animation.prototype.serialize = function () {
  29463. var serializationObject = {};
  29464. serializationObject.name = this.name;
  29465. serializationObject.property = this.targetProperty;
  29466. serializationObject.framePerSecond = this.framePerSecond;
  29467. serializationObject.dataType = this.dataType;
  29468. serializationObject.loopBehavior = this.loopMode;
  29469. var dataType = this.dataType;
  29470. serializationObject.keys = [];
  29471. var keys = this.getKeys();
  29472. for (var index = 0; index < keys.length; index++) {
  29473. var animationKey = keys[index];
  29474. var key = {};
  29475. key.frame = animationKey.frame;
  29476. switch (dataType) {
  29477. case Animation.ANIMATIONTYPE_FLOAT:
  29478. key.values = [animationKey.value];
  29479. break;
  29480. case Animation.ANIMATIONTYPE_QUATERNION:
  29481. case Animation.ANIMATIONTYPE_MATRIX:
  29482. case Animation.ANIMATIONTYPE_VECTOR3:
  29483. case Animation.ANIMATIONTYPE_COLOR3:
  29484. key.values = animationKey.value.asArray();
  29485. break;
  29486. }
  29487. serializationObject.keys.push(key);
  29488. }
  29489. serializationObject.ranges = [];
  29490. for (var name in this._ranges) {
  29491. var range = {};
  29492. range.name = name;
  29493. range.from = this._ranges[name].from;
  29494. range.to = this._ranges[name].to;
  29495. serializationObject.ranges.push(range);
  29496. }
  29497. return serializationObject;
  29498. };
  29499. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29500. get: function () {
  29501. return Animation._ANIMATIONTYPE_FLOAT;
  29502. },
  29503. enumerable: true,
  29504. configurable: true
  29505. });
  29506. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29507. get: function () {
  29508. return Animation._ANIMATIONTYPE_VECTOR3;
  29509. },
  29510. enumerable: true,
  29511. configurable: true
  29512. });
  29513. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29514. get: function () {
  29515. return Animation._ANIMATIONTYPE_VECTOR2;
  29516. },
  29517. enumerable: true,
  29518. configurable: true
  29519. });
  29520. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29521. get: function () {
  29522. return Animation._ANIMATIONTYPE_SIZE;
  29523. },
  29524. enumerable: true,
  29525. configurable: true
  29526. });
  29527. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29528. get: function () {
  29529. return Animation._ANIMATIONTYPE_QUATERNION;
  29530. },
  29531. enumerable: true,
  29532. configurable: true
  29533. });
  29534. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29535. get: function () {
  29536. return Animation._ANIMATIONTYPE_MATRIX;
  29537. },
  29538. enumerable: true,
  29539. configurable: true
  29540. });
  29541. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29542. get: function () {
  29543. return Animation._ANIMATIONTYPE_COLOR3;
  29544. },
  29545. enumerable: true,
  29546. configurable: true
  29547. });
  29548. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29549. get: function () {
  29550. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29551. },
  29552. enumerable: true,
  29553. configurable: true
  29554. });
  29555. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29556. get: function () {
  29557. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29558. },
  29559. enumerable: true,
  29560. configurable: true
  29561. });
  29562. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29563. get: function () {
  29564. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29565. },
  29566. enumerable: true,
  29567. configurable: true
  29568. });
  29569. Animation.Parse = function (parsedAnimation) {
  29570. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29571. var dataType = parsedAnimation.dataType;
  29572. var keys = [];
  29573. var data;
  29574. var index;
  29575. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29576. var key = parsedAnimation.keys[index];
  29577. switch (dataType) {
  29578. case Animation.ANIMATIONTYPE_FLOAT:
  29579. data = key.values[0];
  29580. break;
  29581. case Animation.ANIMATIONTYPE_QUATERNION:
  29582. data = BABYLON.Quaternion.FromArray(key.values);
  29583. break;
  29584. case Animation.ANIMATIONTYPE_MATRIX:
  29585. data = BABYLON.Matrix.FromArray(key.values);
  29586. break;
  29587. case Animation.ANIMATIONTYPE_COLOR3:
  29588. data = BABYLON.Color3.FromArray(key.values);
  29589. break;
  29590. case Animation.ANIMATIONTYPE_VECTOR3:
  29591. default:
  29592. data = BABYLON.Vector3.FromArray(key.values);
  29593. break;
  29594. }
  29595. keys.push({
  29596. frame: key.frame,
  29597. value: data
  29598. });
  29599. }
  29600. animation.setKeys(keys);
  29601. if (parsedAnimation.ranges) {
  29602. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29603. data = parsedAnimation.ranges[index];
  29604. animation.createRange(data.name, data.from, data.to);
  29605. }
  29606. }
  29607. return animation;
  29608. };
  29609. Animation.AppendSerializedAnimations = function (source, destination) {
  29610. if (source.animations) {
  29611. destination.animations = [];
  29612. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29613. var animation = source.animations[animationIndex];
  29614. destination.animations.push(animation.serialize());
  29615. }
  29616. }
  29617. };
  29618. // Statics
  29619. Animation._ANIMATIONTYPE_FLOAT = 0;
  29620. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29621. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29622. Animation._ANIMATIONTYPE_MATRIX = 3;
  29623. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29624. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29625. Animation._ANIMATIONTYPE_SIZE = 6;
  29626. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29627. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29628. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29629. return Animation;
  29630. }());
  29631. BABYLON.Animation = Animation;
  29632. })(BABYLON || (BABYLON = {}));
  29633. //# sourceMappingURL=babylon.animation.js.map
  29634. var BABYLON;
  29635. (function (BABYLON) {
  29636. var Animatable = (function () {
  29637. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29638. if (fromFrame === void 0) { fromFrame = 0; }
  29639. if (toFrame === void 0) { toFrame = 100; }
  29640. if (loopAnimation === void 0) { loopAnimation = false; }
  29641. if (speedRatio === void 0) { speedRatio = 1.0; }
  29642. this.target = target;
  29643. this.fromFrame = fromFrame;
  29644. this.toFrame = toFrame;
  29645. this.loopAnimation = loopAnimation;
  29646. this.speedRatio = speedRatio;
  29647. this.onAnimationEnd = onAnimationEnd;
  29648. this._animations = new Array();
  29649. this._paused = false;
  29650. this.animationStarted = false;
  29651. if (animations) {
  29652. this.appendAnimations(target, animations);
  29653. }
  29654. this._scene = scene;
  29655. scene._activeAnimatables.push(this);
  29656. }
  29657. // Methods
  29658. Animatable.prototype.getAnimations = function () {
  29659. return this._animations;
  29660. };
  29661. Animatable.prototype.appendAnimations = function (target, animations) {
  29662. for (var index = 0; index < animations.length; index++) {
  29663. var animation = animations[index];
  29664. animation._target = target;
  29665. this._animations.push(animation);
  29666. }
  29667. };
  29668. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29669. var animations = this._animations;
  29670. for (var index = 0; index < animations.length; index++) {
  29671. if (animations[index].targetProperty === property) {
  29672. return animations[index];
  29673. }
  29674. }
  29675. return null;
  29676. };
  29677. Animatable.prototype.reset = function () {
  29678. var animations = this._animations;
  29679. for (var index = 0; index < animations.length; index++) {
  29680. animations[index].reset();
  29681. }
  29682. this._localDelayOffset = null;
  29683. this._pausedDelay = null;
  29684. };
  29685. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29686. var animations = this._animations;
  29687. for (var index = 0; index < animations.length; index++) {
  29688. animations[index].enableBlending = true;
  29689. animations[index].blendingSpeed = blendingSpeed;
  29690. }
  29691. };
  29692. Animatable.prototype.disableBlending = function () {
  29693. var animations = this._animations;
  29694. for (var index = 0; index < animations.length; index++) {
  29695. animations[index].enableBlending = false;
  29696. }
  29697. };
  29698. Animatable.prototype.goToFrame = function (frame) {
  29699. var animations = this._animations;
  29700. if (animations[0]) {
  29701. var fps = animations[0].framePerSecond;
  29702. var currentFrame = animations[0].currentFrame;
  29703. var adjustTime = frame - currentFrame;
  29704. var delay = adjustTime * 1000 / fps;
  29705. this._localDelayOffset -= delay;
  29706. }
  29707. for (var index = 0; index < animations.length; index++) {
  29708. animations[index].goToFrame(frame);
  29709. }
  29710. };
  29711. Animatable.prototype.pause = function () {
  29712. if (this._paused) {
  29713. return;
  29714. }
  29715. this._paused = true;
  29716. };
  29717. Animatable.prototype.restart = function () {
  29718. this._paused = false;
  29719. };
  29720. Animatable.prototype.stop = function (animationName) {
  29721. var index = this._scene._activeAnimatables.indexOf(this);
  29722. if (index > -1) {
  29723. var animations = this._animations;
  29724. var numberOfAnimationsStopped = 0;
  29725. for (var index = animations.length - 1; index >= 0; index--) {
  29726. if (typeof animationName === "string" && animations[index].name != animationName) {
  29727. continue;
  29728. }
  29729. animations[index].reset();
  29730. animations.splice(index, 1);
  29731. numberOfAnimationsStopped++;
  29732. }
  29733. if (animations.length == numberOfAnimationsStopped) {
  29734. this._scene._activeAnimatables.splice(index, 1);
  29735. if (this.onAnimationEnd) {
  29736. this.onAnimationEnd();
  29737. }
  29738. }
  29739. }
  29740. };
  29741. Animatable.prototype._animate = function (delay) {
  29742. if (this._paused) {
  29743. this.animationStarted = false;
  29744. if (!this._pausedDelay) {
  29745. this._pausedDelay = delay;
  29746. }
  29747. return true;
  29748. }
  29749. if (!this._localDelayOffset) {
  29750. this._localDelayOffset = delay;
  29751. }
  29752. else if (this._pausedDelay) {
  29753. this._localDelayOffset += delay - this._pausedDelay;
  29754. this._pausedDelay = null;
  29755. }
  29756. // Animating
  29757. var running = false;
  29758. var animations = this._animations;
  29759. var index;
  29760. for (index = 0; index < animations.length; index++) {
  29761. var animation = animations[index];
  29762. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29763. running = running || isRunning;
  29764. }
  29765. this.animationStarted = running;
  29766. if (!running) {
  29767. // Remove from active animatables
  29768. index = this._scene._activeAnimatables.indexOf(this);
  29769. this._scene._activeAnimatables.splice(index, 1);
  29770. }
  29771. if (!running && this.onAnimationEnd) {
  29772. this.onAnimationEnd();
  29773. this.onAnimationEnd = null;
  29774. }
  29775. return running;
  29776. };
  29777. return Animatable;
  29778. }());
  29779. BABYLON.Animatable = Animatable;
  29780. })(BABYLON || (BABYLON = {}));
  29781. //# sourceMappingURL=babylon.animatable.js.map
  29782. var BABYLON;
  29783. (function (BABYLON) {
  29784. var EasingFunction = (function () {
  29785. function EasingFunction() {
  29786. // Properties
  29787. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29788. }
  29789. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29790. get: function () {
  29791. return EasingFunction._EASINGMODE_EASEIN;
  29792. },
  29793. enumerable: true,
  29794. configurable: true
  29795. });
  29796. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29797. get: function () {
  29798. return EasingFunction._EASINGMODE_EASEOUT;
  29799. },
  29800. enumerable: true,
  29801. configurable: true
  29802. });
  29803. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29804. get: function () {
  29805. return EasingFunction._EASINGMODE_EASEINOUT;
  29806. },
  29807. enumerable: true,
  29808. configurable: true
  29809. });
  29810. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29811. var n = Math.min(Math.max(easingMode, 0), 2);
  29812. this._easingMode = n;
  29813. };
  29814. EasingFunction.prototype.getEasingMode = function () {
  29815. return this._easingMode;
  29816. };
  29817. EasingFunction.prototype.easeInCore = function (gradient) {
  29818. throw new Error('You must implement this method');
  29819. };
  29820. EasingFunction.prototype.ease = function (gradient) {
  29821. switch (this._easingMode) {
  29822. case EasingFunction.EASINGMODE_EASEIN:
  29823. return this.easeInCore(gradient);
  29824. case EasingFunction.EASINGMODE_EASEOUT:
  29825. return (1 - this.easeInCore(1 - gradient));
  29826. }
  29827. if (gradient >= 0.5) {
  29828. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29829. }
  29830. return (this.easeInCore(gradient * 2) * 0.5);
  29831. };
  29832. //Statics
  29833. EasingFunction._EASINGMODE_EASEIN = 0;
  29834. EasingFunction._EASINGMODE_EASEOUT = 1;
  29835. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29836. return EasingFunction;
  29837. }());
  29838. BABYLON.EasingFunction = EasingFunction;
  29839. var CircleEase = (function (_super) {
  29840. __extends(CircleEase, _super);
  29841. function CircleEase() {
  29842. _super.apply(this, arguments);
  29843. }
  29844. CircleEase.prototype.easeInCore = function (gradient) {
  29845. gradient = Math.max(0, Math.min(1, gradient));
  29846. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29847. };
  29848. return CircleEase;
  29849. }(EasingFunction));
  29850. BABYLON.CircleEase = CircleEase;
  29851. var BackEase = (function (_super) {
  29852. __extends(BackEase, _super);
  29853. function BackEase(amplitude) {
  29854. if (amplitude === void 0) { amplitude = 1; }
  29855. _super.call(this);
  29856. this.amplitude = amplitude;
  29857. }
  29858. BackEase.prototype.easeInCore = function (gradient) {
  29859. var num = Math.max(0, this.amplitude);
  29860. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29861. };
  29862. return BackEase;
  29863. }(EasingFunction));
  29864. BABYLON.BackEase = BackEase;
  29865. var BounceEase = (function (_super) {
  29866. __extends(BounceEase, _super);
  29867. function BounceEase(bounces, bounciness) {
  29868. if (bounces === void 0) { bounces = 3; }
  29869. if (bounciness === void 0) { bounciness = 2; }
  29870. _super.call(this);
  29871. this.bounces = bounces;
  29872. this.bounciness = bounciness;
  29873. }
  29874. BounceEase.prototype.easeInCore = function (gradient) {
  29875. var y = Math.max(0.0, this.bounces);
  29876. var bounciness = this.bounciness;
  29877. if (bounciness <= 1.0) {
  29878. bounciness = 1.001;
  29879. }
  29880. var num9 = Math.pow(bounciness, y);
  29881. var num5 = 1.0 - bounciness;
  29882. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29883. var num15 = gradient * num4;
  29884. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29885. var num3 = Math.floor(num65);
  29886. var num13 = num3 + 1.0;
  29887. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29888. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29889. var num7 = (num8 + num12) * 0.5;
  29890. var num6 = gradient - num7;
  29891. var num2 = num7 - num8;
  29892. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29893. };
  29894. return BounceEase;
  29895. }(EasingFunction));
  29896. BABYLON.BounceEase = BounceEase;
  29897. var CubicEase = (function (_super) {
  29898. __extends(CubicEase, _super);
  29899. function CubicEase() {
  29900. _super.apply(this, arguments);
  29901. }
  29902. CubicEase.prototype.easeInCore = function (gradient) {
  29903. return (gradient * gradient * gradient);
  29904. };
  29905. return CubicEase;
  29906. }(EasingFunction));
  29907. BABYLON.CubicEase = CubicEase;
  29908. var ElasticEase = (function (_super) {
  29909. __extends(ElasticEase, _super);
  29910. function ElasticEase(oscillations, springiness) {
  29911. if (oscillations === void 0) { oscillations = 3; }
  29912. if (springiness === void 0) { springiness = 3; }
  29913. _super.call(this);
  29914. this.oscillations = oscillations;
  29915. this.springiness = springiness;
  29916. }
  29917. ElasticEase.prototype.easeInCore = function (gradient) {
  29918. var num2;
  29919. var num3 = Math.max(0.0, this.oscillations);
  29920. var num = Math.max(0.0, this.springiness);
  29921. if (num == 0) {
  29922. num2 = gradient;
  29923. }
  29924. else {
  29925. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29926. }
  29927. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29928. };
  29929. return ElasticEase;
  29930. }(EasingFunction));
  29931. BABYLON.ElasticEase = ElasticEase;
  29932. var ExponentialEase = (function (_super) {
  29933. __extends(ExponentialEase, _super);
  29934. function ExponentialEase(exponent) {
  29935. if (exponent === void 0) { exponent = 2; }
  29936. _super.call(this);
  29937. this.exponent = exponent;
  29938. }
  29939. ExponentialEase.prototype.easeInCore = function (gradient) {
  29940. if (this.exponent <= 0) {
  29941. return gradient;
  29942. }
  29943. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29944. };
  29945. return ExponentialEase;
  29946. }(EasingFunction));
  29947. BABYLON.ExponentialEase = ExponentialEase;
  29948. var PowerEase = (function (_super) {
  29949. __extends(PowerEase, _super);
  29950. function PowerEase(power) {
  29951. if (power === void 0) { power = 2; }
  29952. _super.call(this);
  29953. this.power = power;
  29954. }
  29955. PowerEase.prototype.easeInCore = function (gradient) {
  29956. var y = Math.max(0.0, this.power);
  29957. return Math.pow(gradient, y);
  29958. };
  29959. return PowerEase;
  29960. }(EasingFunction));
  29961. BABYLON.PowerEase = PowerEase;
  29962. var QuadraticEase = (function (_super) {
  29963. __extends(QuadraticEase, _super);
  29964. function QuadraticEase() {
  29965. _super.apply(this, arguments);
  29966. }
  29967. QuadraticEase.prototype.easeInCore = function (gradient) {
  29968. return (gradient * gradient);
  29969. };
  29970. return QuadraticEase;
  29971. }(EasingFunction));
  29972. BABYLON.QuadraticEase = QuadraticEase;
  29973. var QuarticEase = (function (_super) {
  29974. __extends(QuarticEase, _super);
  29975. function QuarticEase() {
  29976. _super.apply(this, arguments);
  29977. }
  29978. QuarticEase.prototype.easeInCore = function (gradient) {
  29979. return (gradient * gradient * gradient * gradient);
  29980. };
  29981. return QuarticEase;
  29982. }(EasingFunction));
  29983. BABYLON.QuarticEase = QuarticEase;
  29984. var QuinticEase = (function (_super) {
  29985. __extends(QuinticEase, _super);
  29986. function QuinticEase() {
  29987. _super.apply(this, arguments);
  29988. }
  29989. QuinticEase.prototype.easeInCore = function (gradient) {
  29990. return (gradient * gradient * gradient * gradient * gradient);
  29991. };
  29992. return QuinticEase;
  29993. }(EasingFunction));
  29994. BABYLON.QuinticEase = QuinticEase;
  29995. var SineEase = (function (_super) {
  29996. __extends(SineEase, _super);
  29997. function SineEase() {
  29998. _super.apply(this, arguments);
  29999. }
  30000. SineEase.prototype.easeInCore = function (gradient) {
  30001. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30002. };
  30003. return SineEase;
  30004. }(EasingFunction));
  30005. BABYLON.SineEase = SineEase;
  30006. var BezierCurveEase = (function (_super) {
  30007. __extends(BezierCurveEase, _super);
  30008. function BezierCurveEase(x1, y1, x2, y2) {
  30009. if (x1 === void 0) { x1 = 0; }
  30010. if (y1 === void 0) { y1 = 0; }
  30011. if (x2 === void 0) { x2 = 1; }
  30012. if (y2 === void 0) { y2 = 1; }
  30013. _super.call(this);
  30014. this.x1 = x1;
  30015. this.y1 = y1;
  30016. this.x2 = x2;
  30017. this.y2 = y2;
  30018. }
  30019. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30020. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30021. };
  30022. return BezierCurveEase;
  30023. }(EasingFunction));
  30024. BABYLON.BezierCurveEase = BezierCurveEase;
  30025. })(BABYLON || (BABYLON = {}));
  30026. //# sourceMappingURL=babylon.easing.js.map
  30027. var BABYLON;
  30028. (function (BABYLON) {
  30029. var Bone = (function (_super) {
  30030. __extends(Bone, _super);
  30031. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30032. _super.call(this, name, skeleton.getScene());
  30033. this.name = name;
  30034. this.children = new Array();
  30035. this.animations = new Array();
  30036. this._worldTransform = new BABYLON.Matrix();
  30037. this._absoluteTransform = new BABYLON.Matrix();
  30038. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30039. this._scaleMatrix = BABYLON.Matrix.Identity();
  30040. this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30041. this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30042. this._scalingDeterminant = 1;
  30043. this._syncScaleVector = function () {
  30044. var lm = this.getLocalMatrix();
  30045. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30046. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30047. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30048. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30049. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30050. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30051. this._scaleVector.x = xs * Math.sqrt(xsq);
  30052. this._scaleVector.y = ys * Math.sqrt(ysq);
  30053. this._scaleVector.z = zs * Math.sqrt(zsq);
  30054. if (this._parent) {
  30055. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30056. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30057. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30058. }
  30059. 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);
  30060. };
  30061. this._skeleton = skeleton;
  30062. this._matrix = matrix;
  30063. this._baseMatrix = matrix;
  30064. this._restPose = restPose ? restPose : matrix.clone();
  30065. skeleton.bones.push(this);
  30066. if (parentBone) {
  30067. this._parent = parentBone;
  30068. parentBone.children.push(this);
  30069. }
  30070. else {
  30071. this._parent = null;
  30072. }
  30073. this._updateDifferenceMatrix();
  30074. if (this.getAbsoluteTransform().determinant() < 0) {
  30075. this._scalingDeterminant *= -1;
  30076. }
  30077. }
  30078. // Members
  30079. Bone.prototype.getParent = function () {
  30080. return this._parent;
  30081. };
  30082. Bone.prototype.getLocalMatrix = function () {
  30083. return this._matrix;
  30084. };
  30085. Bone.prototype.getBaseMatrix = function () {
  30086. return this._baseMatrix;
  30087. };
  30088. Bone.prototype.getRestPose = function () {
  30089. return this._restPose;
  30090. };
  30091. Bone.prototype.returnToRest = function () {
  30092. this.updateMatrix(this._restPose.clone());
  30093. };
  30094. Bone.prototype.getWorldMatrix = function () {
  30095. return this._worldTransform;
  30096. };
  30097. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30098. return this._invertedAbsoluteTransform;
  30099. };
  30100. Bone.prototype.getAbsoluteTransform = function () {
  30101. return this._absoluteTransform;
  30102. };
  30103. // Methods
  30104. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30105. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30106. this._baseMatrix = matrix.clone();
  30107. this._matrix = matrix.clone();
  30108. this._skeleton._markAsDirty();
  30109. if (updateDifferenceMatrix) {
  30110. this._updateDifferenceMatrix();
  30111. }
  30112. };
  30113. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30114. if (!rootMatrix) {
  30115. rootMatrix = this._baseMatrix;
  30116. }
  30117. if (this._parent) {
  30118. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30119. }
  30120. else {
  30121. this._absoluteTransform.copyFrom(rootMatrix);
  30122. }
  30123. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  30124. for (var index = 0; index < this.children.length; index++) {
  30125. this.children[index]._updateDifferenceMatrix();
  30126. }
  30127. };
  30128. Bone.prototype.markAsDirty = function () {
  30129. this._currentRenderId++;
  30130. this._skeleton._markAsDirty();
  30131. };
  30132. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  30133. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30134. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  30135. // all animation may be coming from a library skeleton, so may need to create animation
  30136. if (this.animations.length === 0) {
  30137. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  30138. this.animations[0].setKeys([]);
  30139. }
  30140. // get animation info / verify there is such a range from the source bone
  30141. var sourceRange = source.animations[0].getRange(rangeName);
  30142. if (!sourceRange) {
  30143. return false;
  30144. }
  30145. var from = sourceRange.from;
  30146. var to = sourceRange.to;
  30147. var sourceKeys = source.animations[0].getKeys();
  30148. // rescaling prep
  30149. var sourceBoneLength = source.length;
  30150. var sourceParent = source.getParent();
  30151. var parent = this.getParent();
  30152. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  30153. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  30154. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  30155. var destKeys = this.animations[0].getKeys();
  30156. // loop vars declaration
  30157. var orig;
  30158. var origTranslation;
  30159. var mat;
  30160. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  30161. orig = sourceKeys[key];
  30162. if (orig.frame >= from && orig.frame <= to) {
  30163. if (rescaleAsRequired) {
  30164. mat = orig.value.clone();
  30165. // scale based on parent ratio, when bone has parent
  30166. if (parentScalingReqd) {
  30167. origTranslation = mat.getTranslation();
  30168. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  30169. }
  30170. else if (dimensionsScalingReqd) {
  30171. origTranslation = mat.getTranslation();
  30172. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  30173. }
  30174. else {
  30175. mat = orig.value;
  30176. }
  30177. }
  30178. else {
  30179. mat = orig.value;
  30180. }
  30181. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  30182. }
  30183. }
  30184. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  30185. return true;
  30186. };
  30187. Bone.prototype.translate = function (vec, space, mesh) {
  30188. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30189. var lm = this.getLocalMatrix();
  30190. if (space == BABYLON.Space.LOCAL) {
  30191. lm.m[12] += vec.x;
  30192. lm.m[13] += vec.y;
  30193. lm.m[14] += vec.z;
  30194. }
  30195. else {
  30196. this._skeleton.computeAbsoluteTransforms();
  30197. var tmat = BABYLON.Tmp.Matrix[0];
  30198. var tvec = BABYLON.Tmp.Vector3[0];
  30199. if (mesh) {
  30200. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30201. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30202. }
  30203. else {
  30204. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30205. }
  30206. tmat.m[12] = 0;
  30207. tmat.m[13] = 0;
  30208. tmat.m[14] = 0;
  30209. tmat.invert();
  30210. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  30211. lm.m[12] += tvec.x;
  30212. lm.m[13] += tvec.y;
  30213. lm.m[14] += tvec.z;
  30214. }
  30215. this.markAsDirty();
  30216. };
  30217. Bone.prototype.setPosition = function (position, space, mesh) {
  30218. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30219. var lm = this.getLocalMatrix();
  30220. if (space == BABYLON.Space.LOCAL) {
  30221. lm.m[12] = position.x;
  30222. lm.m[13] = position.y;
  30223. lm.m[14] = position.z;
  30224. }
  30225. else {
  30226. this._skeleton.computeAbsoluteTransforms();
  30227. var tmat = BABYLON.Tmp.Matrix[0];
  30228. var vec = BABYLON.Tmp.Vector3[0];
  30229. if (mesh) {
  30230. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30231. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30232. }
  30233. else {
  30234. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30235. }
  30236. tmat.invert();
  30237. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  30238. lm.m[12] = vec.x;
  30239. lm.m[13] = vec.y;
  30240. lm.m[14] = vec.z;
  30241. }
  30242. this.markAsDirty();
  30243. };
  30244. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  30245. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  30246. };
  30247. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  30248. if (scaleChildren === void 0) { scaleChildren = false; }
  30249. if (this.animations[0] && !this.animations[0].isStopped()) {
  30250. if (!scaleChildren) {
  30251. this._negateScaleChildren.x = 1 / x;
  30252. this._negateScaleChildren.y = 1 / y;
  30253. this._negateScaleChildren.z = 1 / z;
  30254. }
  30255. this._syncScaleVector();
  30256. }
  30257. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  30258. };
  30259. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  30260. if (scaleChildren === void 0) { scaleChildren = false; }
  30261. var locMat = this.getLocalMatrix();
  30262. var origLocMat = BABYLON.Tmp.Matrix[0];
  30263. origLocMat.copyFrom(locMat);
  30264. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  30265. origLocMatInv.copyFrom(origLocMat);
  30266. origLocMatInv.invert();
  30267. var scaleMat = BABYLON.Tmp.Matrix[2];
  30268. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  30269. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  30270. this._scaleVector.x *= x;
  30271. this._scaleVector.y *= y;
  30272. this._scaleVector.z *= z;
  30273. locMat.multiplyToRef(origLocMatInv, locMat);
  30274. locMat.multiplyToRef(scaleMat, locMat);
  30275. locMat.multiplyToRef(origLocMat, locMat);
  30276. var parent = this.getParent();
  30277. if (parent) {
  30278. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  30279. }
  30280. else {
  30281. this.getAbsoluteTransform().copyFrom(locMat);
  30282. }
  30283. var len = this.children.length;
  30284. scaleMat.invert();
  30285. for (var i = 0; i < len; i++) {
  30286. var child = this.children[i];
  30287. var cm = child.getLocalMatrix();
  30288. cm.multiplyToRef(scaleMat, cm);
  30289. var lm = child.getLocalMatrix();
  30290. lm.m[12] *= x;
  30291. lm.m[13] *= y;
  30292. lm.m[14] *= z;
  30293. }
  30294. this.computeAbsoluteTransforms();
  30295. if (scaleChildren) {
  30296. for (var i = 0; i < len; i++) {
  30297. this.children[i].scale(x, y, z, scaleChildren);
  30298. }
  30299. }
  30300. this.markAsDirty();
  30301. };
  30302. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  30303. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30304. var rotMat = BABYLON.Tmp.Matrix[0];
  30305. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  30306. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30307. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30308. rotMatInv.multiplyToRef(rotMat, rotMat);
  30309. this._rotateWithMatrix(rotMat, space, mesh);
  30310. };
  30311. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  30312. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30313. var rmat = BABYLON.Tmp.Matrix[0];
  30314. rmat.m[12] = 0;
  30315. rmat.m[13] = 0;
  30316. rmat.m[14] = 0;
  30317. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  30318. this._rotateWithMatrix(rmat, space, mesh);
  30319. };
  30320. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  30321. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30322. var rotMat = BABYLON.Tmp.Matrix[0];
  30323. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  30324. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30325. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30326. rotMatInv.multiplyToRef(rotMat, rotMat);
  30327. this._rotateWithMatrix(rotMat, space, mesh);
  30328. };
  30329. Bone.prototype.setRotation = function (rotation, space, mesh) {
  30330. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30331. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  30332. };
  30333. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  30334. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30335. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30336. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30337. var rotMat = BABYLON.Tmp.Matrix[1];
  30338. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  30339. rotMatInv.multiplyToRef(rotMat, rotMat);
  30340. this._rotateWithMatrix(rotMat, space, mesh);
  30341. };
  30342. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  30343. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30344. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30345. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30346. var rotMat2 = BABYLON.Tmp.Matrix[1];
  30347. rotMat2.copyFrom(rotMat);
  30348. rotMatInv.multiplyToRef(rotMat, rotMat2);
  30349. this._rotateWithMatrix(rotMat2, space, mesh);
  30350. };
  30351. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  30352. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30353. var lmat = this.getLocalMatrix();
  30354. var lx = lmat.m[12];
  30355. var ly = lmat.m[13];
  30356. var lz = lmat.m[14];
  30357. var parent = this.getParent();
  30358. var parentScale = BABYLON.Tmp.Matrix[3];
  30359. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  30360. if (parent) {
  30361. if (space == BABYLON.Space.WORLD) {
  30362. if (mesh) {
  30363. parentScale.copyFrom(mesh.getWorldMatrix());
  30364. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  30365. }
  30366. else {
  30367. parentScale.copyFrom(parent.getAbsoluteTransform());
  30368. }
  30369. }
  30370. else {
  30371. parentScale = parent._scaleMatrix;
  30372. }
  30373. parentScaleInv.copyFrom(parentScale);
  30374. parentScaleInv.invert();
  30375. lmat.multiplyToRef(parentScale, lmat);
  30376. lmat.multiplyToRef(rmat, lmat);
  30377. lmat.multiplyToRef(parentScaleInv, lmat);
  30378. }
  30379. else {
  30380. if (space == BABYLON.Space.WORLD && mesh) {
  30381. parentScale.copyFrom(mesh.getWorldMatrix());
  30382. parentScaleInv.copyFrom(parentScale);
  30383. parentScaleInv.invert();
  30384. lmat.multiplyToRef(parentScale, lmat);
  30385. lmat.multiplyToRef(rmat, lmat);
  30386. lmat.multiplyToRef(parentScaleInv, lmat);
  30387. }
  30388. else {
  30389. lmat.multiplyToRef(rmat, lmat);
  30390. }
  30391. }
  30392. lmat.m[12] = lx;
  30393. lmat.m[13] = ly;
  30394. lmat.m[14] = lz;
  30395. this.computeAbsoluteTransforms();
  30396. this.markAsDirty();
  30397. };
  30398. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  30399. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30400. if (space == BABYLON.Space.WORLD) {
  30401. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30402. scaleMatrix.copyFrom(this._scaleMatrix);
  30403. rotMatInv.copyFrom(this.getAbsoluteTransform());
  30404. if (mesh) {
  30405. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  30406. var meshScale = BABYLON.Tmp.Matrix[3];
  30407. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  30408. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  30409. }
  30410. rotMatInv.invert();
  30411. scaleMatrix.m[0] *= this._scalingDeterminant;
  30412. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30413. }
  30414. else {
  30415. rotMatInv.copyFrom(this.getLocalMatrix());
  30416. rotMatInv.invert();
  30417. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30418. scaleMatrix.copyFrom(this._scaleMatrix);
  30419. if (this._parent) {
  30420. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  30421. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  30422. pscaleMatrix.invert();
  30423. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  30424. }
  30425. else {
  30426. scaleMatrix.m[0] *= this._scalingDeterminant;
  30427. }
  30428. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30429. }
  30430. };
  30431. Bone.prototype.getScale = function () {
  30432. return this._scaleVector.clone();
  30433. };
  30434. Bone.prototype.getScaleToRef = function (result) {
  30435. result.copyFrom(this._scaleVector);
  30436. };
  30437. Bone.prototype.getPosition = function (space, mesh) {
  30438. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30439. var pos = BABYLON.Vector3.Zero();
  30440. this.getPositionToRef(space, mesh, pos);
  30441. return pos;
  30442. };
  30443. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  30444. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30445. if (space == BABYLON.Space.LOCAL) {
  30446. var lm = this.getLocalMatrix();
  30447. result.x = lm.m[12];
  30448. result.y = lm.m[13];
  30449. result.z = lm.m[14];
  30450. }
  30451. else {
  30452. this._skeleton.computeAbsoluteTransforms();
  30453. var tmat = BABYLON.Tmp.Matrix[0];
  30454. if (mesh) {
  30455. tmat.copyFrom(this.getAbsoluteTransform());
  30456. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30457. }
  30458. else {
  30459. tmat = this.getAbsoluteTransform();
  30460. }
  30461. result.x = tmat.m[12];
  30462. result.y = tmat.m[13];
  30463. result.z = tmat.m[14];
  30464. }
  30465. };
  30466. Bone.prototype.getAbsolutePosition = function (mesh) {
  30467. var pos = BABYLON.Vector3.Zero();
  30468. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  30469. return pos;
  30470. };
  30471. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  30472. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  30473. };
  30474. Bone.prototype.computeAbsoluteTransforms = function () {
  30475. if (this._parent) {
  30476. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30477. }
  30478. else {
  30479. this._absoluteTransform.copyFrom(this._matrix);
  30480. var poseMatrix = this._skeleton.getPoseMatrix();
  30481. if (poseMatrix) {
  30482. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  30483. }
  30484. }
  30485. var children = this.children;
  30486. var len = children.length;
  30487. for (var i = 0; i < len; i++) {
  30488. children[i].computeAbsoluteTransforms();
  30489. }
  30490. };
  30491. Bone.prototype.getDirection = function (localAxis, mesh) {
  30492. var result = BABYLON.Vector3.Zero();
  30493. this.getDirectionToRef(localAxis, mesh, result);
  30494. return result;
  30495. };
  30496. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  30497. this._skeleton.computeAbsoluteTransforms();
  30498. var mat = BABYLON.Tmp.Matrix[0];
  30499. mat.copyFrom(this.getAbsoluteTransform());
  30500. if (mesh) {
  30501. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30502. }
  30503. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  30504. result.normalize();
  30505. };
  30506. Bone.prototype.getRotation = function (space, mesh) {
  30507. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30508. var result = BABYLON.Vector3.Zero();
  30509. this.getRotationToRef(space, mesh, result);
  30510. return result;
  30511. };
  30512. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  30513. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30514. var quat = BABYLON.Tmp.Quaternion[0];
  30515. this.getRotationQuaternionToRef(space, mesh, quat);
  30516. quat.toEulerAnglesToRef(result);
  30517. };
  30518. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  30519. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30520. var result = BABYLON.Quaternion.Identity();
  30521. this.getRotationQuaternionToRef(space, mesh, result);
  30522. return result;
  30523. };
  30524. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  30525. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30526. if (space == BABYLON.Space.LOCAL) {
  30527. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30528. }
  30529. else {
  30530. var mat = BABYLON.Tmp.Matrix[0];
  30531. var amat = this.getAbsoluteTransform();
  30532. if (mesh) {
  30533. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30534. }
  30535. else {
  30536. mat.copyFrom(amat);
  30537. }
  30538. mat.m[0] *= this._scalingDeterminant;
  30539. mat.m[1] *= this._scalingDeterminant;
  30540. mat.m[2] *= this._scalingDeterminant;
  30541. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30542. }
  30543. };
  30544. Bone.prototype.getRotationMatrix = function (space, mesh) {
  30545. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30546. var result = BABYLON.Matrix.Identity();
  30547. this.getRotationMatrixToRef(space, mesh, result);
  30548. return result;
  30549. };
  30550. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  30551. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30552. if (space == BABYLON.Space.LOCAL) {
  30553. this.getLocalMatrix().getRotationMatrixToRef(result);
  30554. }
  30555. else {
  30556. var mat = BABYLON.Tmp.Matrix[0];
  30557. var amat = this.getAbsoluteTransform();
  30558. if (mesh) {
  30559. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30560. }
  30561. else {
  30562. mat.copyFrom(amat);
  30563. }
  30564. mat.m[0] *= this._scalingDeterminant;
  30565. mat.m[1] *= this._scalingDeterminant;
  30566. mat.m[2] *= this._scalingDeterminant;
  30567. mat.getRotationMatrixToRef(result);
  30568. }
  30569. };
  30570. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  30571. var result = BABYLON.Vector3.Zero();
  30572. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  30573. return result;
  30574. };
  30575. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  30576. this._skeleton.computeAbsoluteTransforms();
  30577. var tmat = BABYLON.Tmp.Matrix[0];
  30578. if (mesh) {
  30579. tmat.copyFrom(this.getAbsoluteTransform());
  30580. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30581. }
  30582. else {
  30583. tmat = this.getAbsoluteTransform();
  30584. }
  30585. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30586. };
  30587. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  30588. var result = BABYLON.Vector3.Zero();
  30589. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  30590. return result;
  30591. };
  30592. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  30593. this._skeleton.computeAbsoluteTransforms();
  30594. var tmat = BABYLON.Tmp.Matrix[0];
  30595. tmat.copyFrom(this.getAbsoluteTransform());
  30596. if (mesh) {
  30597. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30598. }
  30599. tmat.invert();
  30600. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30601. };
  30602. return Bone;
  30603. }(BABYLON.Node));
  30604. BABYLON.Bone = Bone;
  30605. })(BABYLON || (BABYLON = {}));
  30606. //# sourceMappingURL=babylon.bone.js.map
  30607. var BABYLON;
  30608. (function (BABYLON) {
  30609. var BoneIKController = (function () {
  30610. function BoneIKController(mesh, bone, options) {
  30611. this.targetPosition = BABYLON.Vector3.Zero();
  30612. this.poleTargetPosition = BABYLON.Vector3.Zero();
  30613. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  30614. this.poleAngle = 0;
  30615. this.slerpAmount = 1;
  30616. this._bone1Quat = BABYLON.Quaternion.Identity();
  30617. this._bone1Mat = BABYLON.Matrix.Identity();
  30618. this._bone2Ang = Math.PI;
  30619. this._maxAngle = Math.PI;
  30620. this._tmpVec1 = BABYLON.Vector3.Zero();
  30621. this._tmpVec2 = BABYLON.Vector3.Zero();
  30622. this._tmpVec3 = BABYLON.Vector3.Zero();
  30623. this._tmpVec4 = BABYLON.Vector3.Zero();
  30624. this._tmpVec5 = BABYLON.Vector3.Zero();
  30625. this._tmpMat1 = BABYLON.Matrix.Identity();
  30626. this._tmpMat2 = BABYLON.Matrix.Identity();
  30627. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  30628. this._rightHandedSystem = false;
  30629. this._bendAxis = BABYLON.Vector3.Right();
  30630. this._slerping = false;
  30631. this._bone2 = bone;
  30632. this._bone1 = bone.getParent();
  30633. this.mesh = mesh;
  30634. if (bone.getAbsoluteTransform().determinant() > 0) {
  30635. this._rightHandedSystem = true;
  30636. this._bendAxis.x = 0;
  30637. this._bendAxis.y = 0;
  30638. this._bendAxis.z = 1;
  30639. }
  30640. if (this._bone1.length) {
  30641. var boneScale1 = this._bone1.getScale();
  30642. var boneScale2 = this._bone2.getScale();
  30643. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  30644. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  30645. }
  30646. else if (this._bone1.children[0]) {
  30647. mesh.computeWorldMatrix(true);
  30648. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  30649. var pos2 = this._bone2.getAbsolutePosition(mesh);
  30650. var pos3 = this._bone1.getAbsolutePosition(mesh);
  30651. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  30652. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  30653. }
  30654. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  30655. this.maxAngle = Math.PI;
  30656. if (options) {
  30657. if (options.targetMesh) {
  30658. this.targetMesh = options.targetMesh;
  30659. this.targetMesh.computeWorldMatrix(true);
  30660. }
  30661. if (options.poleTargetMesh) {
  30662. this.poleTargetMesh = options.poleTargetMesh;
  30663. this.poleTargetMesh.computeWorldMatrix(true);
  30664. }
  30665. else if (options.poleTargetBone) {
  30666. this.poleTargetBone = options.poleTargetBone;
  30667. }
  30668. else if (this._bone1.getParent()) {
  30669. this.poleTargetBone = this._bone1.getParent();
  30670. }
  30671. if (options.poleTargetLocalOffset) {
  30672. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  30673. }
  30674. if (options.poleAngle) {
  30675. this.poleAngle = options.poleAngle;
  30676. }
  30677. if (options.bendAxis) {
  30678. this._bendAxis.copyFrom(options.bendAxis);
  30679. }
  30680. if (options.maxAngle) {
  30681. this.maxAngle = options.maxAngle;
  30682. }
  30683. if (options.slerpAmount) {
  30684. this.slerpAmount = options.slerpAmount;
  30685. }
  30686. }
  30687. }
  30688. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  30689. get: function () {
  30690. return this._maxAngle;
  30691. },
  30692. set: function (value) {
  30693. this._setMaxAngle(value);
  30694. },
  30695. enumerable: true,
  30696. configurable: true
  30697. });
  30698. BoneIKController.prototype._setMaxAngle = function (ang) {
  30699. if (ang < 0) {
  30700. ang = 0;
  30701. }
  30702. if (ang > Math.PI || ang == undefined) {
  30703. ang = Math.PI;
  30704. }
  30705. this._maxAngle = ang;
  30706. var a = this._bone1Length;
  30707. var b = this._bone2Length;
  30708. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  30709. };
  30710. BoneIKController.prototype.update = function () {
  30711. var bone1 = this._bone1;
  30712. var target = this.targetPosition;
  30713. var poleTarget = this.poleTargetPosition;
  30714. var mat1 = this._tmpMat1;
  30715. var mat2 = this._tmpMat2;
  30716. if (this.targetMesh) {
  30717. target.copyFrom(this.targetMesh.getAbsolutePosition());
  30718. }
  30719. if (this.poleTargetBone) {
  30720. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  30721. }
  30722. else if (this.poleTargetMesh) {
  30723. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  30724. }
  30725. var bonePos = this._tmpVec1;
  30726. var zaxis = this._tmpVec2;
  30727. var xaxis = this._tmpVec3;
  30728. var yaxis = this._tmpVec4;
  30729. var upAxis = this._tmpVec5;
  30730. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  30731. poleTarget.subtractToRef(bonePos, upAxis);
  30732. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  30733. upAxis.y = 1;
  30734. }
  30735. else {
  30736. upAxis.normalize();
  30737. }
  30738. target.subtractToRef(bonePos, yaxis);
  30739. yaxis.normalize();
  30740. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  30741. zaxis.normalize();
  30742. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  30743. xaxis.normalize();
  30744. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30745. var a = this._bone1Length;
  30746. var b = this._bone2Length;
  30747. var c = BABYLON.Vector3.Distance(bonePos, target);
  30748. if (this._maxReach > 0) {
  30749. c = Math.min(this._maxReach, c);
  30750. }
  30751. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  30752. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  30753. if (acosa > 1) {
  30754. acosa = 1;
  30755. }
  30756. if (acosb > 1) {
  30757. acosb = 1;
  30758. }
  30759. if (acosa < -1) {
  30760. acosa = -1;
  30761. }
  30762. if (acosb < -1) {
  30763. acosb = -1;
  30764. }
  30765. var angA = Math.acos(acosa);
  30766. var angB = Math.acos(acosb);
  30767. var angC = -angA - angB;
  30768. if (this._rightHandedSystem) {
  30769. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  30770. mat2.multiplyToRef(mat1, mat1);
  30771. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  30772. mat2.multiplyToRef(mat1, mat1);
  30773. }
  30774. else {
  30775. this._tmpVec1.copyFrom(this._bendAxis);
  30776. this._tmpVec1.x *= -1;
  30777. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  30778. mat2.multiplyToRef(mat1, mat1);
  30779. }
  30780. if (this.poleAngle) {
  30781. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  30782. mat1.multiplyToRef(mat2, mat1);
  30783. }
  30784. if (this.slerpAmount < 1) {
  30785. if (!this._slerping) {
  30786. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  30787. }
  30788. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  30789. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  30790. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  30791. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  30792. this._slerping = true;
  30793. }
  30794. else {
  30795. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30796. this._bone1Mat.copyFrom(mat1);
  30797. this._slerping = false;
  30798. }
  30799. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  30800. this._bone2Ang = angC;
  30801. };
  30802. return BoneIKController;
  30803. }());
  30804. BABYLON.BoneIKController = BoneIKController;
  30805. })(BABYLON || (BABYLON = {}));
  30806. //# sourceMappingURL=babylon.boneIKController.js.map
  30807. var BABYLON;
  30808. (function (BABYLON) {
  30809. var BoneLookController = (function () {
  30810. function BoneLookController(mesh, bone, target, options) {
  30811. this.upAxis = BABYLON.Vector3.Up();
  30812. this.adjustYaw = 0;
  30813. this.adjustPitch = 0;
  30814. this.adjustRoll = 0;
  30815. this._tmpVec1 = BABYLON.Vector3.Zero();
  30816. this._tmpVec2 = BABYLON.Vector3.Zero();
  30817. this._tmpVec3 = BABYLON.Vector3.Zero();
  30818. this._tmpVec4 = BABYLON.Vector3.Zero();
  30819. this._tmpMat1 = BABYLON.Matrix.Identity();
  30820. this._tmpMat2 = BABYLON.Matrix.Identity();
  30821. this.mesh = mesh;
  30822. this.bone = bone;
  30823. this.target = target;
  30824. if (options) {
  30825. if (options.adjustYaw) {
  30826. this.adjustYaw = options.adjustYaw;
  30827. }
  30828. if (options.adjustPitch) {
  30829. this.adjustPitch = options.adjustPitch;
  30830. }
  30831. if (options.adjustRoll) {
  30832. this.adjustRoll = options.adjustRoll;
  30833. }
  30834. }
  30835. }
  30836. BoneLookController.prototype.update = function () {
  30837. var bone = this.bone;
  30838. var target = this.target;
  30839. var bonePos = this._tmpVec1;
  30840. var zaxis = this._tmpVec2;
  30841. var xaxis = this._tmpVec3;
  30842. var yaxis = this._tmpVec4;
  30843. var mat1 = this._tmpMat1;
  30844. var mat2 = this._tmpMat2;
  30845. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  30846. target.subtractToRef(bonePos, zaxis);
  30847. zaxis.normalize();
  30848. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  30849. xaxis.normalize();
  30850. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  30851. yaxis.normalize();
  30852. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30853. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  30854. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  30855. mat2.multiplyToRef(mat1, mat1);
  30856. }
  30857. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30858. };
  30859. return BoneLookController;
  30860. }());
  30861. BABYLON.BoneLookController = BoneLookController;
  30862. })(BABYLON || (BABYLON = {}));
  30863. //# sourceMappingURL=babylon.boneLookController.js.map
  30864. var BABYLON;
  30865. (function (BABYLON) {
  30866. var Skeleton = (function () {
  30867. function Skeleton(name, id, scene) {
  30868. this.name = name;
  30869. this.id = id;
  30870. this.bones = new Array();
  30871. this.needInitialSkinMatrix = false;
  30872. this._isDirty = true;
  30873. this._meshesWithPoseMatrix = new Array();
  30874. this._identity = BABYLON.Matrix.Identity();
  30875. this._ranges = {};
  30876. this._lastAbsoluteTransformsUpdateId = -1;
  30877. this.bones = [];
  30878. this._scene = scene;
  30879. scene.skeletons.push(this);
  30880. //make sure it will recalculate the matrix next time prepare is called.
  30881. this._isDirty = true;
  30882. }
  30883. // Members
  30884. Skeleton.prototype.getTransformMatrices = function (mesh) {
  30885. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  30886. return mesh._bonesTransformMatrices;
  30887. }
  30888. if (!this._transformMatrices) {
  30889. this.prepare();
  30890. }
  30891. return this._transformMatrices;
  30892. };
  30893. Skeleton.prototype.getScene = function () {
  30894. return this._scene;
  30895. };
  30896. // Methods
  30897. /**
  30898. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30899. */
  30900. Skeleton.prototype.toString = function (fullDetails) {
  30901. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  30902. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30903. if (fullDetails) {
  30904. ret += ", Ranges: {";
  30905. var first = true;
  30906. for (var name_1 in this._ranges) {
  30907. if (first) {
  30908. ret += ", ";
  30909. first = false;
  30910. }
  30911. ret += name_1;
  30912. }
  30913. ret += "}";
  30914. }
  30915. return ret;
  30916. };
  30917. /**
  30918. * Get bone's index searching by name
  30919. * @param {string} name is bone's name to search for
  30920. * @return {number} Indice of the bone. Returns -1 if not found
  30921. */
  30922. Skeleton.prototype.getBoneIndexByName = function (name) {
  30923. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  30924. if (this.bones[boneIndex].name === name) {
  30925. return boneIndex;
  30926. }
  30927. }
  30928. return -1;
  30929. };
  30930. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  30931. // check name not already in use
  30932. if (!this._ranges[name]) {
  30933. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  30934. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  30935. if (this.bones[i].animations[0]) {
  30936. this.bones[i].animations[0].createRange(name, from, to);
  30937. }
  30938. }
  30939. }
  30940. };
  30941. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  30942. if (deleteFrames === void 0) { deleteFrames = true; }
  30943. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  30944. if (this.bones[i].animations[0]) {
  30945. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  30946. }
  30947. }
  30948. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30949. };
  30950. Skeleton.prototype.getAnimationRange = function (name) {
  30951. return this._ranges[name];
  30952. };
  30953. /**
  30954. * Returns as an Array, all AnimationRanges defined on this skeleton
  30955. */
  30956. Skeleton.prototype.getAnimationRanges = function () {
  30957. var animationRanges = [];
  30958. var name;
  30959. var i = 0;
  30960. for (name in this._ranges) {
  30961. animationRanges[i] = this._ranges[name];
  30962. i++;
  30963. }
  30964. return animationRanges;
  30965. };
  30966. /**
  30967. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  30968. */
  30969. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  30970. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30971. if (this._ranges[name] || !source.getAnimationRange(name)) {
  30972. return false;
  30973. }
  30974. var ret = true;
  30975. var frameOffset = this._getHighestAnimationFrame() + 1;
  30976. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  30977. var boneDict = {};
  30978. var sourceBones = source.bones;
  30979. var nBones;
  30980. var i;
  30981. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  30982. boneDict[sourceBones[i].name] = sourceBones[i];
  30983. }
  30984. if (this.bones.length !== sourceBones.length) {
  30985. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  30986. ret = false;
  30987. }
  30988. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  30989. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  30990. var boneName = this.bones[i].name;
  30991. var sourceBone = boneDict[boneName];
  30992. if (sourceBone) {
  30993. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  30994. }
  30995. else {
  30996. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  30997. ret = false;
  30998. }
  30999. }
  31000. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31001. var range = source.getAnimationRange(name);
  31002. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31003. return ret;
  31004. };
  31005. Skeleton.prototype.returnToRest = function () {
  31006. for (var index = 0; index < this.bones.length; index++) {
  31007. this.bones[index].returnToRest();
  31008. }
  31009. };
  31010. Skeleton.prototype._getHighestAnimationFrame = function () {
  31011. var ret = 0;
  31012. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31013. if (this.bones[i].animations[0]) {
  31014. var highest = this.bones[i].animations[0].getHighestFrame();
  31015. if (ret < highest) {
  31016. ret = highest;
  31017. }
  31018. }
  31019. }
  31020. return ret;
  31021. };
  31022. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31023. var range = this.getAnimationRange(name);
  31024. if (!range) {
  31025. return null;
  31026. }
  31027. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31028. };
  31029. Skeleton.prototype._markAsDirty = function () {
  31030. this._isDirty = true;
  31031. };
  31032. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31033. this._meshesWithPoseMatrix.push(mesh);
  31034. };
  31035. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31036. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31037. if (index > -1) {
  31038. this._meshesWithPoseMatrix.splice(index, 1);
  31039. }
  31040. };
  31041. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31042. for (var index = 0; index < this.bones.length; index++) {
  31043. var bone = this.bones[index];
  31044. var parentBone = bone.getParent();
  31045. if (parentBone) {
  31046. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31047. }
  31048. else {
  31049. if (initialSkinMatrix) {
  31050. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31051. }
  31052. else {
  31053. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31054. }
  31055. }
  31056. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31057. }
  31058. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31059. };
  31060. Skeleton.prototype.prepare = function () {
  31061. if (!this._isDirty) {
  31062. return;
  31063. }
  31064. if (this.needInitialSkinMatrix) {
  31065. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31066. var mesh = this._meshesWithPoseMatrix[index];
  31067. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31068. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31069. }
  31070. var poseMatrix = mesh.getPoseMatrix();
  31071. // Prepare bones
  31072. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31073. var bone = this.bones[boneIndex];
  31074. if (!bone.getParent()) {
  31075. var matrix = bone.getBaseMatrix();
  31076. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31077. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31078. }
  31079. }
  31080. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31081. }
  31082. }
  31083. else {
  31084. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31085. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31086. }
  31087. this._computeTransformMatrices(this._transformMatrices, null);
  31088. }
  31089. this._isDirty = false;
  31090. this._scene._activeBones.addCount(this.bones.length, false);
  31091. };
  31092. Skeleton.prototype.getAnimatables = function () {
  31093. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31094. this._animatables = [];
  31095. for (var index = 0; index < this.bones.length; index++) {
  31096. this._animatables.push(this.bones[index]);
  31097. }
  31098. }
  31099. return this._animatables;
  31100. };
  31101. Skeleton.prototype.clone = function (name, id) {
  31102. var result = new Skeleton(name, id || name, this._scene);
  31103. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31104. for (var index = 0; index < this.bones.length; index++) {
  31105. var source = this.bones[index];
  31106. var parentBone = null;
  31107. if (source.getParent()) {
  31108. var parentIndex = this.bones.indexOf(source.getParent());
  31109. parentBone = result.bones[parentIndex];
  31110. }
  31111. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31112. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31113. }
  31114. if (this._ranges) {
  31115. result._ranges = {};
  31116. for (var rangeName in this._ranges) {
  31117. result._ranges[rangeName] = this._ranges[rangeName].clone();
  31118. }
  31119. }
  31120. this._isDirty = true;
  31121. return result;
  31122. };
  31123. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  31124. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  31125. this.bones.forEach(function (bone) {
  31126. bone.animations.forEach(function (animation) {
  31127. animation.enableBlending = true;
  31128. animation.blendingSpeed = blendingSpeed;
  31129. });
  31130. });
  31131. };
  31132. Skeleton.prototype.dispose = function () {
  31133. this._meshesWithPoseMatrix = [];
  31134. // Animations
  31135. this.getScene().stopAnimation(this);
  31136. // Remove from scene
  31137. this.getScene().removeSkeleton(this);
  31138. };
  31139. Skeleton.prototype.serialize = function () {
  31140. var serializationObject = {};
  31141. serializationObject.name = this.name;
  31142. serializationObject.id = this.id;
  31143. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  31144. serializationObject.bones = [];
  31145. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31146. for (var index = 0; index < this.bones.length; index++) {
  31147. var bone = this.bones[index];
  31148. var serializedBone = {
  31149. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  31150. name: bone.name,
  31151. matrix: bone.getLocalMatrix().toArray(),
  31152. rest: bone.getRestPose().toArray()
  31153. };
  31154. serializationObject.bones.push(serializedBone);
  31155. if (bone.length) {
  31156. serializedBone.length = bone.length;
  31157. }
  31158. if (bone.animations && bone.animations.length > 0) {
  31159. serializedBone.animation = bone.animations[0].serialize();
  31160. }
  31161. serializationObject.ranges = [];
  31162. for (var name in this._ranges) {
  31163. var range = {};
  31164. range.name = name;
  31165. range.from = this._ranges[name].from;
  31166. range.to = this._ranges[name].to;
  31167. serializationObject.ranges.push(range);
  31168. }
  31169. }
  31170. return serializationObject;
  31171. };
  31172. Skeleton.Parse = function (parsedSkeleton, scene) {
  31173. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  31174. if (parsedSkeleton.dimensionsAtRest) {
  31175. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  31176. }
  31177. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  31178. var index;
  31179. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  31180. var parsedBone = parsedSkeleton.bones[index];
  31181. var parentBone = null;
  31182. if (parsedBone.parentBoneIndex > -1) {
  31183. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  31184. }
  31185. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  31186. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  31187. if (parsedBone.length) {
  31188. bone.length = parsedBone.length;
  31189. }
  31190. if (parsedBone.animation) {
  31191. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  31192. }
  31193. }
  31194. // placed after bones, so createAnimationRange can cascade down
  31195. if (parsedSkeleton.ranges) {
  31196. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  31197. var data = parsedSkeleton.ranges[index];
  31198. skeleton.createAnimationRange(data.name, data.from, data.to);
  31199. }
  31200. }
  31201. return skeleton;
  31202. };
  31203. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  31204. if (forceUpdate === void 0) { forceUpdate = false; }
  31205. var renderId = this._scene.getRenderId();
  31206. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  31207. this.bones[0].computeAbsoluteTransforms();
  31208. this._lastAbsoluteTransformsUpdateId = renderId;
  31209. }
  31210. };
  31211. Skeleton.prototype.getPoseMatrix = function () {
  31212. var poseMatrix;
  31213. if (this._meshesWithPoseMatrix.length > 0) {
  31214. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  31215. }
  31216. return poseMatrix;
  31217. };
  31218. return Skeleton;
  31219. }());
  31220. BABYLON.Skeleton = Skeleton;
  31221. })(BABYLON || (BABYLON = {}));
  31222. //# sourceMappingURL=babylon.skeleton.js.map
  31223. var BABYLON;
  31224. (function (BABYLON) {
  31225. var PostProcess = (function () {
  31226. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  31227. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  31228. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31229. this.name = name;
  31230. this.width = -1;
  31231. this.height = -1;
  31232. /*
  31233. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  31234. Can only be used on a single postprocess or on the last one of a chain.
  31235. */
  31236. this.enablePixelPerfectMode = false;
  31237. this._reusable = false;
  31238. this._textures = new BABYLON.SmartArray(2);
  31239. this._currentRenderTextureInd = 0;
  31240. this._scaleRatio = new BABYLON.Vector2(1, 1);
  31241. // Events
  31242. /**
  31243. * An event triggered when the postprocess is activated.
  31244. * @type {BABYLON.Observable}
  31245. */
  31246. this.onActivateObservable = new BABYLON.Observable();
  31247. /**
  31248. * An event triggered when the postprocess changes its size.
  31249. * @type {BABYLON.Observable}
  31250. */
  31251. this.onSizeChangedObservable = new BABYLON.Observable();
  31252. /**
  31253. * An event triggered when the postprocess applies its effect.
  31254. * @type {BABYLON.Observable}
  31255. */
  31256. this.onApplyObservable = new BABYLON.Observable();
  31257. /**
  31258. * An event triggered before rendering the postprocess
  31259. * @type {BABYLON.Observable}
  31260. */
  31261. this.onBeforeRenderObservable = new BABYLON.Observable();
  31262. /**
  31263. * An event triggered after rendering the postprocess
  31264. * @type {BABYLON.Observable}
  31265. */
  31266. this.onAfterRenderObservable = new BABYLON.Observable();
  31267. if (camera != null) {
  31268. this._camera = camera;
  31269. this._scene = camera.getScene();
  31270. camera.attachPostProcess(this);
  31271. this._engine = this._scene.getEngine();
  31272. }
  31273. else {
  31274. this._engine = engine;
  31275. }
  31276. this._options = options;
  31277. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  31278. this._reusable = reusable || false;
  31279. this._textureType = textureType;
  31280. this._samplers = samplers || [];
  31281. this._samplers.push("textureSampler");
  31282. this._fragmentUrl = fragmentUrl;
  31283. this._parameters = parameters || [];
  31284. this._parameters.push("scale");
  31285. this.updateEffect(defines);
  31286. }
  31287. Object.defineProperty(PostProcess.prototype, "onActivate", {
  31288. set: function (callback) {
  31289. if (this._onActivateObserver) {
  31290. this.onActivateObservable.remove(this._onActivateObserver);
  31291. }
  31292. this._onActivateObserver = this.onActivateObservable.add(callback);
  31293. },
  31294. enumerable: true,
  31295. configurable: true
  31296. });
  31297. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  31298. set: function (callback) {
  31299. if (this._onSizeChangedObserver) {
  31300. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  31301. }
  31302. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  31303. },
  31304. enumerable: true,
  31305. configurable: true
  31306. });
  31307. Object.defineProperty(PostProcess.prototype, "onApply", {
  31308. set: function (callback) {
  31309. if (this._onApplyObserver) {
  31310. this.onApplyObservable.remove(this._onApplyObserver);
  31311. }
  31312. this._onApplyObserver = this.onApplyObservable.add(callback);
  31313. },
  31314. enumerable: true,
  31315. configurable: true
  31316. });
  31317. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  31318. set: function (callback) {
  31319. if (this._onBeforeRenderObserver) {
  31320. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31321. }
  31322. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31323. },
  31324. enumerable: true,
  31325. configurable: true
  31326. });
  31327. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  31328. set: function (callback) {
  31329. if (this._onAfterRenderObserver) {
  31330. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31331. }
  31332. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31333. },
  31334. enumerable: true,
  31335. configurable: true
  31336. });
  31337. PostProcess.prototype.updateEffect = function (defines) {
  31338. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  31339. };
  31340. PostProcess.prototype.isReusable = function () {
  31341. return this._reusable;
  31342. };
  31343. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  31344. PostProcess.prototype.markTextureDirty = function () {
  31345. this.width = -1;
  31346. };
  31347. PostProcess.prototype.activate = function (camera, sourceTexture) {
  31348. camera = camera || this._camera;
  31349. var scene = camera.getScene();
  31350. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  31351. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  31352. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  31353. var desiredWidth = this._options.width || requiredWidth;
  31354. var desiredHeight = this._options.height || requiredHeight;
  31355. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31356. if (!this._options.width) {
  31357. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  31358. }
  31359. if (!this._options.height) {
  31360. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  31361. }
  31362. }
  31363. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  31364. if (this._textures.length > 0) {
  31365. for (var i = 0; i < this._textures.length; i++) {
  31366. this._engine._releaseTexture(this._textures.data[i]);
  31367. }
  31368. this._textures.reset();
  31369. }
  31370. this.width = desiredWidth;
  31371. this.height = desiredHeight;
  31372. var textureSize = { width: this.width, height: this.height };
  31373. var textureOptions = {
  31374. generateMipMaps: false,
  31375. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  31376. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  31377. samplingMode: this.renderTargetSamplingMode,
  31378. type: this._textureType
  31379. };
  31380. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31381. if (this._reusable) {
  31382. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31383. }
  31384. this.onSizeChangedObservable.notifyObservers(this);
  31385. }
  31386. if (this.enablePixelPerfectMode) {
  31387. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  31388. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  31389. }
  31390. else {
  31391. this._scaleRatio.copyFromFloats(1, 1);
  31392. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  31393. }
  31394. this.onActivateObservable.notifyObservers(camera);
  31395. // Clear
  31396. if (this.clearColor) {
  31397. this._engine.clear(this.clearColor, true, true, true);
  31398. }
  31399. else {
  31400. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  31401. }
  31402. if (this._reusable) {
  31403. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  31404. }
  31405. };
  31406. Object.defineProperty(PostProcess.prototype, "isSupported", {
  31407. get: function () {
  31408. return this._effect.isSupported;
  31409. },
  31410. enumerable: true,
  31411. configurable: true
  31412. });
  31413. PostProcess.prototype.apply = function () {
  31414. // Check
  31415. if (!this._effect.isReady())
  31416. return null;
  31417. // States
  31418. this._engine.enableEffect(this._effect);
  31419. this._engine.setState(false);
  31420. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31421. this._engine.setDepthBuffer(false);
  31422. this._engine.setDepthWrite(false);
  31423. // Texture
  31424. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  31425. // Parameters
  31426. this._effect.setVector2("scale", this._scaleRatio);
  31427. this.onApplyObservable.notifyObservers(this._effect);
  31428. return this._effect;
  31429. };
  31430. PostProcess.prototype.dispose = function (camera) {
  31431. camera = camera || this._camera;
  31432. if (this._textures.length > 0) {
  31433. for (var i = 0; i < this._textures.length; i++) {
  31434. this._engine._releaseTexture(this._textures.data[i]);
  31435. }
  31436. this._textures.reset();
  31437. }
  31438. if (!camera) {
  31439. return;
  31440. }
  31441. camera.detachPostProcess(this);
  31442. var index = camera._postProcesses.indexOf(this);
  31443. if (index === 0 && camera._postProcesses.length > 0) {
  31444. this._camera._postProcesses[0].markTextureDirty();
  31445. }
  31446. this.onActivateObservable.clear();
  31447. this.onAfterRenderObservable.clear();
  31448. this.onApplyObservable.clear();
  31449. this.onBeforeRenderObservable.clear();
  31450. this.onSizeChangedObservable.clear();
  31451. };
  31452. return PostProcess;
  31453. }());
  31454. BABYLON.PostProcess = PostProcess;
  31455. })(BABYLON || (BABYLON = {}));
  31456. //# sourceMappingURL=babylon.postProcess.js.map
  31457. var BABYLON;
  31458. (function (BABYLON) {
  31459. var PostProcessManager = (function () {
  31460. function PostProcessManager(scene) {
  31461. this._vertexBuffers = {};
  31462. this._scene = scene;
  31463. }
  31464. PostProcessManager.prototype._prepareBuffers = function () {
  31465. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31466. return;
  31467. }
  31468. // VBO
  31469. var vertices = [];
  31470. vertices.push(1, 1);
  31471. vertices.push(-1, 1);
  31472. vertices.push(-1, -1);
  31473. vertices.push(1, -1);
  31474. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31475. // Indices
  31476. var indices = [];
  31477. indices.push(0);
  31478. indices.push(1);
  31479. indices.push(2);
  31480. indices.push(0);
  31481. indices.push(2);
  31482. indices.push(3);
  31483. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31484. };
  31485. // Methods
  31486. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  31487. var postProcesses = this._scene.activeCamera._postProcesses;
  31488. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31489. return false;
  31490. }
  31491. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  31492. return true;
  31493. };
  31494. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  31495. var engine = this._scene.getEngine();
  31496. for (var index = 0; index < postProcesses.length; index++) {
  31497. if (index < postProcesses.length - 1) {
  31498. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31499. }
  31500. else {
  31501. if (targetTexture) {
  31502. engine.bindFramebuffer(targetTexture);
  31503. }
  31504. else {
  31505. engine.restoreDefaultFramebuffer();
  31506. }
  31507. }
  31508. var pp = postProcesses[index];
  31509. var effect = pp.apply();
  31510. if (effect) {
  31511. pp.onBeforeRenderObservable.notifyObservers(effect);
  31512. // VBOs
  31513. this._prepareBuffers();
  31514. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31515. // Draw order
  31516. engine.draw(true, 0, 6);
  31517. pp.onAfterRenderObservable.notifyObservers(effect);
  31518. }
  31519. }
  31520. // Restore depth buffer
  31521. engine.setDepthBuffer(true);
  31522. engine.setDepthWrite(true);
  31523. };
  31524. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  31525. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  31526. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31527. return;
  31528. }
  31529. var engine = this._scene.getEngine();
  31530. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31531. if (index < len - 1) {
  31532. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31533. }
  31534. else {
  31535. if (targetTexture) {
  31536. engine.bindFramebuffer(targetTexture, faceIndex);
  31537. }
  31538. else {
  31539. engine.restoreDefaultFramebuffer();
  31540. }
  31541. }
  31542. if (doNotPresent) {
  31543. break;
  31544. }
  31545. var pp = postProcesses[index];
  31546. var effect = pp.apply();
  31547. if (effect) {
  31548. pp.onBeforeRenderObservable.notifyObservers(effect);
  31549. // VBOs
  31550. this._prepareBuffers();
  31551. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31552. // Draw order
  31553. engine.draw(true, 0, 6);
  31554. pp.onAfterRenderObservable.notifyObservers(effect);
  31555. }
  31556. }
  31557. // Restore depth buffer
  31558. engine.setDepthBuffer(true);
  31559. engine.setDepthWrite(true);
  31560. };
  31561. PostProcessManager.prototype.dispose = function () {
  31562. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31563. if (buffer) {
  31564. buffer.dispose();
  31565. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31566. }
  31567. if (this._indexBuffer) {
  31568. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31569. this._indexBuffer = null;
  31570. }
  31571. };
  31572. return PostProcessManager;
  31573. }());
  31574. BABYLON.PostProcessManager = PostProcessManager;
  31575. })(BABYLON || (BABYLON = {}));
  31576. //# sourceMappingURL=babylon.postProcessManager.js.map
  31577. var BABYLON;
  31578. (function (BABYLON) {
  31579. var PassPostProcess = (function (_super) {
  31580. __extends(PassPostProcess, _super);
  31581. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  31582. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  31583. }
  31584. return PassPostProcess;
  31585. }(BABYLON.PostProcess));
  31586. BABYLON.PassPostProcess = PassPostProcess;
  31587. })(BABYLON || (BABYLON = {}));
  31588. //# sourceMappingURL=babylon.passPostProcess.js.map
  31589. var BABYLON;
  31590. (function (BABYLON) {
  31591. /**
  31592. * This is a holder class for the physics joint created by the physics plugin.
  31593. * It holds a set of functions to control the underlying joint.
  31594. */
  31595. var PhysicsJoint = (function () {
  31596. function PhysicsJoint(type, jointData) {
  31597. this.type = type;
  31598. this.jointData = jointData;
  31599. jointData.nativeParams = jointData.nativeParams || {};
  31600. }
  31601. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  31602. get: function () {
  31603. return this._physicsJoint;
  31604. },
  31605. set: function (newJoint) {
  31606. if (this._physicsJoint) {
  31607. }
  31608. this._physicsJoint = newJoint;
  31609. },
  31610. enumerable: true,
  31611. configurable: true
  31612. });
  31613. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  31614. set: function (physicsPlugin) {
  31615. this._physicsPlugin = physicsPlugin;
  31616. },
  31617. enumerable: true,
  31618. configurable: true
  31619. });
  31620. /**
  31621. * Execute a function that is physics-plugin specific.
  31622. * @param {Function} func the function that will be executed.
  31623. * It accepts two parameters: the physics world and the physics joint.
  31624. */
  31625. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  31626. func(this._physicsPlugin.world, this._physicsJoint);
  31627. };
  31628. //TODO check if the native joints are the same
  31629. //Joint Types
  31630. PhysicsJoint.DistanceJoint = 0;
  31631. PhysicsJoint.HingeJoint = 1;
  31632. PhysicsJoint.BallAndSocketJoint = 2;
  31633. PhysicsJoint.WheelJoint = 3;
  31634. PhysicsJoint.SliderJoint = 4;
  31635. //OIMO
  31636. PhysicsJoint.PrismaticJoint = 5;
  31637. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  31638. PhysicsJoint.UniversalJoint = 6;
  31639. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  31640. //Cannon
  31641. //Similar to a Ball-Joint. Different in params
  31642. PhysicsJoint.PointToPointJoint = 8;
  31643. //Cannon only at the moment
  31644. PhysicsJoint.SpringJoint = 9;
  31645. PhysicsJoint.LockJoint = 10;
  31646. return PhysicsJoint;
  31647. }());
  31648. BABYLON.PhysicsJoint = PhysicsJoint;
  31649. /**
  31650. * A class representing a physics distance joint.
  31651. */
  31652. var DistanceJoint = (function (_super) {
  31653. __extends(DistanceJoint, _super);
  31654. function DistanceJoint(jointData) {
  31655. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  31656. }
  31657. /**
  31658. * Update the predefined distance.
  31659. */
  31660. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  31661. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  31662. };
  31663. return DistanceJoint;
  31664. }(PhysicsJoint));
  31665. BABYLON.DistanceJoint = DistanceJoint;
  31666. var MotorEnabledJoint = (function (_super) {
  31667. __extends(MotorEnabledJoint, _super);
  31668. function MotorEnabledJoint(type, jointData) {
  31669. _super.call(this, type, jointData);
  31670. }
  31671. /**
  31672. * Set the motor values.
  31673. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31674. * @param {number} force the force to apply
  31675. * @param {number} maxForce max force for this motor.
  31676. */
  31677. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  31678. this._physicsPlugin.setMotor(this, force, maxForce);
  31679. };
  31680. /**
  31681. * Set the motor's limits.
  31682. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31683. */
  31684. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31685. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31686. };
  31687. return MotorEnabledJoint;
  31688. }(PhysicsJoint));
  31689. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  31690. /**
  31691. * This class represents a single hinge physics joint
  31692. */
  31693. var HingeJoint = (function (_super) {
  31694. __extends(HingeJoint, _super);
  31695. function HingeJoint(jointData) {
  31696. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  31697. }
  31698. /**
  31699. * Set the motor values.
  31700. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31701. * @param {number} force the force to apply
  31702. * @param {number} maxForce max force for this motor.
  31703. */
  31704. HingeJoint.prototype.setMotor = function (force, maxForce) {
  31705. this._physicsPlugin.setMotor(this, force, maxForce);
  31706. };
  31707. /**
  31708. * Set the motor's limits.
  31709. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31710. */
  31711. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31712. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31713. };
  31714. return HingeJoint;
  31715. }(MotorEnabledJoint));
  31716. BABYLON.HingeJoint = HingeJoint;
  31717. /**
  31718. * This class represents a dual hinge physics joint (same as wheel joint)
  31719. */
  31720. var Hinge2Joint = (function (_super) {
  31721. __extends(Hinge2Joint, _super);
  31722. function Hinge2Joint(jointData) {
  31723. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  31724. }
  31725. /**
  31726. * Set the motor values.
  31727. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31728. * @param {number} force the force to apply
  31729. * @param {number} maxForce max force for this motor.
  31730. * @param {motorIndex} the motor's index, 0 or 1.
  31731. */
  31732. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  31733. if (motorIndex === void 0) { motorIndex = 0; }
  31734. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  31735. };
  31736. /**
  31737. * Set the motor limits.
  31738. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31739. * @param {number} upperLimit the upper limit
  31740. * @param {number} lowerLimit lower limit
  31741. * @param {motorIndex} the motor's index, 0 or 1.
  31742. */
  31743. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  31744. if (motorIndex === void 0) { motorIndex = 0; }
  31745. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  31746. };
  31747. return Hinge2Joint;
  31748. }(MotorEnabledJoint));
  31749. BABYLON.Hinge2Joint = Hinge2Joint;
  31750. })(BABYLON || (BABYLON = {}));
  31751. //# sourceMappingURL=babylon.physicsJoint.js.map
  31752. var BABYLON;
  31753. (function (BABYLON) {
  31754. var PhysicsImpostor = (function () {
  31755. function PhysicsImpostor(object, type, _options, _scene) {
  31756. var _this = this;
  31757. if (_options === void 0) { _options = { mass: 0 }; }
  31758. this.object = object;
  31759. this.type = type;
  31760. this._options = _options;
  31761. this._scene = _scene;
  31762. this._bodyUpdateRequired = false;
  31763. this._onBeforePhysicsStepCallbacks = new Array();
  31764. this._onAfterPhysicsStepCallbacks = new Array();
  31765. this._onPhysicsCollideCallbacks = [];
  31766. this._deltaPosition = BABYLON.Vector3.Zero();
  31767. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  31768. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  31769. /**
  31770. * this function is executed by the physics engine.
  31771. */
  31772. this.beforeStep = function () {
  31773. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  31774. //conjugate deltaRotation
  31775. if (_this._deltaRotationConjugated) {
  31776. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  31777. }
  31778. else {
  31779. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  31780. }
  31781. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  31782. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  31783. func(_this);
  31784. });
  31785. };
  31786. /**
  31787. * this function is executed by the physics engine.
  31788. */
  31789. this.afterStep = function () {
  31790. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  31791. func(_this);
  31792. });
  31793. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  31794. _this.object.position.addInPlace(_this._deltaPosition);
  31795. if (_this._deltaRotation) {
  31796. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  31797. }
  31798. };
  31799. //event and body object due to cannon's event-based architecture.
  31800. this.onCollide = function (e) {
  31801. if (!_this._onPhysicsCollideCallbacks.length)
  31802. return;
  31803. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  31804. if (otherImpostor) {
  31805. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  31806. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  31807. }).forEach(function (obj) {
  31808. obj.callback(_this, otherImpostor);
  31809. });
  31810. }
  31811. };
  31812. //sanity check!
  31813. if (!this.object) {
  31814. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  31815. return;
  31816. }
  31817. //legacy support for old syntax.
  31818. if (!this._scene && object.getScene) {
  31819. this._scene = object.getScene();
  31820. }
  31821. this._physicsEngine = this._scene.getPhysicsEngine();
  31822. if (!this._physicsEngine) {
  31823. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  31824. }
  31825. else {
  31826. //set the object's quaternion, if not set
  31827. if (!this.object.rotationQuaternion) {
  31828. if (this.object.rotation) {
  31829. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  31830. }
  31831. else {
  31832. this.object.rotationQuaternion = new BABYLON.Quaternion();
  31833. }
  31834. }
  31835. //default options params
  31836. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  31837. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  31838. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  31839. this._joints = [];
  31840. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  31841. if (!this.object.parent) {
  31842. this._init();
  31843. }
  31844. }
  31845. }
  31846. /**
  31847. * This function will completly initialize this impostor.
  31848. * It will create a new body - but only if this mesh has no parent.
  31849. * If it has, this impostor will not be used other than to define the impostor
  31850. * of the child mesh.
  31851. */
  31852. PhysicsImpostor.prototype._init = function () {
  31853. this._physicsEngine.removeImpostor(this);
  31854. this.physicsBody = null;
  31855. this._parent = this._parent || this._getPhysicsParent();
  31856. if (!this.parent) {
  31857. this._physicsEngine.addImpostor(this);
  31858. }
  31859. };
  31860. PhysicsImpostor.prototype._getPhysicsParent = function () {
  31861. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  31862. var parentMesh = this.object.parent;
  31863. return parentMesh.physicsImpostor;
  31864. }
  31865. return;
  31866. };
  31867. /**
  31868. * Should a new body be generated.
  31869. */
  31870. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  31871. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  31872. };
  31873. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  31874. this.forceUpdate();
  31875. };
  31876. /**
  31877. * Force a regeneration of this or the parent's impostor's body.
  31878. * Use under cautious - This will remove all joints already implemented.
  31879. */
  31880. PhysicsImpostor.prototype.forceUpdate = function () {
  31881. this._init();
  31882. if (this.parent) {
  31883. this.parent.forceUpdate();
  31884. }
  31885. };
  31886. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  31887. /*public get mesh(): AbstractMesh {
  31888. return this._mesh;
  31889. }*/
  31890. /**
  31891. * Gets the body that holds this impostor. Either its own, or its parent.
  31892. */
  31893. get: function () {
  31894. return this._parent ? this._parent.physicsBody : this._physicsBody;
  31895. },
  31896. /**
  31897. * Set the physics body. Used mainly by the physics engine/plugin
  31898. */
  31899. set: function (physicsBody) {
  31900. if (this._physicsBody) {
  31901. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  31902. }
  31903. this._physicsBody = physicsBody;
  31904. this.resetUpdateFlags();
  31905. },
  31906. enumerable: true,
  31907. configurable: true
  31908. });
  31909. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  31910. get: function () {
  31911. return this._parent;
  31912. },
  31913. set: function (value) {
  31914. this._parent = value;
  31915. },
  31916. enumerable: true,
  31917. configurable: true
  31918. });
  31919. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  31920. this._bodyUpdateRequired = false;
  31921. };
  31922. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  31923. if (this.object.getBoundingInfo) {
  31924. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  31925. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  31926. }
  31927. else {
  31928. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  31929. }
  31930. };
  31931. PhysicsImpostor.prototype.getObjectCenter = function () {
  31932. if (this.object.getBoundingInfo) {
  31933. return this.object.getBoundingInfo().boundingBox.center;
  31934. }
  31935. else {
  31936. return this.object.position;
  31937. }
  31938. };
  31939. /**
  31940. * Get a specific parametes from the options parameter.
  31941. */
  31942. PhysicsImpostor.prototype.getParam = function (paramName) {
  31943. return this._options[paramName];
  31944. };
  31945. /**
  31946. * Sets a specific parameter in the options given to the physics plugin
  31947. */
  31948. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  31949. this._options[paramName] = value;
  31950. this._bodyUpdateRequired = true;
  31951. };
  31952. /**
  31953. * Specifically change the body's mass option. Won't recreate the physics body object
  31954. */
  31955. PhysicsImpostor.prototype.setMass = function (mass) {
  31956. if (this.getParam("mass") !== mass) {
  31957. this.setParam("mass", mass);
  31958. }
  31959. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  31960. };
  31961. PhysicsImpostor.prototype.getLinearVelocity = function () {
  31962. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  31963. };
  31964. /**
  31965. * Set the body's linear velocity.
  31966. */
  31967. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  31968. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  31969. };
  31970. PhysicsImpostor.prototype.getAngularVelocity = function () {
  31971. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  31972. };
  31973. /**
  31974. * Set the body's linear velocity.
  31975. */
  31976. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  31977. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  31978. };
  31979. /**
  31980. * Execute a function with the physics plugin native code.
  31981. * Provide a function the will have two variables - the world object and the physics body object.
  31982. */
  31983. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  31984. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  31985. };
  31986. /**
  31987. * Register a function that will be executed before the physics world is stepping forward.
  31988. */
  31989. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  31990. this._onBeforePhysicsStepCallbacks.push(func);
  31991. };
  31992. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  31993. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  31994. if (index > -1) {
  31995. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  31996. }
  31997. else {
  31998. BABYLON.Tools.Warn("Function to remove was not found");
  31999. }
  32000. };
  32001. /**
  32002. * Register a function that will be executed after the physics step
  32003. */
  32004. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32005. this._onAfterPhysicsStepCallbacks.push(func);
  32006. };
  32007. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32008. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32009. if (index > -1) {
  32010. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32011. }
  32012. else {
  32013. BABYLON.Tools.Warn("Function to remove was not found");
  32014. }
  32015. };
  32016. /**
  32017. * register a function that will be executed when this impostor collides against a different body.
  32018. */
  32019. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32020. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32021. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32022. };
  32023. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32024. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32025. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32026. if (index > -1) {
  32027. this._onPhysicsCollideCallbacks.splice(index, 1);
  32028. }
  32029. else {
  32030. BABYLON.Tools.Warn("Function to remove was not found");
  32031. }
  32032. };
  32033. /**
  32034. * Apply a force
  32035. */
  32036. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32037. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32038. };
  32039. /**
  32040. * Apply an impulse
  32041. */
  32042. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32043. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32044. };
  32045. /**
  32046. * A help function to create a joint.
  32047. */
  32048. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32049. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32050. this.addJoint(otherImpostor, joint);
  32051. };
  32052. /**
  32053. * Add a joint to this impostor with a different impostor.
  32054. */
  32055. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32056. this._joints.push({
  32057. otherImpostor: otherImpostor,
  32058. joint: joint
  32059. });
  32060. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32061. };
  32062. /**
  32063. * Will keep this body still, in a sleep mode.
  32064. */
  32065. PhysicsImpostor.prototype.sleep = function () {
  32066. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32067. };
  32068. /**
  32069. * Wake the body up.
  32070. */
  32071. PhysicsImpostor.prototype.wakeUp = function () {
  32072. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32073. };
  32074. PhysicsImpostor.prototype.clone = function (newObject) {
  32075. if (!newObject)
  32076. return null;
  32077. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32078. };
  32079. PhysicsImpostor.prototype.dispose = function () {
  32080. var _this = this;
  32081. //no dispose if no physics engine is available.
  32082. if (!this._physicsEngine) {
  32083. return;
  32084. }
  32085. this._joints.forEach(function (j) {
  32086. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32087. });
  32088. //dispose the physics body
  32089. this._physicsEngine.removeImpostor(this);
  32090. if (this.parent) {
  32091. this.parent.forceUpdate();
  32092. }
  32093. else {
  32094. }
  32095. };
  32096. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32097. this._deltaPosition.copyFrom(position);
  32098. };
  32099. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32100. if (!this._deltaRotation) {
  32101. this._deltaRotation = new BABYLON.Quaternion();
  32102. }
  32103. this._deltaRotation.copyFrom(rotation);
  32104. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32105. };
  32106. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32107. //Impostor types
  32108. PhysicsImpostor.NoImpostor = 0;
  32109. PhysicsImpostor.SphereImpostor = 1;
  32110. PhysicsImpostor.BoxImpostor = 2;
  32111. PhysicsImpostor.PlaneImpostor = 3;
  32112. PhysicsImpostor.MeshImpostor = 4;
  32113. PhysicsImpostor.CylinderImpostor = 7;
  32114. PhysicsImpostor.ParticleImpostor = 8;
  32115. PhysicsImpostor.HeightmapImpostor = 9;
  32116. return PhysicsImpostor;
  32117. }());
  32118. BABYLON.PhysicsImpostor = PhysicsImpostor;
  32119. })(BABYLON || (BABYLON = {}));
  32120. //# sourceMappingURL=babylon.physicsImpostor.js.map
  32121. var BABYLON;
  32122. (function (BABYLON) {
  32123. var PhysicsEngine = (function () {
  32124. function PhysicsEngine(gravity, _physicsPlugin) {
  32125. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  32126. this._physicsPlugin = _physicsPlugin;
  32127. //new methods and parameters
  32128. this._impostors = [];
  32129. this._joints = [];
  32130. if (!this._physicsPlugin.isSupported()) {
  32131. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  32132. + "Please make sure it is included.");
  32133. }
  32134. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  32135. this.setGravity(gravity);
  32136. this.setTimeStep();
  32137. }
  32138. PhysicsEngine.prototype.setGravity = function (gravity) {
  32139. this.gravity = gravity;
  32140. this._physicsPlugin.setGravity(this.gravity);
  32141. };
  32142. /**
  32143. * Set the time step of the physics engine.
  32144. * default is 1/60.
  32145. * To slow it down, enter 1/600 for example.
  32146. * To speed it up, 1/30
  32147. * @param {number} newTimeStep the new timestep to apply to this world.
  32148. */
  32149. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  32150. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  32151. this._physicsPlugin.setTimeStep(newTimeStep);
  32152. };
  32153. PhysicsEngine.prototype.dispose = function () {
  32154. this._impostors.forEach(function (impostor) {
  32155. impostor.dispose();
  32156. });
  32157. this._physicsPlugin.dispose();
  32158. };
  32159. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  32160. return this._physicsPlugin.name;
  32161. };
  32162. /**
  32163. * Adding a new impostor for the impostor tracking.
  32164. * This will be done by the impostor itself.
  32165. * @param {PhysicsImpostor} impostor the impostor to add
  32166. */
  32167. PhysicsEngine.prototype.addImpostor = function (impostor) {
  32168. impostor.uniqueId = this._impostors.push(impostor);
  32169. //if no parent, generate the body
  32170. if (!impostor.parent) {
  32171. this._physicsPlugin.generatePhysicsBody(impostor);
  32172. }
  32173. };
  32174. /**
  32175. * Remove an impostor from the engine.
  32176. * This impostor and its mesh will not longer be updated by the physics engine.
  32177. * @param {PhysicsImpostor} impostor the impostor to remove
  32178. */
  32179. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  32180. var index = this._impostors.indexOf(impostor);
  32181. if (index > -1) {
  32182. var removed = this._impostors.splice(index, 1);
  32183. //Is it needed?
  32184. if (removed.length) {
  32185. //this will also remove it from the world.
  32186. removed[0].physicsBody = null;
  32187. }
  32188. }
  32189. };
  32190. /**
  32191. * Add a joint to the physics engine
  32192. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  32193. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  32194. * @param {PhysicsJoint} the joint that will connect both impostors.
  32195. */
  32196. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  32197. var impostorJoint = {
  32198. mainImpostor: mainImpostor,
  32199. connectedImpostor: connectedImpostor,
  32200. joint: joint
  32201. };
  32202. joint.physicsPlugin = this._physicsPlugin;
  32203. this._joints.push(impostorJoint);
  32204. this._physicsPlugin.generateJoint(impostorJoint);
  32205. };
  32206. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  32207. var matchingJoints = this._joints.filter(function (impostorJoint) {
  32208. return (impostorJoint.connectedImpostor === connectedImpostor
  32209. && impostorJoint.joint === joint
  32210. && impostorJoint.mainImpostor === mainImpostor);
  32211. });
  32212. if (matchingJoints.length) {
  32213. this._physicsPlugin.removeJoint(matchingJoints[0]);
  32214. }
  32215. };
  32216. /**
  32217. * Called by the scene. no need to call it.
  32218. */
  32219. PhysicsEngine.prototype._step = function (delta) {
  32220. var _this = this;
  32221. //check if any mesh has no body / requires an update
  32222. this._impostors.forEach(function (impostor) {
  32223. if (impostor.isBodyInitRequired()) {
  32224. _this._physicsPlugin.generatePhysicsBody(impostor);
  32225. }
  32226. });
  32227. if (delta > 0.1) {
  32228. delta = 0.1;
  32229. }
  32230. else if (delta <= 0) {
  32231. delta = 1.0 / 60.0;
  32232. }
  32233. this._physicsPlugin.executeStep(delta, this._impostors);
  32234. };
  32235. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  32236. return this._physicsPlugin;
  32237. };
  32238. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  32239. for (var i = 0; i < this._impostors.length; ++i) {
  32240. if (this._impostors[i].object === object) {
  32241. return this._impostors[i];
  32242. }
  32243. }
  32244. };
  32245. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  32246. for (var i = 0; i < this._impostors.length; ++i) {
  32247. if (this._impostors[i].physicsBody === body) {
  32248. return this._impostors[i];
  32249. }
  32250. }
  32251. };
  32252. // Statics, Legacy support.
  32253. /**
  32254. * @Deprecated
  32255. *
  32256. */
  32257. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  32258. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  32259. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  32260. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  32261. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  32262. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  32263. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  32264. PhysicsEngine.CapsuleImpostor = -1;
  32265. PhysicsEngine.ConeImpostor = -1;
  32266. PhysicsEngine.ConvexHullImpostor = -1;
  32267. PhysicsEngine.Epsilon = 0.001;
  32268. return PhysicsEngine;
  32269. }());
  32270. BABYLON.PhysicsEngine = PhysicsEngine;
  32271. })(BABYLON || (BABYLON = {}));
  32272. //# sourceMappingURL=babylon.physicsEngine.js.map
  32273. var BABYLON;
  32274. (function (BABYLON) {
  32275. var VertexData = (function () {
  32276. function VertexData() {
  32277. }
  32278. VertexData.prototype.set = function (data, kind) {
  32279. switch (kind) {
  32280. case BABYLON.VertexBuffer.PositionKind:
  32281. this.positions = data;
  32282. break;
  32283. case BABYLON.VertexBuffer.NormalKind:
  32284. this.normals = data;
  32285. break;
  32286. case BABYLON.VertexBuffer.UVKind:
  32287. this.uvs = data;
  32288. break;
  32289. case BABYLON.VertexBuffer.UV2Kind:
  32290. this.uvs2 = data;
  32291. break;
  32292. case BABYLON.VertexBuffer.UV3Kind:
  32293. this.uvs3 = data;
  32294. break;
  32295. case BABYLON.VertexBuffer.UV4Kind:
  32296. this.uvs4 = data;
  32297. break;
  32298. case BABYLON.VertexBuffer.UV5Kind:
  32299. this.uvs5 = data;
  32300. break;
  32301. case BABYLON.VertexBuffer.UV6Kind:
  32302. this.uvs6 = data;
  32303. break;
  32304. case BABYLON.VertexBuffer.ColorKind:
  32305. this.colors = data;
  32306. break;
  32307. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32308. this.matricesIndices = data;
  32309. break;
  32310. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32311. this.matricesWeights = data;
  32312. break;
  32313. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32314. this.matricesIndicesExtra = data;
  32315. break;
  32316. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32317. this.matricesWeightsExtra = data;
  32318. break;
  32319. }
  32320. };
  32321. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32322. this._applyTo(mesh, updatable);
  32323. };
  32324. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32325. this._applyTo(geometry, updatable);
  32326. };
  32327. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32328. this._update(mesh);
  32329. };
  32330. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32331. this._update(geometry);
  32332. };
  32333. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32334. if (this.positions) {
  32335. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32336. }
  32337. if (this.normals) {
  32338. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32339. }
  32340. if (this.uvs) {
  32341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32342. }
  32343. if (this.uvs2) {
  32344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32345. }
  32346. if (this.uvs3) {
  32347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32348. }
  32349. if (this.uvs4) {
  32350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32351. }
  32352. if (this.uvs5) {
  32353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32354. }
  32355. if (this.uvs6) {
  32356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32357. }
  32358. if (this.colors) {
  32359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32360. }
  32361. if (this.matricesIndices) {
  32362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32363. }
  32364. if (this.matricesWeights) {
  32365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32366. }
  32367. if (this.matricesIndicesExtra) {
  32368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32369. }
  32370. if (this.matricesWeightsExtra) {
  32371. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32372. }
  32373. if (this.indices) {
  32374. meshOrGeometry.setIndices(this.indices);
  32375. }
  32376. };
  32377. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32378. if (this.positions) {
  32379. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32380. }
  32381. if (this.normals) {
  32382. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32383. }
  32384. if (this.uvs) {
  32385. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32386. }
  32387. if (this.uvs2) {
  32388. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32389. }
  32390. if (this.uvs3) {
  32391. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32392. }
  32393. if (this.uvs4) {
  32394. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32395. }
  32396. if (this.uvs5) {
  32397. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32398. }
  32399. if (this.uvs6) {
  32400. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32401. }
  32402. if (this.colors) {
  32403. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32404. }
  32405. if (this.matricesIndices) {
  32406. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32407. }
  32408. if (this.matricesWeights) {
  32409. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32410. }
  32411. if (this.matricesIndicesExtra) {
  32412. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32413. }
  32414. if (this.matricesWeightsExtra) {
  32415. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32416. }
  32417. if (this.indices) {
  32418. meshOrGeometry.setIndices(this.indices);
  32419. }
  32420. };
  32421. VertexData.prototype.transform = function (matrix) {
  32422. var transformed = BABYLON.Vector3.Zero();
  32423. var index;
  32424. if (this.positions) {
  32425. var position = BABYLON.Vector3.Zero();
  32426. for (index = 0; index < this.positions.length; index += 3) {
  32427. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32428. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32429. this.positions[index] = transformed.x;
  32430. this.positions[index + 1] = transformed.y;
  32431. this.positions[index + 2] = transformed.z;
  32432. }
  32433. }
  32434. if (this.normals) {
  32435. var normal = BABYLON.Vector3.Zero();
  32436. for (index = 0; index < this.normals.length; index += 3) {
  32437. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32438. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32439. this.normals[index] = transformed.x;
  32440. this.normals[index + 1] = transformed.y;
  32441. this.normals[index + 2] = transformed.z;
  32442. }
  32443. }
  32444. };
  32445. VertexData.prototype.merge = function (other) {
  32446. if (other.indices) {
  32447. if (!this.indices) {
  32448. this.indices = [];
  32449. }
  32450. var offset = this.positions ? this.positions.length / 3 : 0;
  32451. for (var index = 0; index < other.indices.length; index++) {
  32452. //TODO check type - if Int32Array!
  32453. this.indices.push(other.indices[index] + offset);
  32454. }
  32455. }
  32456. this.positions = this._mergeElement(this.positions, other.positions);
  32457. this.normals = this._mergeElement(this.normals, other.normals);
  32458. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32459. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32460. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32461. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32462. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32463. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32464. this.colors = this._mergeElement(this.colors, other.colors);
  32465. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32466. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32467. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32468. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32469. };
  32470. VertexData.prototype._mergeElement = function (source, other) {
  32471. if (!other)
  32472. return source;
  32473. if (!source)
  32474. return other;
  32475. var len = other.length + source.length;
  32476. var isSrcTypedArray = source instanceof Float32Array;
  32477. var isOthTypedArray = other instanceof Float32Array;
  32478. // use non-loop method when the source is Float32Array
  32479. if (isSrcTypedArray) {
  32480. var ret32 = new Float32Array(len);
  32481. ret32.set(source);
  32482. ret32.set(other, source.length);
  32483. return ret32;
  32484. }
  32485. else if (!isOthTypedArray) {
  32486. return source.concat(other);
  32487. }
  32488. else {
  32489. var ret = source.slice(0); // copy source to a separate array
  32490. for (var i = 0, len = other.length; i < len; i++) {
  32491. ret.push(other[i]);
  32492. }
  32493. return ret;
  32494. }
  32495. };
  32496. VertexData.prototype.serialize = function () {
  32497. var serializationObject = this.serialize();
  32498. if (this.positions) {
  32499. serializationObject.positions = this.positions;
  32500. }
  32501. if (this.normals) {
  32502. serializationObject.normals = this.normals;
  32503. }
  32504. if (this.uvs) {
  32505. serializationObject.uvs = this.uvs;
  32506. }
  32507. if (this.uvs2) {
  32508. serializationObject.uvs2 = this.uvs2;
  32509. }
  32510. if (this.uvs3) {
  32511. serializationObject.uvs3 = this.uvs3;
  32512. }
  32513. if (this.uvs4) {
  32514. serializationObject.uvs4 = this.uvs4;
  32515. }
  32516. if (this.uvs5) {
  32517. serializationObject.uvs5 = this.uvs5;
  32518. }
  32519. if (this.uvs6) {
  32520. serializationObject.uvs6 = this.uvs6;
  32521. }
  32522. if (this.colors) {
  32523. serializationObject.colors = this.colors;
  32524. }
  32525. if (this.matricesIndices) {
  32526. serializationObject.matricesIndices = this.matricesIndices;
  32527. serializationObject.matricesIndices._isExpanded = true;
  32528. }
  32529. if (this.matricesWeights) {
  32530. serializationObject.matricesWeights = this.matricesWeights;
  32531. }
  32532. if (this.matricesIndicesExtra) {
  32533. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32534. serializationObject.matricesIndicesExtra._isExpanded = true;
  32535. }
  32536. if (this.matricesWeightsExtra) {
  32537. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32538. }
  32539. serializationObject.indices = this.indices;
  32540. return serializationObject;
  32541. };
  32542. // Statics
  32543. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  32544. return VertexData._ExtractFrom(mesh, copyWhenShared);
  32545. };
  32546. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  32547. return VertexData._ExtractFrom(geometry, copyWhenShared);
  32548. };
  32549. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  32550. var result = new VertexData();
  32551. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32552. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  32553. }
  32554. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32555. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  32556. }
  32557. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32558. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  32559. }
  32560. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32561. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  32562. }
  32563. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32564. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  32565. }
  32566. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32567. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  32568. }
  32569. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32570. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  32571. }
  32572. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32573. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  32574. }
  32575. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32576. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  32577. }
  32578. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32579. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  32580. }
  32581. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32582. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  32583. }
  32584. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32585. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  32586. }
  32587. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32588. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  32589. }
  32590. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32591. return result;
  32592. };
  32593. VertexData.CreateRibbon = function (options) {
  32594. var pathArray = options.pathArray;
  32595. var closeArray = options.closeArray || false;
  32596. var closePath = options.closePath || false;
  32597. var invertUV = options.invertUV || false;
  32598. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32599. var offset = options.offset || defaultOffset;
  32600. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32601. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32602. var positions = [];
  32603. var indices = [];
  32604. var normals = [];
  32605. var uvs = [];
  32606. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32607. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32608. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32609. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32610. var minlg; // minimal length among all paths from pathArray
  32611. var lg = []; // array of path lengths : nb of vertex per path
  32612. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32613. var p; // path iterator
  32614. var i; // point iterator
  32615. var j; // point iterator
  32616. // if single path in pathArray
  32617. if (pathArray.length < 2) {
  32618. var ar1 = [];
  32619. var ar2 = [];
  32620. for (i = 0; i < pathArray[0].length - offset; i++) {
  32621. ar1.push(pathArray[0][i]);
  32622. ar2.push(pathArray[0][i + offset]);
  32623. }
  32624. pathArray = [ar1, ar2];
  32625. }
  32626. // positions and horizontal distances (u)
  32627. var idc = 0;
  32628. var closePathCorr = (closePath) ? 1 : 0;
  32629. var path;
  32630. var l;
  32631. minlg = pathArray[0].length;
  32632. var vectlg;
  32633. var dist;
  32634. for (p = 0; p < pathArray.length; p++) {
  32635. uTotalDistance[p] = 0;
  32636. us[p] = [0];
  32637. path = pathArray[p];
  32638. l = path.length;
  32639. minlg = (minlg < l) ? minlg : l;
  32640. j = 0;
  32641. while (j < l) {
  32642. positions.push(path[j].x, path[j].y, path[j].z);
  32643. if (j > 0) {
  32644. vectlg = path[j].subtract(path[j - 1]).length();
  32645. dist = vectlg + uTotalDistance[p];
  32646. us[p].push(dist);
  32647. uTotalDistance[p] = dist;
  32648. }
  32649. j++;
  32650. }
  32651. if (closePath) {
  32652. j--;
  32653. positions.push(path[0].x, path[0].y, path[0].z);
  32654. vectlg = path[j].subtract(path[0]).length();
  32655. dist = vectlg + uTotalDistance[p];
  32656. us[p].push(dist);
  32657. uTotalDistance[p] = dist;
  32658. }
  32659. lg[p] = l + closePathCorr;
  32660. idx[p] = idc;
  32661. idc += (l + closePathCorr);
  32662. }
  32663. // vertical distances (v)
  32664. var path1;
  32665. var path2;
  32666. var vertex1;
  32667. var vertex2;
  32668. for (i = 0; i < minlg + closePathCorr; i++) {
  32669. vTotalDistance[i] = 0;
  32670. vs[i] = [0];
  32671. for (p = 0; p < pathArray.length - 1; p++) {
  32672. path1 = pathArray[p];
  32673. path2 = pathArray[p + 1];
  32674. if (i === minlg) {
  32675. vertex1 = path1[0];
  32676. vertex2 = path2[0];
  32677. }
  32678. else {
  32679. vertex1 = path1[i];
  32680. vertex2 = path2[i];
  32681. }
  32682. vectlg = vertex2.subtract(vertex1).length();
  32683. dist = vectlg + vTotalDistance[i];
  32684. vs[i].push(dist);
  32685. vTotalDistance[i] = dist;
  32686. }
  32687. if (closeArray) {
  32688. path1 = pathArray[p];
  32689. path2 = pathArray[0];
  32690. if (i === minlg) {
  32691. vertex2 = path2[0];
  32692. }
  32693. vectlg = vertex2.subtract(vertex1).length();
  32694. dist = vectlg + vTotalDistance[i];
  32695. vTotalDistance[i] = dist;
  32696. }
  32697. }
  32698. // uvs
  32699. var u;
  32700. var v;
  32701. for (p = 0; p < pathArray.length; p++) {
  32702. for (i = 0; i < minlg + closePathCorr; i++) {
  32703. u = us[p][i] / uTotalDistance[p];
  32704. v = vs[i][p] / vTotalDistance[i];
  32705. if (invertUV) {
  32706. uvs.push(v, u);
  32707. }
  32708. else {
  32709. uvs.push(u, v);
  32710. }
  32711. }
  32712. }
  32713. // indices
  32714. p = 0; // path index
  32715. var pi = 0; // positions array index
  32716. var l1 = lg[p] - 1; // path1 length
  32717. var l2 = lg[p + 1] - 1; // path2 length
  32718. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32719. var shft = idx[1] - idx[0]; // shift
  32720. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32721. while (pi <= min && p < path1nb) {
  32722. // 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
  32723. indices.push(pi, pi + shft, pi + 1);
  32724. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32725. pi += 1;
  32726. if (pi === min) {
  32727. p++;
  32728. if (p === lg.length - 1) {
  32729. shft = idx[0] - idx[p];
  32730. l1 = lg[p] - 1;
  32731. l2 = lg[0] - 1;
  32732. }
  32733. else {
  32734. shft = idx[p + 1] - idx[p];
  32735. l1 = lg[p] - 1;
  32736. l2 = lg[p + 1] - 1;
  32737. }
  32738. pi = idx[p];
  32739. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32740. }
  32741. }
  32742. // normals
  32743. VertexData.ComputeNormals(positions, indices, normals);
  32744. if (closePath) {
  32745. var indexFirst = 0;
  32746. var indexLast = 0;
  32747. for (p = 0; p < pathArray.length; p++) {
  32748. indexFirst = idx[p] * 3;
  32749. if (p + 1 < pathArray.length) {
  32750. indexLast = (idx[p + 1] - 1) * 3;
  32751. }
  32752. else {
  32753. indexLast = normals.length - 3;
  32754. }
  32755. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32756. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32757. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32758. normals[indexLast] = normals[indexFirst];
  32759. normals[indexLast + 1] = normals[indexFirst + 1];
  32760. normals[indexLast + 2] = normals[indexFirst + 2];
  32761. }
  32762. }
  32763. // sides
  32764. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32765. // Result
  32766. var vertexData = new VertexData();
  32767. vertexData.indices = indices;
  32768. vertexData.positions = positions;
  32769. vertexData.normals = normals;
  32770. vertexData.uvs = uvs;
  32771. if (closePath) {
  32772. vertexData._idx = idx;
  32773. }
  32774. return vertexData;
  32775. };
  32776. VertexData.CreateBox = function (options) {
  32777. var normalsSource = [
  32778. new BABYLON.Vector3(0, 0, 1),
  32779. new BABYLON.Vector3(0, 0, -1),
  32780. new BABYLON.Vector3(1, 0, 0),
  32781. new BABYLON.Vector3(-1, 0, 0),
  32782. new BABYLON.Vector3(0, 1, 0),
  32783. new BABYLON.Vector3(0, -1, 0)
  32784. ];
  32785. var indices = [];
  32786. var positions = [];
  32787. var normals = [];
  32788. var uvs = [];
  32789. var width = options.width || options.size || 1;
  32790. var height = options.height || options.size || 1;
  32791. var depth = options.depth || options.size || 1;
  32792. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32793. var faceUV = options.faceUV || new Array(6);
  32794. var faceColors = options.faceColors;
  32795. var colors = [];
  32796. // default face colors and UV if undefined
  32797. for (var f = 0; f < 6; f++) {
  32798. if (faceUV[f] === undefined) {
  32799. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32800. }
  32801. if (faceColors && faceColors[f] === undefined) {
  32802. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32803. }
  32804. }
  32805. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32806. // Create each face in turn.
  32807. for (var index = 0; index < normalsSource.length; index++) {
  32808. var normal = normalsSource[index];
  32809. // Get two vectors perpendicular to the face normal and to each other.
  32810. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32811. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32812. // Six indices (two triangles) per face.
  32813. var verticesLength = positions.length / 3;
  32814. indices.push(verticesLength);
  32815. indices.push(verticesLength + 1);
  32816. indices.push(verticesLength + 2);
  32817. indices.push(verticesLength);
  32818. indices.push(verticesLength + 2);
  32819. indices.push(verticesLength + 3);
  32820. // Four vertices per face.
  32821. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32822. positions.push(vertex.x, vertex.y, vertex.z);
  32823. normals.push(normal.x, normal.y, normal.z);
  32824. uvs.push(faceUV[index].z, faceUV[index].w);
  32825. if (faceColors) {
  32826. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32827. }
  32828. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32829. positions.push(vertex.x, vertex.y, vertex.z);
  32830. normals.push(normal.x, normal.y, normal.z);
  32831. uvs.push(faceUV[index].x, faceUV[index].w);
  32832. if (faceColors) {
  32833. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32834. }
  32835. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32836. positions.push(vertex.x, vertex.y, vertex.z);
  32837. normals.push(normal.x, normal.y, normal.z);
  32838. uvs.push(faceUV[index].x, faceUV[index].y);
  32839. if (faceColors) {
  32840. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32841. }
  32842. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32843. positions.push(vertex.x, vertex.y, vertex.z);
  32844. normals.push(normal.x, normal.y, normal.z);
  32845. uvs.push(faceUV[index].z, faceUV[index].y);
  32846. if (faceColors) {
  32847. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32848. }
  32849. }
  32850. // sides
  32851. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32852. // Result
  32853. var vertexData = new VertexData();
  32854. vertexData.indices = indices;
  32855. vertexData.positions = positions;
  32856. vertexData.normals = normals;
  32857. vertexData.uvs = uvs;
  32858. if (faceColors) {
  32859. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32860. vertexData.colors = totalColors;
  32861. }
  32862. return vertexData;
  32863. };
  32864. VertexData.CreateSphere = function (options) {
  32865. var segments = options.segments || 32;
  32866. var diameterX = options.diameterX || options.diameter || 1;
  32867. var diameterY = options.diameterY || options.diameter || 1;
  32868. var diameterZ = options.diameterZ || options.diameter || 1;
  32869. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32870. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32871. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32872. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32873. var totalZRotationSteps = 2 + segments;
  32874. var totalYRotationSteps = 2 * totalZRotationSteps;
  32875. var indices = [];
  32876. var positions = [];
  32877. var normals = [];
  32878. var uvs = [];
  32879. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32880. var normalizedZ = zRotationStep / totalZRotationSteps;
  32881. var angleZ = normalizedZ * Math.PI * slice;
  32882. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32883. var normalizedY = yRotationStep / totalYRotationSteps;
  32884. var angleY = normalizedY * Math.PI * 2 * arc;
  32885. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32886. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32887. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32888. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32889. var vertex = complete.multiply(radius);
  32890. var normal = complete.divide(radius).normalize();
  32891. positions.push(vertex.x, vertex.y, vertex.z);
  32892. normals.push(normal.x, normal.y, normal.z);
  32893. uvs.push(normalizedY, normalizedZ);
  32894. }
  32895. if (zRotationStep > 0) {
  32896. var verticesCount = positions.length / 3;
  32897. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32898. indices.push((firstIndex));
  32899. indices.push((firstIndex + 1));
  32900. indices.push(firstIndex + totalYRotationSteps + 1);
  32901. indices.push((firstIndex + totalYRotationSteps + 1));
  32902. indices.push((firstIndex + 1));
  32903. indices.push((firstIndex + totalYRotationSteps + 2));
  32904. }
  32905. }
  32906. }
  32907. // Sides
  32908. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32909. // Result
  32910. var vertexData = new VertexData();
  32911. vertexData.indices = indices;
  32912. vertexData.positions = positions;
  32913. vertexData.normals = normals;
  32914. vertexData.uvs = uvs;
  32915. return vertexData;
  32916. };
  32917. // Cylinder and cone
  32918. VertexData.CreateCylinder = function (options) {
  32919. var height = options.height || 2;
  32920. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32921. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32922. var tessellation = options.tessellation || 24;
  32923. var subdivisions = options.subdivisions || 1;
  32924. var hasRings = options.hasRings;
  32925. var enclose = options.enclose;
  32926. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32927. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32928. var faceUV = options.faceUV || new Array(3);
  32929. var faceColors = options.faceColors;
  32930. // default face colors and UV if undefined
  32931. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32932. var ringNb = (hasRings) ? subdivisions : 1;
  32933. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32934. var f;
  32935. for (f = 0; f < surfaceNb; f++) {
  32936. if (faceColors && faceColors[f] === undefined) {
  32937. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32938. }
  32939. }
  32940. for (f = 0; f < surfaceNb; f++) {
  32941. if (faceUV && faceUV[f] === undefined) {
  32942. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32943. }
  32944. }
  32945. var indices = [];
  32946. var positions = [];
  32947. var normals = [];
  32948. var uvs = [];
  32949. var colors = [];
  32950. var angle_step = Math.PI * 2 * arc / tessellation;
  32951. var angle;
  32952. var h;
  32953. var radius;
  32954. var tan = (diameterBottom - diameterTop) / 2 / height;
  32955. var ringVertex = BABYLON.Vector3.Zero();
  32956. var ringNormal = BABYLON.Vector3.Zero();
  32957. var ringFirstVertex = BABYLON.Vector3.Zero();
  32958. var ringFirstNormal = BABYLON.Vector3.Zero();
  32959. var quadNormal = BABYLON.Vector3.Zero();
  32960. var Y = BABYLON.Axis.Y;
  32961. // positions, normals, uvs
  32962. var i;
  32963. var j;
  32964. var r;
  32965. var ringIdx = 1;
  32966. var s = 1; // surface index
  32967. var cs = 0;
  32968. var v = 0;
  32969. for (i = 0; i <= subdivisions; i++) {
  32970. h = i / subdivisions;
  32971. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32972. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32973. for (r = 0; r < ringIdx; r++) {
  32974. if (hasRings) {
  32975. s += r;
  32976. }
  32977. if (enclose) {
  32978. s += 2 * r;
  32979. }
  32980. for (j = 0; j <= tessellation; j++) {
  32981. angle = j * angle_step;
  32982. // position
  32983. ringVertex.x = Math.cos(-angle) * radius;
  32984. ringVertex.y = -height / 2 + h * height;
  32985. ringVertex.z = Math.sin(-angle) * radius;
  32986. // normal
  32987. if (diameterTop === 0 && i === subdivisions) {
  32988. // if no top cap, reuse former normals
  32989. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32990. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32991. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32992. }
  32993. else {
  32994. ringNormal.x = ringVertex.x;
  32995. ringNormal.z = ringVertex.z;
  32996. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32997. ringNormal.normalize();
  32998. }
  32999. // keep first ring vertex values for enclose
  33000. if (j === 0) {
  33001. ringFirstVertex.copyFrom(ringVertex);
  33002. ringFirstNormal.copyFrom(ringNormal);
  33003. }
  33004. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33005. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33006. if (hasRings) {
  33007. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33008. }
  33009. else {
  33010. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33011. }
  33012. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33013. if (faceColors) {
  33014. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33015. }
  33016. }
  33017. // if enclose, add four vertices and their dedicated normals
  33018. if (arc !== 1 && enclose) {
  33019. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33020. positions.push(0, ringVertex.y, 0);
  33021. positions.push(0, ringVertex.y, 0);
  33022. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33023. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33024. quadNormal.normalize();
  33025. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33026. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33027. quadNormal.normalize();
  33028. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33029. if (hasRings) {
  33030. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33031. }
  33032. else {
  33033. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33034. }
  33035. uvs.push(faceUV[s + 1].x, v);
  33036. uvs.push(faceUV[s + 1].z, v);
  33037. if (hasRings) {
  33038. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33039. }
  33040. else {
  33041. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33042. }
  33043. uvs.push(faceUV[s + 2].x, v);
  33044. uvs.push(faceUV[s + 2].z, v);
  33045. if (faceColors) {
  33046. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33047. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33048. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33049. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33050. }
  33051. }
  33052. if (cs !== s) {
  33053. cs = s;
  33054. }
  33055. }
  33056. }
  33057. // indices
  33058. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33059. var s;
  33060. i = 0;
  33061. for (s = 0; s < subdivisions; s++) {
  33062. for (j = 0; j < tessellation; j++) {
  33063. var i0 = i * (e + 1) + j;
  33064. var i1 = (i + 1) * (e + 1) + j;
  33065. var i2 = i * (e + 1) + (j + 1);
  33066. var i3 = (i + 1) * (e + 1) + (j + 1);
  33067. indices.push(i0, i1, i2);
  33068. indices.push(i3, i2, i1);
  33069. }
  33070. if (arc !== 1 && enclose) {
  33071. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33072. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33073. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33074. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33075. }
  33076. i = (hasRings) ? (i + 2) : (i + 1);
  33077. }
  33078. // Caps
  33079. var createCylinderCap = function (isTop) {
  33080. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33081. if (radius === 0) {
  33082. return;
  33083. }
  33084. // Cap positions, normals & uvs
  33085. var angle;
  33086. var circleVector;
  33087. var i;
  33088. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33089. var c;
  33090. if (faceColors) {
  33091. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33092. }
  33093. // cap center
  33094. var vbase = positions.length / 3;
  33095. var offset = isTop ? height / 2 : -height / 2;
  33096. var center = new BABYLON.Vector3(0, offset, 0);
  33097. positions.push(center.x, center.y, center.z);
  33098. normals.push(0, isTop ? 1 : -1, 0);
  33099. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33100. if (faceColors) {
  33101. colors.push(c.r, c.g, c.b, c.a);
  33102. }
  33103. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33104. for (i = 0; i <= tessellation; i++) {
  33105. angle = Math.PI * 2 * i * arc / tessellation;
  33106. var cos = Math.cos(-angle);
  33107. var sin = Math.sin(-angle);
  33108. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33109. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33110. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33111. normals.push(0, isTop ? 1 : -1, 0);
  33112. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33113. if (faceColors) {
  33114. colors.push(c.r, c.g, c.b, c.a);
  33115. }
  33116. }
  33117. // Cap indices
  33118. for (i = 0; i < tessellation; i++) {
  33119. if (!isTop) {
  33120. indices.push(vbase);
  33121. indices.push(vbase + (i + 1));
  33122. indices.push(vbase + (i + 2));
  33123. }
  33124. else {
  33125. indices.push(vbase);
  33126. indices.push(vbase + (i + 2));
  33127. indices.push(vbase + (i + 1));
  33128. }
  33129. }
  33130. };
  33131. // add caps to geometry
  33132. createCylinderCap(false);
  33133. createCylinderCap(true);
  33134. // Sides
  33135. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33136. var vertexData = new VertexData();
  33137. vertexData.indices = indices;
  33138. vertexData.positions = positions;
  33139. vertexData.normals = normals;
  33140. vertexData.uvs = uvs;
  33141. if (faceColors) {
  33142. vertexData.colors = colors;
  33143. }
  33144. return vertexData;
  33145. };
  33146. VertexData.CreateTorus = function (options) {
  33147. var indices = [];
  33148. var positions = [];
  33149. var normals = [];
  33150. var uvs = [];
  33151. var diameter = options.diameter || 1;
  33152. var thickness = options.thickness || 0.5;
  33153. var tessellation = options.tessellation || 16;
  33154. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33155. var stride = tessellation + 1;
  33156. for (var i = 0; i <= tessellation; i++) {
  33157. var u = i / tessellation;
  33158. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33159. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33160. for (var j = 0; j <= tessellation; j++) {
  33161. var v = 1 - j / tessellation;
  33162. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33163. var dx = Math.cos(innerAngle);
  33164. var dy = Math.sin(innerAngle);
  33165. // Create a vertex.
  33166. var normal = new BABYLON.Vector3(dx, dy, 0);
  33167. var position = normal.scale(thickness / 2);
  33168. var textureCoordinate = new BABYLON.Vector2(u, v);
  33169. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33170. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33171. positions.push(position.x, position.y, position.z);
  33172. normals.push(normal.x, normal.y, normal.z);
  33173. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33174. // And create indices for two triangles.
  33175. var nextI = (i + 1) % stride;
  33176. var nextJ = (j + 1) % stride;
  33177. indices.push(i * stride + j);
  33178. indices.push(i * stride + nextJ);
  33179. indices.push(nextI * stride + j);
  33180. indices.push(i * stride + nextJ);
  33181. indices.push(nextI * stride + nextJ);
  33182. indices.push(nextI * stride + j);
  33183. }
  33184. }
  33185. // Sides
  33186. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33187. // Result
  33188. var vertexData = new VertexData();
  33189. vertexData.indices = indices;
  33190. vertexData.positions = positions;
  33191. vertexData.normals = normals;
  33192. vertexData.uvs = uvs;
  33193. return vertexData;
  33194. };
  33195. VertexData.CreateLineSystem = function (options) {
  33196. var indices = [];
  33197. var positions = [];
  33198. var lines = options.lines;
  33199. var idx = 0;
  33200. for (var l = 0; l < lines.length; l++) {
  33201. var points = lines[l];
  33202. for (var index = 0; index < points.length; index++) {
  33203. positions.push(points[index].x, points[index].y, points[index].z);
  33204. if (index > 0) {
  33205. indices.push(idx - 1);
  33206. indices.push(idx);
  33207. }
  33208. idx++;
  33209. }
  33210. }
  33211. var vertexData = new VertexData();
  33212. vertexData.indices = indices;
  33213. vertexData.positions = positions;
  33214. return vertexData;
  33215. };
  33216. VertexData.CreateDashedLines = function (options) {
  33217. var dashSize = options.dashSize || 3;
  33218. var gapSize = options.gapSize || 1;
  33219. var dashNb = options.dashNb || 200;
  33220. var points = options.points;
  33221. var positions = new Array();
  33222. var indices = new Array();
  33223. var curvect = BABYLON.Vector3.Zero();
  33224. var lg = 0;
  33225. var nb = 0;
  33226. var shft = 0;
  33227. var dashshft = 0;
  33228. var curshft = 0;
  33229. var idx = 0;
  33230. var i = 0;
  33231. for (i = 0; i < points.length - 1; i++) {
  33232. points[i + 1].subtractToRef(points[i], curvect);
  33233. lg += curvect.length();
  33234. }
  33235. shft = lg / dashNb;
  33236. dashshft = dashSize * shft / (dashSize + gapSize);
  33237. for (i = 0; i < points.length - 1; i++) {
  33238. points[i + 1].subtractToRef(points[i], curvect);
  33239. nb = Math.floor(curvect.length() / shft);
  33240. curvect.normalize();
  33241. for (var j = 0; j < nb; j++) {
  33242. curshft = shft * j;
  33243. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33244. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33245. indices.push(idx, idx + 1);
  33246. idx += 2;
  33247. }
  33248. }
  33249. // Result
  33250. var vertexData = new VertexData();
  33251. vertexData.positions = positions;
  33252. vertexData.indices = indices;
  33253. return vertexData;
  33254. };
  33255. VertexData.CreateGround = function (options) {
  33256. var indices = [];
  33257. var positions = [];
  33258. var normals = [];
  33259. var uvs = [];
  33260. var row, col;
  33261. var width = options.width || 1;
  33262. var height = options.height || 1;
  33263. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33264. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33265. for (row = 0; row <= subdivisionsY; row++) {
  33266. for (col = 0; col <= subdivisionsX; col++) {
  33267. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33268. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33269. positions.push(position.x, position.y, position.z);
  33270. normals.push(normal.x, normal.y, normal.z);
  33271. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  33272. }
  33273. }
  33274. for (row = 0; row < subdivisionsY; row++) {
  33275. for (col = 0; col < subdivisionsX; col++) {
  33276. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33277. indices.push(col + 1 + row * (subdivisionsX + 1));
  33278. indices.push(col + row * (subdivisionsX + 1));
  33279. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33280. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33281. indices.push(col + row * (subdivisionsX + 1));
  33282. }
  33283. }
  33284. // Result
  33285. var vertexData = new VertexData();
  33286. vertexData.indices = indices;
  33287. vertexData.positions = positions;
  33288. vertexData.normals = normals;
  33289. vertexData.uvs = uvs;
  33290. return vertexData;
  33291. };
  33292. VertexData.CreateTiledGround = function (options) {
  33293. var xmin = options.xmin || -1.0;
  33294. var zmin = options.zmin || -1.0;
  33295. var xmax = options.xmax || 1.0;
  33296. var zmax = options.zmax || 1.0;
  33297. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33298. var precision = options.precision || { w: 1, h: 1 };
  33299. var indices = [];
  33300. var positions = [];
  33301. var normals = [];
  33302. var uvs = [];
  33303. var row, col, tileRow, tileCol;
  33304. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33305. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33306. precision.w = (precision.w < 1) ? 1 : precision.w;
  33307. precision.h = (precision.h < 1) ? 1 : precision.h;
  33308. var tileSize = {
  33309. 'w': (xmax - xmin) / subdivisions.w,
  33310. 'h': (zmax - zmin) / subdivisions.h
  33311. };
  33312. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33313. // Indices
  33314. var base = positions.length / 3;
  33315. var rowLength = precision.w + 1;
  33316. for (row = 0; row < precision.h; row++) {
  33317. for (col = 0; col < precision.w; col++) {
  33318. var square = [
  33319. base + col + row * rowLength,
  33320. base + (col + 1) + row * rowLength,
  33321. base + (col + 1) + (row + 1) * rowLength,
  33322. base + col + (row + 1) * rowLength
  33323. ];
  33324. indices.push(square[1]);
  33325. indices.push(square[2]);
  33326. indices.push(square[3]);
  33327. indices.push(square[0]);
  33328. indices.push(square[1]);
  33329. indices.push(square[3]);
  33330. }
  33331. }
  33332. // Position, normals and uvs
  33333. var position = BABYLON.Vector3.Zero();
  33334. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33335. for (row = 0; row <= precision.h; row++) {
  33336. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33337. for (col = 0; col <= precision.w; col++) {
  33338. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33339. position.y = 0;
  33340. positions.push(position.x, position.y, position.z);
  33341. normals.push(normal.x, normal.y, normal.z);
  33342. uvs.push(col / precision.w, row / precision.h);
  33343. }
  33344. }
  33345. }
  33346. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33347. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33348. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33349. }
  33350. }
  33351. // Result
  33352. var vertexData = new VertexData();
  33353. vertexData.indices = indices;
  33354. vertexData.positions = positions;
  33355. vertexData.normals = normals;
  33356. vertexData.uvs = uvs;
  33357. return vertexData;
  33358. };
  33359. VertexData.CreateGroundFromHeightMap = function (options) {
  33360. var indices = [];
  33361. var positions = [];
  33362. var normals = [];
  33363. var uvs = [];
  33364. var row, col;
  33365. // Vertices
  33366. for (row = 0; row <= options.subdivisions; row++) {
  33367. for (col = 0; col <= options.subdivisions; col++) {
  33368. 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));
  33369. // Compute height
  33370. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33371. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33372. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33373. var r = options.buffer[pos] / 255.0;
  33374. var g = options.buffer[pos + 1] / 255.0;
  33375. var b = options.buffer[pos + 2] / 255.0;
  33376. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33377. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33378. // Add vertex
  33379. positions.push(position.x, position.y, position.z);
  33380. normals.push(0, 0, 0);
  33381. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33382. }
  33383. }
  33384. // Indices
  33385. for (row = 0; row < options.subdivisions; row++) {
  33386. for (col = 0; col < options.subdivisions; col++) {
  33387. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33388. indices.push(col + 1 + row * (options.subdivisions + 1));
  33389. indices.push(col + row * (options.subdivisions + 1));
  33390. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33391. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33392. indices.push(col + row * (options.subdivisions + 1));
  33393. }
  33394. }
  33395. // Normals
  33396. VertexData.ComputeNormals(positions, indices, normals);
  33397. // Result
  33398. var vertexData = new VertexData();
  33399. vertexData.indices = indices;
  33400. vertexData.positions = positions;
  33401. vertexData.normals = normals;
  33402. vertexData.uvs = uvs;
  33403. return vertexData;
  33404. };
  33405. VertexData.CreatePlane = function (options) {
  33406. var indices = [];
  33407. var positions = [];
  33408. var normals = [];
  33409. var uvs = [];
  33410. var width = options.width || options.size || 1;
  33411. var height = options.height || options.size || 1;
  33412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33413. // Vertices
  33414. var halfWidth = width / 2.0;
  33415. var halfHeight = height / 2.0;
  33416. positions.push(-halfWidth, -halfHeight, 0);
  33417. normals.push(0, 0, -1.0);
  33418. uvs.push(0.0, 0.0);
  33419. positions.push(halfWidth, -halfHeight, 0);
  33420. normals.push(0, 0, -1.0);
  33421. uvs.push(1.0, 0.0);
  33422. positions.push(halfWidth, halfHeight, 0);
  33423. normals.push(0, 0, -1.0);
  33424. uvs.push(1.0, 1.0);
  33425. positions.push(-halfWidth, halfHeight, 0);
  33426. normals.push(0, 0, -1.0);
  33427. uvs.push(0.0, 1.0);
  33428. // Indices
  33429. indices.push(0);
  33430. indices.push(1);
  33431. indices.push(2);
  33432. indices.push(0);
  33433. indices.push(2);
  33434. indices.push(3);
  33435. // Sides
  33436. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33437. // Result
  33438. var vertexData = new VertexData();
  33439. vertexData.indices = indices;
  33440. vertexData.positions = positions;
  33441. vertexData.normals = normals;
  33442. vertexData.uvs = uvs;
  33443. return vertexData;
  33444. };
  33445. VertexData.CreateDisc = function (options) {
  33446. var positions = [];
  33447. var indices = [];
  33448. var normals = [];
  33449. var uvs = [];
  33450. var radius = options.radius || 0.5;
  33451. var tessellation = options.tessellation || 64;
  33452. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33453. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33454. // positions and uvs
  33455. positions.push(0, 0, 0); // disc center first
  33456. uvs.push(0.5, 0.5);
  33457. var theta = Math.PI * 2 * arc;
  33458. var step = theta / tessellation;
  33459. for (var a = 0; a < theta; a += step) {
  33460. var x = Math.cos(a);
  33461. var y = Math.sin(a);
  33462. var u = (x + 1) / 2;
  33463. var v = (1 - y) / 2;
  33464. positions.push(radius * x, radius * y, 0);
  33465. uvs.push(u, v);
  33466. }
  33467. if (arc === 1) {
  33468. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33469. uvs.push(uvs[2], uvs[3]);
  33470. }
  33471. //indices
  33472. var vertexNb = positions.length / 3;
  33473. for (var i = 1; i < vertexNb - 1; i++) {
  33474. indices.push(i + 1, 0, i);
  33475. }
  33476. // result
  33477. VertexData.ComputeNormals(positions, indices, normals);
  33478. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33479. var vertexData = new VertexData();
  33480. vertexData.indices = indices;
  33481. vertexData.positions = positions;
  33482. vertexData.normals = normals;
  33483. vertexData.uvs = uvs;
  33484. return vertexData;
  33485. };
  33486. VertexData.CreateIcoSphere = function (options) {
  33487. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33488. var radius = options.radius || 1;
  33489. var flat = (options.flat === undefined) ? true : options.flat;
  33490. var subdivisions = options.subdivisions || 4;
  33491. var radiusX = options.radiusX || radius;
  33492. var radiusY = options.radiusY || radius;
  33493. var radiusZ = options.radiusZ || radius;
  33494. var t = (1 + Math.sqrt(5)) / 2;
  33495. // 12 vertex x,y,z
  33496. var ico_vertices = [
  33497. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33498. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33499. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33500. ];
  33501. // index of 3 vertex makes a face of icopshere
  33502. var ico_indices = [
  33503. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33504. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33505. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33506. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33507. ];
  33508. // vertex for uv have aliased position, not for UV
  33509. var vertices_unalias_id = [
  33510. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33511. // vertex alias
  33512. 0,
  33513. 2,
  33514. 3,
  33515. 3,
  33516. 3,
  33517. 4,
  33518. 7,
  33519. 8,
  33520. 9,
  33521. 9,
  33522. 10,
  33523. 11 // 23: B + 12
  33524. ];
  33525. // uv as integer step (not pixels !)
  33526. var ico_vertexuv = [
  33527. 5, 1, 3, 1, 6, 4, 0, 0,
  33528. 5, 3, 4, 2, 2, 2, 4, 0,
  33529. 2, 0, 1, 1, 6, 0, 6, 2,
  33530. // vertex alias (for same vertex on different faces)
  33531. 0, 4,
  33532. 3, 3,
  33533. 4, 4,
  33534. 3, 1,
  33535. 4, 2,
  33536. 4, 4,
  33537. 0, 2,
  33538. 1, 1,
  33539. 2, 2,
  33540. 3, 3,
  33541. 1, 3,
  33542. 2, 4 // 23: B + 12
  33543. ];
  33544. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33545. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33546. // First island of uv mapping
  33547. // v = 4h 3+ 2
  33548. // v = 3h 9+ 4
  33549. // v = 2h 9+ 5 B
  33550. // v = 1h 9 1 0
  33551. // v = 0h 3 8 7 A
  33552. // u = 0 1 2 3 4 5 6 *a
  33553. // Second island of uv mapping
  33554. // v = 4h 0+ B+ 4+
  33555. // v = 3h A+ 2+
  33556. // v = 2h 7+ 6 3+
  33557. // v = 1h 8+ 3+
  33558. // v = 0h
  33559. // u = 0 1 2 3 4 5 6 *a
  33560. // Face layout on texture UV mapping
  33561. // ============
  33562. // \ 4 /\ 16 / ======
  33563. // \ / \ / /\ 11 /
  33564. // \/ 7 \/ / \ /
  33565. // ======= / 10 \/
  33566. // /\ 17 /\ =======
  33567. // / \ / \ \ 15 /\
  33568. // / 8 \/ 12 \ \ / \
  33569. // ============ \/ 6 \
  33570. // \ 18 /\ ============
  33571. // \ / \ \ 5 /\ 0 /
  33572. // \/ 13 \ \ / \ /
  33573. // ======= \/ 1 \/
  33574. // =============
  33575. // /\ 19 /\ 2 /\
  33576. // / \ / \ / \
  33577. // / 14 \/ 9 \/ 3 \
  33578. // ===================
  33579. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33580. var ustep = 138 / 1024;
  33581. var vstep = 239 / 1024;
  33582. var uoffset = 60 / 1024;
  33583. var voffset = 26 / 1024;
  33584. // Second island should have margin, not to touch the first island
  33585. // avoid any borderline artefact in pixel rounding
  33586. var island_u_offset = -40 / 1024;
  33587. var island_v_offset = +20 / 1024;
  33588. // face is either island 0 or 1 :
  33589. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33590. var island = [
  33591. 0, 0, 0, 0, 1,
  33592. 0, 0, 1, 1, 0,
  33593. 0, 0, 1, 1, 0,
  33594. 0, 1, 1, 1, 0 // 15 - 19
  33595. ];
  33596. var indices = [];
  33597. var positions = [];
  33598. var normals = [];
  33599. var uvs = [];
  33600. var current_indice = 0;
  33601. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33602. var face_vertex_pos = new Array(3);
  33603. var face_vertex_uv = new Array(3);
  33604. var v012;
  33605. for (v012 = 0; v012 < 3; v012++) {
  33606. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33607. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33608. }
  33609. // create all with normals
  33610. for (var face = 0; face < 20; face++) {
  33611. // 3 vertex per face
  33612. for (v012 = 0; v012 < 3; v012++) {
  33613. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33614. var v_id = ico_indices[3 * face + v012];
  33615. // vertex have 3D position (x,y,z)
  33616. 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]);
  33617. // Normalize to get normal, then scale to radius
  33618. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33619. // uv Coordinates from vertex ID
  33620. 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);
  33621. }
  33622. // Subdivide the face (interpolate pos, norm, uv)
  33623. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33624. // - norm is linear interpolation of vertex corner normal
  33625. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33626. // - uv is linear interpolation
  33627. //
  33628. // Topology is as below for sub-divide by 2
  33629. // vertex shown as v0,v1,v2
  33630. // interp index is i1 to progress in range [v0,v1[
  33631. // interp index is i2 to progress in range [v0,v2[
  33632. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33633. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33634. //
  33635. //
  33636. // i2 v2
  33637. // ^ ^
  33638. // / / \
  33639. // / / \
  33640. // / / \
  33641. // / / (0,1) \
  33642. // / #---------\
  33643. // / / \ (0,0)'/ \
  33644. // / / \ / \
  33645. // / / \ / \
  33646. // / / (0,0) \ / (1,0) \
  33647. // / #---------#---------\
  33648. // v0 v1
  33649. //
  33650. // --------------------> i1
  33651. //
  33652. // interp of (i1,i2):
  33653. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33654. // along i1 : lerp(x0,x1, i1/(S-i2))
  33655. //
  33656. // centroid of triangle is needed to get help normal computation
  33657. // (c1,c2) are used for centroid location
  33658. var interp_vertex = function (i1, i2, c1, c2) {
  33659. // vertex is interpolated from
  33660. // - face_vertex_pos[0..2]
  33661. // - face_vertex_uv[0..2]
  33662. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33663. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33664. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33665. pos_interp.normalize();
  33666. var vertex_normal;
  33667. if (flat) {
  33668. // in flat mode, recalculate normal as face centroid normal
  33669. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33670. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33671. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33672. }
  33673. else {
  33674. // in smooth mode, recalculate normal from each single vertex position
  33675. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33676. }
  33677. // Vertex normal need correction due to X,Y,Z radius scaling
  33678. vertex_normal.x /= radiusX;
  33679. vertex_normal.y /= radiusY;
  33680. vertex_normal.z /= radiusZ;
  33681. vertex_normal.normalize();
  33682. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33683. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33684. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33685. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33686. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33687. uvs.push(uv_interp.x, uv_interp.y);
  33688. // push each vertex has member of a face
  33689. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33690. indices.push(current_indice);
  33691. current_indice++;
  33692. };
  33693. for (var i2 = 0; i2 < subdivisions; i2++) {
  33694. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33695. // face : (i1,i2) for /\ :
  33696. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33697. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33698. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33699. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33700. if (i1 + i2 + 1 < subdivisions) {
  33701. // face : (i1,i2)' for \/ :
  33702. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33703. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33704. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33705. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33706. }
  33707. }
  33708. }
  33709. }
  33710. // Sides
  33711. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33712. // Result
  33713. var vertexData = new VertexData();
  33714. vertexData.indices = indices;
  33715. vertexData.positions = positions;
  33716. vertexData.normals = normals;
  33717. vertexData.uvs = uvs;
  33718. return vertexData;
  33719. };
  33720. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33721. VertexData.CreatePolyhedron = function (options) {
  33722. // provided polyhedron types :
  33723. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33724. // 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)
  33725. var polyhedra = [];
  33726. 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]] };
  33727. 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]] };
  33728. polyhedra[2] = {
  33729. 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]],
  33730. 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]]
  33731. };
  33732. polyhedra[3] = {
  33733. 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]],
  33734. 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]]
  33735. };
  33736. polyhedra[4] = {
  33737. 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]],
  33738. 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]]
  33739. };
  33740. 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]] };
  33741. 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]] };
  33742. 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]] };
  33743. 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]] };
  33744. 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]] };
  33745. 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]] };
  33746. 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]] };
  33747. 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]] };
  33748. 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]] };
  33749. polyhedra[14] = {
  33750. 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]],
  33751. 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]]
  33752. };
  33753. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33754. var size = options.size;
  33755. var sizeX = options.sizeX || size || 1;
  33756. var sizeY = options.sizeY || size || 1;
  33757. var sizeZ = options.sizeZ || size || 1;
  33758. var data = options.custom || polyhedra[type];
  33759. var nbfaces = data.face.length;
  33760. var faceUV = options.faceUV || new Array(nbfaces);
  33761. var faceColors = options.faceColors;
  33762. var flat = (options.flat === undefined) ? true : options.flat;
  33763. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33764. var positions = [];
  33765. var indices = [];
  33766. var normals = [];
  33767. var uvs = [];
  33768. var colors = [];
  33769. var index = 0;
  33770. var faceIdx = 0; // face cursor in the array "indexes"
  33771. var indexes = [];
  33772. var i = 0;
  33773. var f = 0;
  33774. var u, v, ang, x, y, tmp;
  33775. // default face colors and UV if undefined
  33776. if (flat) {
  33777. for (f = 0; f < nbfaces; f++) {
  33778. if (faceColors && faceColors[f] === undefined) {
  33779. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33780. }
  33781. if (faceUV && faceUV[f] === undefined) {
  33782. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33783. }
  33784. }
  33785. }
  33786. if (!flat) {
  33787. for (i = 0; i < data.vertex.length; i++) {
  33788. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33789. uvs.push(0, 0);
  33790. }
  33791. for (f = 0; f < nbfaces; f++) {
  33792. for (i = 0; i < data.face[f].length - 2; i++) {
  33793. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33794. }
  33795. }
  33796. }
  33797. else {
  33798. for (f = 0; f < nbfaces; f++) {
  33799. var fl = data.face[f].length; // number of vertices of the current face
  33800. ang = 2 * Math.PI / fl;
  33801. x = 0.5 * Math.tan(ang / 2);
  33802. y = 0.5;
  33803. // positions, uvs, colors
  33804. for (i = 0; i < fl; i++) {
  33805. // positions
  33806. 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);
  33807. indexes.push(index);
  33808. index++;
  33809. // uvs
  33810. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33811. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33812. uvs.push(u, v);
  33813. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33814. y = x * Math.sin(ang) + y * Math.cos(ang);
  33815. x = tmp;
  33816. // colors
  33817. if (faceColors) {
  33818. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33819. }
  33820. }
  33821. // indices from indexes
  33822. for (i = 0; i < fl - 2; i++) {
  33823. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33824. }
  33825. faceIdx += fl;
  33826. }
  33827. }
  33828. VertexData.ComputeNormals(positions, indices, normals);
  33829. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33830. var vertexData = new VertexData();
  33831. vertexData.positions = positions;
  33832. vertexData.indices = indices;
  33833. vertexData.normals = normals;
  33834. vertexData.uvs = uvs;
  33835. if (faceColors && flat) {
  33836. vertexData.colors = colors;
  33837. }
  33838. return vertexData;
  33839. };
  33840. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33841. VertexData.CreateTorusKnot = function (options) {
  33842. var indices = [];
  33843. var positions = [];
  33844. var normals = [];
  33845. var uvs = [];
  33846. var radius = options.radius || 2;
  33847. var tube = options.tube || 0.5;
  33848. var radialSegments = options.radialSegments || 32;
  33849. var tubularSegments = options.tubularSegments || 32;
  33850. var p = options.p || 2;
  33851. var q = options.q || 3;
  33852. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33853. // Helper
  33854. var getPos = function (angle) {
  33855. var cu = Math.cos(angle);
  33856. var su = Math.sin(angle);
  33857. var quOverP = q / p * angle;
  33858. var cs = Math.cos(quOverP);
  33859. var tx = radius * (2 + cs) * 0.5 * cu;
  33860. var ty = radius * (2 + cs) * su * 0.5;
  33861. var tz = radius * Math.sin(quOverP) * 0.5;
  33862. return new BABYLON.Vector3(tx, ty, tz);
  33863. };
  33864. // Vertices
  33865. var i;
  33866. var j;
  33867. for (i = 0; i <= radialSegments; i++) {
  33868. var modI = i % radialSegments;
  33869. var u = modI / radialSegments * 2 * p * Math.PI;
  33870. var p1 = getPos(u);
  33871. var p2 = getPos(u + 0.01);
  33872. var tang = p2.subtract(p1);
  33873. var n = p2.add(p1);
  33874. var bitan = BABYLON.Vector3.Cross(tang, n);
  33875. n = BABYLON.Vector3.Cross(bitan, tang);
  33876. bitan.normalize();
  33877. n.normalize();
  33878. for (j = 0; j < tubularSegments; j++) {
  33879. var modJ = j % tubularSegments;
  33880. var v = modJ / tubularSegments * 2 * Math.PI;
  33881. var cx = -tube * Math.cos(v);
  33882. var cy = tube * Math.sin(v);
  33883. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33884. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33885. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33886. uvs.push(i / radialSegments);
  33887. uvs.push(j / tubularSegments);
  33888. }
  33889. }
  33890. for (i = 0; i < radialSegments; i++) {
  33891. for (j = 0; j < tubularSegments; j++) {
  33892. var jNext = (j + 1) % tubularSegments;
  33893. var a = i * tubularSegments + j;
  33894. var b = (i + 1) * tubularSegments + j;
  33895. var c = (i + 1) * tubularSegments + jNext;
  33896. var d = i * tubularSegments + jNext;
  33897. indices.push(d);
  33898. indices.push(b);
  33899. indices.push(a);
  33900. indices.push(d);
  33901. indices.push(c);
  33902. indices.push(b);
  33903. }
  33904. }
  33905. // Normals
  33906. VertexData.ComputeNormals(positions, indices, normals);
  33907. // Sides
  33908. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33909. // Result
  33910. var vertexData = new VertexData();
  33911. vertexData.indices = indices;
  33912. vertexData.positions = positions;
  33913. vertexData.normals = normals;
  33914. vertexData.uvs = uvs;
  33915. return vertexData;
  33916. };
  33917. // Tools
  33918. /**
  33919. * @param {any} - positions (number[] or Float32Array)
  33920. * @param {any} - indices (number[] or Uint16Array)
  33921. * @param {any} - normals (number[] or Float32Array)
  33922. */
  33923. VertexData.ComputeNormals = function (positions, indices, normals) {
  33924. var index = 0;
  33925. var p1p2x = 0.0;
  33926. var p1p2y = 0.0;
  33927. var p1p2z = 0.0;
  33928. var p3p2x = 0.0;
  33929. var p3p2y = 0.0;
  33930. var p3p2z = 0.0;
  33931. var faceNormalx = 0.0;
  33932. var faceNormaly = 0.0;
  33933. var faceNormalz = 0.0;
  33934. var length = 0.0;
  33935. var i1 = 0;
  33936. var i2 = 0;
  33937. var i3 = 0;
  33938. for (index = 0; index < positions.length; index++) {
  33939. normals[index] = 0.0;
  33940. }
  33941. // indice triplet = 1 face
  33942. var nbFaces = indices.length / 3;
  33943. for (index = 0; index < nbFaces; index++) {
  33944. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  33945. i2 = indices[index * 3 + 1];
  33946. i3 = indices[index * 3 + 2];
  33947. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  33948. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  33949. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  33950. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  33951. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  33952. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  33953. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  33954. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  33955. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  33956. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33957. length = (length === 0) ? 1.0 : length;
  33958. faceNormalx /= length; // normalize this normal
  33959. faceNormaly /= length;
  33960. faceNormalz /= length;
  33961. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  33962. normals[i1 * 3 + 1] += faceNormaly;
  33963. normals[i1 * 3 + 2] += faceNormalz;
  33964. normals[i2 * 3] += faceNormalx;
  33965. normals[i2 * 3 + 1] += faceNormaly;
  33966. normals[i2 * 3 + 2] += faceNormalz;
  33967. normals[i3 * 3] += faceNormalx;
  33968. normals[i3 * 3 + 1] += faceNormaly;
  33969. normals[i3 * 3 + 2] += faceNormalz;
  33970. }
  33971. // last normalization of each normal
  33972. for (index = 0; index < normals.length / 3; index++) {
  33973. faceNormalx = normals[index * 3];
  33974. faceNormaly = normals[index * 3 + 1];
  33975. faceNormalz = normals[index * 3 + 2];
  33976. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33977. length = (length === 0) ? 1.0 : length;
  33978. faceNormalx /= length;
  33979. faceNormaly /= length;
  33980. faceNormalz /= length;
  33981. normals[index * 3] = faceNormalx;
  33982. normals[index * 3 + 1] = faceNormaly;
  33983. normals[index * 3 + 2] = faceNormalz;
  33984. }
  33985. };
  33986. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  33987. var li = indices.length;
  33988. var ln = normals.length;
  33989. var i;
  33990. var n;
  33991. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33992. switch (sideOrientation) {
  33993. case BABYLON.Mesh.FRONTSIDE:
  33994. // nothing changed
  33995. break;
  33996. case BABYLON.Mesh.BACKSIDE:
  33997. var tmp;
  33998. // indices
  33999. for (i = 0; i < li; i += 3) {
  34000. tmp = indices[i];
  34001. indices[i] = indices[i + 2];
  34002. indices[i + 2] = tmp;
  34003. }
  34004. // normals
  34005. for (n = 0; n < ln; n++) {
  34006. normals[n] = -normals[n];
  34007. }
  34008. break;
  34009. case BABYLON.Mesh.DOUBLESIDE:
  34010. // positions
  34011. var lp = positions.length;
  34012. var l = lp / 3;
  34013. for (var p = 0; p < lp; p++) {
  34014. positions[lp + p] = positions[p];
  34015. }
  34016. // indices
  34017. for (i = 0; i < li; i += 3) {
  34018. indices[i + li] = indices[i + 2] + l;
  34019. indices[i + 1 + li] = indices[i + 1] + l;
  34020. indices[i + 2 + li] = indices[i] + l;
  34021. }
  34022. // normals
  34023. for (n = 0; n < ln; n++) {
  34024. normals[ln + n] = -normals[n];
  34025. }
  34026. // uvs
  34027. var lu = uvs.length;
  34028. for (var u = 0; u < lu; u++) {
  34029. uvs[u + lu] = uvs[u];
  34030. }
  34031. break;
  34032. }
  34033. };
  34034. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34035. var vertexData = new VertexData();
  34036. // positions
  34037. var positions = parsedVertexData.positions;
  34038. if (positions) {
  34039. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34040. }
  34041. // normals
  34042. var normals = parsedVertexData.normals;
  34043. if (normals) {
  34044. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34045. }
  34046. // uvs
  34047. var uvs = parsedVertexData.uvs;
  34048. if (uvs) {
  34049. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34050. }
  34051. // uv2s
  34052. var uv2s = parsedVertexData.uv2s;
  34053. if (uv2s) {
  34054. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34055. }
  34056. // uv3s
  34057. var uv3s = parsedVertexData.uv3s;
  34058. if (uv3s) {
  34059. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34060. }
  34061. // uv4s
  34062. var uv4s = parsedVertexData.uv4s;
  34063. if (uv4s) {
  34064. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34065. }
  34066. // uv5s
  34067. var uv5s = parsedVertexData.uv5s;
  34068. if (uv5s) {
  34069. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34070. }
  34071. // uv6s
  34072. var uv6s = parsedVertexData.uv6s;
  34073. if (uv6s) {
  34074. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34075. }
  34076. // colors
  34077. var colors = parsedVertexData.colors;
  34078. if (colors) {
  34079. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34080. }
  34081. // matricesIndices
  34082. var matricesIndices = parsedVertexData.matricesIndices;
  34083. if (matricesIndices) {
  34084. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34085. }
  34086. // matricesWeights
  34087. var matricesWeights = parsedVertexData.matricesWeights;
  34088. if (matricesWeights) {
  34089. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34090. }
  34091. // indices
  34092. var indices = parsedVertexData.indices;
  34093. if (indices) {
  34094. vertexData.indices = indices;
  34095. }
  34096. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34097. };
  34098. return VertexData;
  34099. }());
  34100. BABYLON.VertexData = VertexData;
  34101. })(BABYLON || (BABYLON = {}));
  34102. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34103. var BABYLON;
  34104. (function (BABYLON) {
  34105. var Tags = (function () {
  34106. function Tags() {
  34107. }
  34108. Tags.EnableFor = function (obj) {
  34109. obj._tags = obj._tags || {};
  34110. obj.hasTags = function () {
  34111. return Tags.HasTags(obj);
  34112. };
  34113. obj.addTags = function (tagsString) {
  34114. return Tags.AddTagsTo(obj, tagsString);
  34115. };
  34116. obj.removeTags = function (tagsString) {
  34117. return Tags.RemoveTagsFrom(obj, tagsString);
  34118. };
  34119. obj.matchesTagsQuery = function (tagsQuery) {
  34120. return Tags.MatchesQuery(obj, tagsQuery);
  34121. };
  34122. };
  34123. Tags.DisableFor = function (obj) {
  34124. delete obj._tags;
  34125. delete obj.hasTags;
  34126. delete obj.addTags;
  34127. delete obj.removeTags;
  34128. delete obj.matchesTagsQuery;
  34129. };
  34130. Tags.HasTags = function (obj) {
  34131. if (!obj._tags) {
  34132. return false;
  34133. }
  34134. return !BABYLON.Tools.IsEmpty(obj._tags);
  34135. };
  34136. Tags.GetTags = function (obj, asString) {
  34137. if (asString === void 0) { asString = true; }
  34138. if (!obj._tags) {
  34139. return null;
  34140. }
  34141. if (asString) {
  34142. var tagsArray = [];
  34143. for (var tag in obj._tags) {
  34144. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  34145. tagsArray.push(tag);
  34146. }
  34147. }
  34148. return tagsArray.join(" ");
  34149. }
  34150. else {
  34151. return obj._tags;
  34152. }
  34153. };
  34154. // the tags 'true' and 'false' are reserved and cannot be used as tags
  34155. // a tag cannot start with '||', '&&', and '!'
  34156. // it cannot contain whitespaces
  34157. Tags.AddTagsTo = function (obj, tagsString) {
  34158. if (!tagsString) {
  34159. return;
  34160. }
  34161. if (typeof tagsString !== "string") {
  34162. return;
  34163. }
  34164. var tags = tagsString.split(" ");
  34165. tags.forEach(function (tag, index, array) {
  34166. Tags._AddTagTo(obj, tag);
  34167. });
  34168. };
  34169. Tags._AddTagTo = function (obj, tag) {
  34170. tag = tag.trim();
  34171. if (tag === "" || tag === "true" || tag === "false") {
  34172. return;
  34173. }
  34174. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  34175. return;
  34176. }
  34177. Tags.EnableFor(obj);
  34178. obj._tags[tag] = true;
  34179. };
  34180. Tags.RemoveTagsFrom = function (obj, tagsString) {
  34181. if (!Tags.HasTags(obj)) {
  34182. return;
  34183. }
  34184. var tags = tagsString.split(" ");
  34185. for (var t in tags) {
  34186. Tags._RemoveTagFrom(obj, tags[t]);
  34187. }
  34188. };
  34189. Tags._RemoveTagFrom = function (obj, tag) {
  34190. delete obj._tags[tag];
  34191. };
  34192. Tags.MatchesQuery = function (obj, tagsQuery) {
  34193. if (tagsQuery === undefined) {
  34194. return true;
  34195. }
  34196. if (tagsQuery === "") {
  34197. return Tags.HasTags(obj);
  34198. }
  34199. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  34200. };
  34201. return Tags;
  34202. }());
  34203. BABYLON.Tags = Tags;
  34204. })(BABYLON || (BABYLON = {}));
  34205. //# sourceMappingURL=babylon.tags.js.map
  34206. var BABYLON;
  34207. (function (BABYLON) {
  34208. var Internals;
  34209. (function (Internals) {
  34210. var AndOrNotEvaluator = (function () {
  34211. function AndOrNotEvaluator() {
  34212. }
  34213. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  34214. if (!query.match(/\([^\(\)]*\)/g)) {
  34215. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  34216. }
  34217. else {
  34218. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  34219. // remove parenthesis
  34220. r = r.slice(1, r.length - 1);
  34221. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  34222. });
  34223. }
  34224. if (query === "true") {
  34225. return true;
  34226. }
  34227. if (query === "false") {
  34228. return false;
  34229. }
  34230. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  34231. };
  34232. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  34233. evaluateCallback = evaluateCallback || (function (r) {
  34234. return r === "true" ? true : false;
  34235. });
  34236. var result;
  34237. var or = parenthesisContent.split("||");
  34238. for (var i in or) {
  34239. if (or.hasOwnProperty(i)) {
  34240. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  34241. var and = ori.split("&&");
  34242. if (and.length > 1) {
  34243. for (var j = 0; j < and.length; ++j) {
  34244. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  34245. if (andj !== "true" && andj !== "false") {
  34246. if (andj[0] === "!") {
  34247. result = !evaluateCallback(andj.substring(1));
  34248. }
  34249. else {
  34250. result = evaluateCallback(andj);
  34251. }
  34252. }
  34253. else {
  34254. result = andj === "true" ? true : false;
  34255. }
  34256. if (!result) {
  34257. ori = "false";
  34258. break;
  34259. }
  34260. }
  34261. }
  34262. if (result || ori === "true") {
  34263. result = true;
  34264. break;
  34265. }
  34266. // result equals false (or undefined)
  34267. if (ori !== "true" && ori !== "false") {
  34268. if (ori[0] === "!") {
  34269. result = !evaluateCallback(ori.substring(1));
  34270. }
  34271. else {
  34272. result = evaluateCallback(ori);
  34273. }
  34274. }
  34275. else {
  34276. result = ori === "true" ? true : false;
  34277. }
  34278. }
  34279. }
  34280. // the whole parenthesis scope is replaced by 'true' or 'false'
  34281. return result ? "true" : "false";
  34282. };
  34283. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  34284. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  34285. // remove whitespaces
  34286. r = r.replace(/[\s]/g, function () { return ""; });
  34287. return r.length % 2 ? "!" : "";
  34288. });
  34289. booleanString = booleanString.trim();
  34290. if (booleanString === "!true") {
  34291. booleanString = "false";
  34292. }
  34293. else if (booleanString === "!false") {
  34294. booleanString = "true";
  34295. }
  34296. return booleanString;
  34297. };
  34298. return AndOrNotEvaluator;
  34299. }());
  34300. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  34301. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34302. })(BABYLON || (BABYLON = {}));
  34303. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  34304. var BABYLON;
  34305. (function (BABYLON) {
  34306. var PostProcessRenderPass = (function () {
  34307. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  34308. this._enabled = true;
  34309. this._refCount = 0;
  34310. this._name = name;
  34311. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  34312. this.setRenderList(renderList);
  34313. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  34314. this._renderTexture.onAfterRenderObservable.add(afterRender);
  34315. this._scene = scene;
  34316. this._renderList = renderList;
  34317. }
  34318. // private
  34319. PostProcessRenderPass.prototype._incRefCount = function () {
  34320. if (this._refCount === 0) {
  34321. this._scene.customRenderTargets.push(this._renderTexture);
  34322. }
  34323. return ++this._refCount;
  34324. };
  34325. PostProcessRenderPass.prototype._decRefCount = function () {
  34326. this._refCount--;
  34327. if (this._refCount <= 0) {
  34328. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  34329. }
  34330. return this._refCount;
  34331. };
  34332. PostProcessRenderPass.prototype._update = function () {
  34333. this.setRenderList(this._renderList);
  34334. };
  34335. // public
  34336. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  34337. this._renderTexture.renderList = renderList;
  34338. };
  34339. PostProcessRenderPass.prototype.getRenderTexture = function () {
  34340. return this._renderTexture;
  34341. };
  34342. return PostProcessRenderPass;
  34343. }());
  34344. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  34345. })(BABYLON || (BABYLON = {}));
  34346. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  34347. var BABYLON;
  34348. (function (BABYLON) {
  34349. var PostProcessRenderEffect = (function () {
  34350. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  34351. this._engine = engine;
  34352. this._name = name;
  34353. this._singleInstance = singleInstance || true;
  34354. this._getPostProcess = getPostProcess;
  34355. this._cameras = [];
  34356. this._indicesForCamera = [];
  34357. this._postProcesses = {};
  34358. this._renderPasses = {};
  34359. this._renderEffectAsPasses = {};
  34360. }
  34361. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  34362. get: function () {
  34363. for (var index in this._postProcesses) {
  34364. if (!this._postProcesses[index].isSupported) {
  34365. return false;
  34366. }
  34367. }
  34368. return true;
  34369. },
  34370. enumerable: true,
  34371. configurable: true
  34372. });
  34373. PostProcessRenderEffect.prototype._update = function () {
  34374. for (var renderPassName in this._renderPasses) {
  34375. this._renderPasses[renderPassName]._update();
  34376. }
  34377. };
  34378. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  34379. this._renderPasses[renderPass._name] = renderPass;
  34380. this._linkParameters();
  34381. };
  34382. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  34383. delete this._renderPasses[renderPass._name];
  34384. this._linkParameters();
  34385. };
  34386. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  34387. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  34388. this._linkParameters();
  34389. };
  34390. PostProcessRenderEffect.prototype.getPass = function (passName) {
  34391. for (var renderPassName in this._renderPasses) {
  34392. if (renderPassName === passName) {
  34393. return this._renderPasses[passName];
  34394. }
  34395. }
  34396. };
  34397. PostProcessRenderEffect.prototype.emptyPasses = function () {
  34398. this._renderPasses = {};
  34399. this._linkParameters();
  34400. };
  34401. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  34402. var cameraKey;
  34403. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34404. for (var i = 0; i < _cam.length; i++) {
  34405. var camera = _cam[i];
  34406. var cameraName = camera.name;
  34407. if (this._singleInstance) {
  34408. cameraKey = 0;
  34409. }
  34410. else {
  34411. cameraKey = cameraName;
  34412. }
  34413. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  34414. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  34415. if (!this._indicesForCamera[cameraName]) {
  34416. this._indicesForCamera[cameraName] = [];
  34417. }
  34418. this._indicesForCamera[cameraName].push(index);
  34419. if (this._cameras.indexOf(camera) === -1) {
  34420. this._cameras[cameraName] = camera;
  34421. }
  34422. for (var passName in this._renderPasses) {
  34423. this._renderPasses[passName]._incRefCount();
  34424. }
  34425. }
  34426. this._linkParameters();
  34427. };
  34428. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  34429. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34430. for (var i = 0; i < _cam.length; i++) {
  34431. var camera = _cam[i];
  34432. var cameraName = camera.name;
  34433. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34434. var index = this._cameras.indexOf(cameraName);
  34435. this._indicesForCamera.splice(index, 1);
  34436. this._cameras.splice(index, 1);
  34437. for (var passName in this._renderPasses) {
  34438. this._renderPasses[passName]._decRefCount();
  34439. }
  34440. }
  34441. };
  34442. PostProcessRenderEffect.prototype._enable = function (cameras) {
  34443. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34444. for (var i = 0; i < _cam.length; i++) {
  34445. var camera = _cam[i];
  34446. var cameraName = camera.name;
  34447. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  34448. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  34449. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  34450. }
  34451. }
  34452. for (var passName in this._renderPasses) {
  34453. this._renderPasses[passName]._incRefCount();
  34454. }
  34455. }
  34456. };
  34457. PostProcessRenderEffect.prototype._disable = function (cameras) {
  34458. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34459. for (var i = 0; i < _cam.length; i++) {
  34460. var camera = _cam[i];
  34461. var cameraName = camera.Name;
  34462. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34463. for (var passName in this._renderPasses) {
  34464. this._renderPasses[passName]._decRefCount();
  34465. }
  34466. }
  34467. };
  34468. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  34469. if (this._singleInstance) {
  34470. return this._postProcesses[0];
  34471. }
  34472. else {
  34473. return this._postProcesses[camera.name];
  34474. }
  34475. };
  34476. PostProcessRenderEffect.prototype._linkParameters = function () {
  34477. var _this = this;
  34478. for (var index in this._postProcesses) {
  34479. if (this.applyParameters) {
  34480. this.applyParameters(this._postProcesses[index]);
  34481. }
  34482. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  34483. _this._linkTextures(effect);
  34484. });
  34485. }
  34486. };
  34487. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  34488. for (var renderPassName in this._renderPasses) {
  34489. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  34490. }
  34491. for (var renderEffectName in this._renderEffectAsPasses) {
  34492. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  34493. }
  34494. };
  34495. return PostProcessRenderEffect;
  34496. }());
  34497. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  34498. })(BABYLON || (BABYLON = {}));
  34499. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  34500. var BABYLON;
  34501. (function (BABYLON) {
  34502. var PostProcessRenderPipeline = (function () {
  34503. function PostProcessRenderPipeline(engine, name) {
  34504. this._engine = engine;
  34505. this._name = name;
  34506. this._renderEffects = {};
  34507. this._renderEffectsForIsolatedPass = {};
  34508. this._cameras = [];
  34509. }
  34510. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  34511. get: function () {
  34512. for (var renderEffectName in this._renderEffects) {
  34513. if (!this._renderEffects[renderEffectName].isSupported) {
  34514. return false;
  34515. }
  34516. }
  34517. return true;
  34518. },
  34519. enumerable: true,
  34520. configurable: true
  34521. });
  34522. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  34523. this._renderEffects[renderEffect._name] = renderEffect;
  34524. };
  34525. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  34526. var renderEffects = this._renderEffects[renderEffectName];
  34527. if (!renderEffects) {
  34528. return;
  34529. }
  34530. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34531. };
  34532. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  34533. var renderEffects = this._renderEffects[renderEffectName];
  34534. if (!renderEffects) {
  34535. return;
  34536. }
  34537. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34538. };
  34539. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  34540. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34541. var indicesToDelete = [];
  34542. var i;
  34543. for (i = 0; i < _cam.length; i++) {
  34544. var camera = _cam[i];
  34545. var cameraName = camera.name;
  34546. if (this._cameras.indexOf(camera) === -1) {
  34547. this._cameras[cameraName] = camera;
  34548. }
  34549. else if (unique) {
  34550. indicesToDelete.push(i);
  34551. }
  34552. }
  34553. for (i = 0; i < indicesToDelete.length; i++) {
  34554. cameras.splice(indicesToDelete[i], 1);
  34555. }
  34556. for (var renderEffectName in this._renderEffects) {
  34557. this._renderEffects[renderEffectName]._attachCameras(_cam);
  34558. }
  34559. };
  34560. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  34561. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34562. for (var renderEffectName in this._renderEffects) {
  34563. this._renderEffects[renderEffectName]._detachCameras(_cam);
  34564. }
  34565. for (var i = 0; i < _cam.length; i++) {
  34566. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  34567. }
  34568. };
  34569. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  34570. var _this = this;
  34571. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34572. var pass = null;
  34573. var renderEffectName;
  34574. for (renderEffectName in this._renderEffects) {
  34575. pass = this._renderEffects[renderEffectName].getPass(passName);
  34576. if (pass != null) {
  34577. break;
  34578. }
  34579. }
  34580. if (pass === null) {
  34581. return;
  34582. }
  34583. for (renderEffectName in this._renderEffects) {
  34584. this._renderEffects[renderEffectName]._disable(_cam);
  34585. }
  34586. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  34587. for (var i = 0; i < _cam.length; i++) {
  34588. var camera = _cam[i];
  34589. var cameraName = camera.name;
  34590. 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); });
  34591. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  34592. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  34593. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  34594. }
  34595. };
  34596. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  34597. var _this = this;
  34598. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34599. for (var i = 0; i < _cam.length; i++) {
  34600. var camera = _cam[i];
  34601. var cameraName = camera.name;
  34602. 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); });
  34603. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  34604. }
  34605. for (var renderEffectName in this._renderEffects) {
  34606. this._renderEffects[renderEffectName]._enable(_cam);
  34607. }
  34608. };
  34609. PostProcessRenderPipeline.prototype._update = function () {
  34610. for (var renderEffectName in this._renderEffects) {
  34611. this._renderEffects[renderEffectName]._update();
  34612. }
  34613. for (var i = 0; i < this._cameras.length; i++) {
  34614. var cameraName = this._cameras[i].name;
  34615. if (this._renderEffectsForIsolatedPass[cameraName]) {
  34616. this._renderEffectsForIsolatedPass[cameraName]._update();
  34617. }
  34618. }
  34619. };
  34620. PostProcessRenderPipeline.prototype.dispose = function () {
  34621. // Must be implemented by children
  34622. };
  34623. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  34624. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  34625. return PostProcessRenderPipeline;
  34626. }());
  34627. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  34628. })(BABYLON || (BABYLON = {}));
  34629. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  34630. var BABYLON;
  34631. (function (BABYLON) {
  34632. var PostProcessRenderPipelineManager = (function () {
  34633. function PostProcessRenderPipelineManager() {
  34634. this._renderPipelines = {};
  34635. }
  34636. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  34637. this._renderPipelines[renderPipeline._name] = renderPipeline;
  34638. };
  34639. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  34640. var renderPipeline = this._renderPipelines[renderPipelineName];
  34641. if (!renderPipeline) {
  34642. return;
  34643. }
  34644. renderPipeline._attachCameras(cameras, unique);
  34645. };
  34646. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  34647. var renderPipeline = this._renderPipelines[renderPipelineName];
  34648. if (!renderPipeline) {
  34649. return;
  34650. }
  34651. renderPipeline._detachCameras(cameras);
  34652. };
  34653. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34654. var renderPipeline = this._renderPipelines[renderPipelineName];
  34655. if (!renderPipeline) {
  34656. return;
  34657. }
  34658. renderPipeline._enableEffect(renderEffectName, cameras);
  34659. };
  34660. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34661. var renderPipeline = this._renderPipelines[renderPipelineName];
  34662. if (!renderPipeline) {
  34663. return;
  34664. }
  34665. renderPipeline._disableEffect(renderEffectName, cameras);
  34666. };
  34667. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  34668. var renderPipeline = this._renderPipelines[renderPipelineName];
  34669. if (!renderPipeline) {
  34670. return;
  34671. }
  34672. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  34673. };
  34674. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  34675. var renderPipeline = this._renderPipelines[renderPipelineName];
  34676. if (!renderPipeline) {
  34677. return;
  34678. }
  34679. renderPipeline._disableDisplayOnlyPass(cameras);
  34680. };
  34681. PostProcessRenderPipelineManager.prototype.update = function () {
  34682. for (var renderPipelineName in this._renderPipelines) {
  34683. var pipeline = this._renderPipelines[renderPipelineName];
  34684. if (!pipeline.isSupported) {
  34685. pipeline.dispose();
  34686. delete this._renderPipelines[renderPipelineName];
  34687. }
  34688. else {
  34689. pipeline._update();
  34690. }
  34691. }
  34692. };
  34693. return PostProcessRenderPipelineManager;
  34694. }());
  34695. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  34696. })(BABYLON || (BABYLON = {}));
  34697. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  34698. var BABYLON;
  34699. (function (BABYLON) {
  34700. var BoundingBoxRenderer = (function () {
  34701. function BoundingBoxRenderer(scene) {
  34702. this.frontColor = new BABYLON.Color3(1, 1, 1);
  34703. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  34704. this.showBackLines = true;
  34705. this.renderList = new BABYLON.SmartArray(32);
  34706. this._vertexBuffers = {};
  34707. this._scene = scene;
  34708. }
  34709. BoundingBoxRenderer.prototype._prepareRessources = function () {
  34710. if (this._colorShader) {
  34711. return;
  34712. }
  34713. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  34714. attributes: [BABYLON.VertexBuffer.PositionKind],
  34715. uniforms: ["worldViewProjection", "color"]
  34716. });
  34717. var engine = this._scene.getEngine();
  34718. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  34719. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  34720. 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]);
  34721. };
  34722. BoundingBoxRenderer.prototype.reset = function () {
  34723. this.renderList.reset();
  34724. };
  34725. BoundingBoxRenderer.prototype.render = function () {
  34726. if (this.renderList.length === 0) {
  34727. return;
  34728. }
  34729. this._prepareRessources();
  34730. if (!this._colorShader.isReady()) {
  34731. return;
  34732. }
  34733. var engine = this._scene.getEngine();
  34734. engine.setDepthWrite(false);
  34735. this._colorShader._preBind();
  34736. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34737. var boundingBox = this.renderList.data[boundingBoxIndex];
  34738. var min = boundingBox.minimum;
  34739. var max = boundingBox.maximum;
  34740. var diff = max.subtract(min);
  34741. var median = min.add(diff.scale(0.5));
  34742. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  34743. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  34744. .multiply(boundingBox.getWorldMatrix());
  34745. // VBOs
  34746. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  34747. if (this.showBackLines) {
  34748. // Back
  34749. engine.setDepthFunctionToGreaterOrEqual();
  34750. this._scene.resetCachedMaterial();
  34751. this._colorShader.setColor4("color", this.backColor.toColor4());
  34752. this._colorShader.bind(worldMatrix);
  34753. // Draw order
  34754. engine.draw(false, 0, 24);
  34755. }
  34756. // Front
  34757. engine.setDepthFunctionToLess();
  34758. this._scene.resetCachedMaterial();
  34759. this._colorShader.setColor4("color", this.frontColor.toColor4());
  34760. this._colorShader.bind(worldMatrix);
  34761. // Draw order
  34762. engine.draw(false, 0, 24);
  34763. }
  34764. this._colorShader.unbind();
  34765. engine.setDepthFunctionToLessOrEqual();
  34766. engine.setDepthWrite(true);
  34767. };
  34768. BoundingBoxRenderer.prototype.dispose = function () {
  34769. if (!this._colorShader) {
  34770. return;
  34771. }
  34772. this._colorShader.dispose();
  34773. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34774. if (buffer) {
  34775. buffer.dispose();
  34776. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34777. }
  34778. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34779. };
  34780. return BoundingBoxRenderer;
  34781. }());
  34782. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  34783. })(BABYLON || (BABYLON = {}));
  34784. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  34785. var BABYLON;
  34786. (function (BABYLON) {
  34787. var Condition = (function () {
  34788. function Condition(actionManager) {
  34789. this._actionManager = actionManager;
  34790. }
  34791. Condition.prototype.isValid = function () {
  34792. return true;
  34793. };
  34794. Condition.prototype._getProperty = function (propertyPath) {
  34795. return this._actionManager._getProperty(propertyPath);
  34796. };
  34797. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34798. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34799. };
  34800. Condition.prototype.serialize = function () {
  34801. };
  34802. Condition.prototype._serialize = function (serializedCondition) {
  34803. return {
  34804. type: 2,
  34805. children: [],
  34806. name: serializedCondition.name,
  34807. properties: serializedCondition.properties
  34808. };
  34809. };
  34810. return Condition;
  34811. }());
  34812. BABYLON.Condition = Condition;
  34813. var ValueCondition = (function (_super) {
  34814. __extends(ValueCondition, _super);
  34815. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  34816. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  34817. _super.call(this, actionManager);
  34818. this.propertyPath = propertyPath;
  34819. this.value = value;
  34820. this.operator = operator;
  34821. this._target = target;
  34822. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  34823. this._property = this._getProperty(this.propertyPath);
  34824. }
  34825. Object.defineProperty(ValueCondition, "IsEqual", {
  34826. get: function () {
  34827. return ValueCondition._IsEqual;
  34828. },
  34829. enumerable: true,
  34830. configurable: true
  34831. });
  34832. Object.defineProperty(ValueCondition, "IsDifferent", {
  34833. get: function () {
  34834. return ValueCondition._IsDifferent;
  34835. },
  34836. enumerable: true,
  34837. configurable: true
  34838. });
  34839. Object.defineProperty(ValueCondition, "IsGreater", {
  34840. get: function () {
  34841. return ValueCondition._IsGreater;
  34842. },
  34843. enumerable: true,
  34844. configurable: true
  34845. });
  34846. Object.defineProperty(ValueCondition, "IsLesser", {
  34847. get: function () {
  34848. return ValueCondition._IsLesser;
  34849. },
  34850. enumerable: true,
  34851. configurable: true
  34852. });
  34853. // Methods
  34854. ValueCondition.prototype.isValid = function () {
  34855. switch (this.operator) {
  34856. case ValueCondition.IsGreater:
  34857. return this._effectiveTarget[this._property] > this.value;
  34858. case ValueCondition.IsLesser:
  34859. return this._effectiveTarget[this._property] < this.value;
  34860. case ValueCondition.IsEqual:
  34861. case ValueCondition.IsDifferent:
  34862. var check;
  34863. if (this.value.equals) {
  34864. check = this.value.equals(this._effectiveTarget[this._property]);
  34865. }
  34866. else {
  34867. check = this.value === this._effectiveTarget[this._property];
  34868. }
  34869. return this.operator === ValueCondition.IsEqual ? check : !check;
  34870. }
  34871. return false;
  34872. };
  34873. ValueCondition.prototype.serialize = function () {
  34874. return this._serialize({
  34875. name: "ValueCondition",
  34876. properties: [
  34877. BABYLON.Action._GetTargetProperty(this._target),
  34878. { name: "propertyPath", value: this.propertyPath },
  34879. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34880. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  34881. ]
  34882. });
  34883. };
  34884. ValueCondition.GetOperatorName = function (operator) {
  34885. switch (operator) {
  34886. case ValueCondition._IsEqual: return "IsEqual";
  34887. case ValueCondition._IsDifferent: return "IsDifferent";
  34888. case ValueCondition._IsGreater: return "IsGreater";
  34889. case ValueCondition._IsLesser: return "IsLesser";
  34890. default: return "";
  34891. }
  34892. };
  34893. // Statics
  34894. ValueCondition._IsEqual = 0;
  34895. ValueCondition._IsDifferent = 1;
  34896. ValueCondition._IsGreater = 2;
  34897. ValueCondition._IsLesser = 3;
  34898. return ValueCondition;
  34899. }(Condition));
  34900. BABYLON.ValueCondition = ValueCondition;
  34901. var PredicateCondition = (function (_super) {
  34902. __extends(PredicateCondition, _super);
  34903. function PredicateCondition(actionManager, predicate) {
  34904. _super.call(this, actionManager);
  34905. this.predicate = predicate;
  34906. }
  34907. PredicateCondition.prototype.isValid = function () {
  34908. return this.predicate();
  34909. };
  34910. return PredicateCondition;
  34911. }(Condition));
  34912. BABYLON.PredicateCondition = PredicateCondition;
  34913. var StateCondition = (function (_super) {
  34914. __extends(StateCondition, _super);
  34915. function StateCondition(actionManager, target, value) {
  34916. _super.call(this, actionManager);
  34917. this.value = value;
  34918. this._target = target;
  34919. }
  34920. // Methods
  34921. StateCondition.prototype.isValid = function () {
  34922. return this._target.state === this.value;
  34923. };
  34924. StateCondition.prototype.serialize = function () {
  34925. return this._serialize({
  34926. name: "StateCondition",
  34927. properties: [
  34928. BABYLON.Action._GetTargetProperty(this._target),
  34929. { name: "value", value: this.value }
  34930. ]
  34931. });
  34932. };
  34933. return StateCondition;
  34934. }(Condition));
  34935. BABYLON.StateCondition = StateCondition;
  34936. })(BABYLON || (BABYLON = {}));
  34937. //# sourceMappingURL=babylon.condition.js.map
  34938. var BABYLON;
  34939. (function (BABYLON) {
  34940. var Action = (function () {
  34941. function Action(triggerOptions, condition) {
  34942. this.triggerOptions = triggerOptions;
  34943. if (triggerOptions.parameter) {
  34944. this.trigger = triggerOptions.trigger;
  34945. this._triggerParameter = triggerOptions.parameter;
  34946. }
  34947. else {
  34948. this.trigger = triggerOptions;
  34949. }
  34950. this._nextActiveAction = this;
  34951. this._condition = condition;
  34952. }
  34953. // Methods
  34954. Action.prototype._prepare = function () {
  34955. };
  34956. Action.prototype.getTriggerParameter = function () {
  34957. return this._triggerParameter;
  34958. };
  34959. Action.prototype._executeCurrent = function (evt) {
  34960. if (this._nextActiveAction._condition) {
  34961. var condition = this._nextActiveAction._condition;
  34962. var currentRenderId = this._actionManager.getScene().getRenderId();
  34963. // We cache the current evaluation for the current frame
  34964. if (condition._evaluationId === currentRenderId) {
  34965. if (!condition._currentResult) {
  34966. return;
  34967. }
  34968. }
  34969. else {
  34970. condition._evaluationId = currentRenderId;
  34971. if (!condition.isValid()) {
  34972. condition._currentResult = false;
  34973. return;
  34974. }
  34975. condition._currentResult = true;
  34976. }
  34977. }
  34978. this._nextActiveAction.execute(evt);
  34979. this.skipToNextActiveAction();
  34980. };
  34981. Action.prototype.execute = function (evt) {
  34982. };
  34983. Action.prototype.skipToNextActiveAction = function () {
  34984. if (this._nextActiveAction._child) {
  34985. if (!this._nextActiveAction._child._actionManager) {
  34986. this._nextActiveAction._child._actionManager = this._actionManager;
  34987. }
  34988. this._nextActiveAction = this._nextActiveAction._child;
  34989. }
  34990. else {
  34991. this._nextActiveAction = this;
  34992. }
  34993. };
  34994. Action.prototype.then = function (action) {
  34995. this._child = action;
  34996. action._actionManager = this._actionManager;
  34997. action._prepare();
  34998. return action;
  34999. };
  35000. Action.prototype._getProperty = function (propertyPath) {
  35001. return this._actionManager._getProperty(propertyPath);
  35002. };
  35003. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35004. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35005. };
  35006. Action.prototype.serialize = function (parent) {
  35007. };
  35008. // Called by BABYLON.Action objects in serialize(...). Internal use
  35009. Action.prototype._serialize = function (serializedAction, parent) {
  35010. var serializationObject = {
  35011. type: 1,
  35012. children: [],
  35013. name: serializedAction.name,
  35014. properties: serializedAction.properties || []
  35015. };
  35016. // Serialize child
  35017. if (this._child) {
  35018. this._child.serialize(serializationObject);
  35019. }
  35020. // Check if "this" has a condition
  35021. if (this._condition) {
  35022. var serializedCondition = this._condition.serialize();
  35023. serializedCondition.children.push(serializationObject);
  35024. if (parent) {
  35025. parent.children.push(serializedCondition);
  35026. }
  35027. return serializedCondition;
  35028. }
  35029. if (parent) {
  35030. parent.children.push(serializationObject);
  35031. }
  35032. return serializationObject;
  35033. };
  35034. Action._SerializeValueAsString = function (value) {
  35035. if (typeof value === "number") {
  35036. return value.toString();
  35037. }
  35038. if (typeof value === "boolean") {
  35039. return value ? "true" : "false";
  35040. }
  35041. if (value instanceof BABYLON.Vector2) {
  35042. return value.x + ", " + value.y;
  35043. }
  35044. if (value instanceof BABYLON.Vector3) {
  35045. return value.x + ", " + value.y + ", " + value.z;
  35046. }
  35047. if (value instanceof BABYLON.Color3) {
  35048. return value.r + ", " + value.g + ", " + value.b;
  35049. }
  35050. if (value instanceof BABYLON.Color4) {
  35051. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35052. }
  35053. return value; // string
  35054. };
  35055. Action._GetTargetProperty = function (target) {
  35056. return {
  35057. name: "target",
  35058. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35059. : target instanceof BABYLON.Light ? "LightProperties"
  35060. : target instanceof BABYLON.Camera ? "CameraProperties"
  35061. : "SceneProperties",
  35062. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35063. };
  35064. };
  35065. return Action;
  35066. }());
  35067. BABYLON.Action = Action;
  35068. })(BABYLON || (BABYLON = {}));
  35069. //# sourceMappingURL=babylon.action.js.map
  35070. var BABYLON;
  35071. (function (BABYLON) {
  35072. /**
  35073. * ActionEvent is the event beint sent when an action is triggered.
  35074. */
  35075. var ActionEvent = (function () {
  35076. /**
  35077. * @constructor
  35078. * @param source The mesh or sprite that triggered the action.
  35079. * @param pointerX The X mouse cursor position at the time of the event
  35080. * @param pointerY The Y mouse cursor position at the time of the event
  35081. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35082. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35083. */
  35084. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35085. this.source = source;
  35086. this.pointerX = pointerX;
  35087. this.pointerY = pointerY;
  35088. this.meshUnderPointer = meshUnderPointer;
  35089. this.sourceEvent = sourceEvent;
  35090. this.additionalData = additionalData;
  35091. }
  35092. /**
  35093. * Helper function to auto-create an ActionEvent from a source mesh.
  35094. * @param source The source mesh that triggered the event
  35095. * @param evt {Event} The original (browser) event
  35096. */
  35097. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35098. var scene = source.getScene();
  35099. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35100. };
  35101. /**
  35102. * Helper function to auto-create an ActionEvent from a source mesh.
  35103. * @param source The source sprite that triggered the event
  35104. * @param scene Scene associated with the sprite
  35105. * @param evt {Event} The original (browser) event
  35106. */
  35107. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35108. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35109. };
  35110. /**
  35111. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35112. * @param scene the scene where the event occurred
  35113. * @param evt {Event} The original (browser) event
  35114. */
  35115. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35116. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35117. };
  35118. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35119. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35120. };
  35121. return ActionEvent;
  35122. }());
  35123. BABYLON.ActionEvent = ActionEvent;
  35124. /**
  35125. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35126. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35127. */
  35128. var ActionManager = (function () {
  35129. function ActionManager(scene) {
  35130. // Members
  35131. this.actions = new Array();
  35132. this.hoverCursor = '';
  35133. this._scene = scene;
  35134. scene._actionManagers.push(this);
  35135. }
  35136. Object.defineProperty(ActionManager, "NothingTrigger", {
  35137. get: function () {
  35138. return ActionManager._NothingTrigger;
  35139. },
  35140. enumerable: true,
  35141. configurable: true
  35142. });
  35143. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35144. get: function () {
  35145. return ActionManager._OnPickTrigger;
  35146. },
  35147. enumerable: true,
  35148. configurable: true
  35149. });
  35150. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35151. get: function () {
  35152. return ActionManager._OnLeftPickTrigger;
  35153. },
  35154. enumerable: true,
  35155. configurable: true
  35156. });
  35157. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35158. get: function () {
  35159. return ActionManager._OnRightPickTrigger;
  35160. },
  35161. enumerable: true,
  35162. configurable: true
  35163. });
  35164. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35165. get: function () {
  35166. return ActionManager._OnCenterPickTrigger;
  35167. },
  35168. enumerable: true,
  35169. configurable: true
  35170. });
  35171. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35172. get: function () {
  35173. return ActionManager._OnPickDownTrigger;
  35174. },
  35175. enumerable: true,
  35176. configurable: true
  35177. });
  35178. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35179. get: function () {
  35180. return ActionManager._OnPickUpTrigger;
  35181. },
  35182. enumerable: true,
  35183. configurable: true
  35184. });
  35185. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35186. /// This trigger will only be raised if you also declared a OnPickDown
  35187. get: function () {
  35188. return ActionManager._OnPickOutTrigger;
  35189. },
  35190. enumerable: true,
  35191. configurable: true
  35192. });
  35193. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35194. get: function () {
  35195. return ActionManager._OnLongPressTrigger;
  35196. },
  35197. enumerable: true,
  35198. configurable: true
  35199. });
  35200. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35201. get: function () {
  35202. return ActionManager._OnPointerOverTrigger;
  35203. },
  35204. enumerable: true,
  35205. configurable: true
  35206. });
  35207. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35208. get: function () {
  35209. return ActionManager._OnPointerOutTrigger;
  35210. },
  35211. enumerable: true,
  35212. configurable: true
  35213. });
  35214. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35215. get: function () {
  35216. return ActionManager._OnEveryFrameTrigger;
  35217. },
  35218. enumerable: true,
  35219. configurable: true
  35220. });
  35221. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35222. get: function () {
  35223. return ActionManager._OnIntersectionEnterTrigger;
  35224. },
  35225. enumerable: true,
  35226. configurable: true
  35227. });
  35228. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35229. get: function () {
  35230. return ActionManager._OnIntersectionExitTrigger;
  35231. },
  35232. enumerable: true,
  35233. configurable: true
  35234. });
  35235. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35236. get: function () {
  35237. return ActionManager._OnKeyDownTrigger;
  35238. },
  35239. enumerable: true,
  35240. configurable: true
  35241. });
  35242. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35243. get: function () {
  35244. return ActionManager._OnKeyUpTrigger;
  35245. },
  35246. enumerable: true,
  35247. configurable: true
  35248. });
  35249. // Methods
  35250. ActionManager.prototype.dispose = function () {
  35251. var index = this._scene._actionManagers.indexOf(this);
  35252. if (index > -1) {
  35253. this._scene._actionManagers.splice(index, 1);
  35254. }
  35255. };
  35256. ActionManager.prototype.getScene = function () {
  35257. return this._scene;
  35258. };
  35259. /**
  35260. * Does this action manager handles actions of any of the given triggers
  35261. * @param {number[]} triggers - the triggers to be tested
  35262. * @return {boolean} whether one (or more) of the triggers is handeled
  35263. */
  35264. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35265. for (var index = 0; index < this.actions.length; index++) {
  35266. var action = this.actions[index];
  35267. if (triggers.indexOf(action.trigger) > -1) {
  35268. return true;
  35269. }
  35270. }
  35271. return false;
  35272. };
  35273. /**
  35274. * Does this action manager handles actions of a given trigger
  35275. * @param {number} trigger - the trigger to be tested
  35276. * @return {boolean} whether the trigger is handeled
  35277. */
  35278. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35279. for (var index = 0; index < this.actions.length; index++) {
  35280. var action = this.actions[index];
  35281. if (action.trigger === trigger) {
  35282. return true;
  35283. }
  35284. }
  35285. return false;
  35286. };
  35287. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35288. /**
  35289. * Does this action manager has pointer triggers
  35290. * @return {boolean} whether or not it has pointer triggers
  35291. */
  35292. get: function () {
  35293. for (var index = 0; index < this.actions.length; index++) {
  35294. var action = this.actions[index];
  35295. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35296. return true;
  35297. }
  35298. }
  35299. return false;
  35300. },
  35301. enumerable: true,
  35302. configurable: true
  35303. });
  35304. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35305. /**
  35306. * Does this action manager has pick triggers
  35307. * @return {boolean} whether or not it has pick triggers
  35308. */
  35309. get: function () {
  35310. for (var index = 0; index < this.actions.length; index++) {
  35311. var action = this.actions[index];
  35312. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35313. return true;
  35314. }
  35315. }
  35316. return false;
  35317. },
  35318. enumerable: true,
  35319. configurable: true
  35320. });
  35321. /**
  35322. * Registers an action to this action manager
  35323. * @param {BABYLON.Action} action - the action to be registered
  35324. * @return {BABYLON.Action} the action amended (prepared) after registration
  35325. */
  35326. ActionManager.prototype.registerAction = function (action) {
  35327. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35328. if (this.getScene().actionManager !== this) {
  35329. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35330. return null;
  35331. }
  35332. }
  35333. this.actions.push(action);
  35334. action._actionManager = this;
  35335. action._prepare();
  35336. return action;
  35337. };
  35338. /**
  35339. * Process a specific trigger
  35340. * @param {number} trigger - the trigger to process
  35341. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35342. */
  35343. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35344. for (var index = 0; index < this.actions.length; index++) {
  35345. var action = this.actions[index];
  35346. if (action.trigger === trigger) {
  35347. if (trigger === ActionManager.OnKeyUpTrigger
  35348. || trigger === ActionManager.OnKeyDownTrigger) {
  35349. var parameter = action.getTriggerParameter();
  35350. if (parameter) {
  35351. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35352. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35353. if (actualkey !== parameter.toLowerCase()) {
  35354. continue;
  35355. }
  35356. }
  35357. }
  35358. action._executeCurrent(evt);
  35359. }
  35360. }
  35361. };
  35362. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35363. var properties = propertyPath.split(".");
  35364. for (var index = 0; index < properties.length - 1; index++) {
  35365. target = target[properties[index]];
  35366. }
  35367. return target;
  35368. };
  35369. ActionManager.prototype._getProperty = function (propertyPath) {
  35370. var properties = propertyPath.split(".");
  35371. return properties[properties.length - 1];
  35372. };
  35373. ActionManager.prototype.serialize = function (name) {
  35374. var root = {
  35375. children: [],
  35376. name: name,
  35377. type: 3,
  35378. properties: [] // Empty for root but required
  35379. };
  35380. for (var i = 0; i < this.actions.length; i++) {
  35381. var triggerObject = {
  35382. type: 0,
  35383. children: [],
  35384. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35385. properties: []
  35386. };
  35387. var triggerOptions = this.actions[i].triggerOptions;
  35388. if (triggerOptions && typeof triggerOptions !== "number") {
  35389. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35390. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35391. }
  35392. else {
  35393. var parameter = {};
  35394. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35395. if (triggerOptions.parameter.mesh) {
  35396. parameter._meshId = triggerOptions.parameter.mesh.id;
  35397. }
  35398. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35399. }
  35400. }
  35401. // Serialize child action, recursively
  35402. this.actions[i].serialize(triggerObject);
  35403. // Add serialized trigger
  35404. root.children.push(triggerObject);
  35405. }
  35406. return root;
  35407. };
  35408. ActionManager.Parse = function (parsedActions, object, scene) {
  35409. var actionManager = new BABYLON.ActionManager(scene);
  35410. if (object === null)
  35411. scene.actionManager = actionManager;
  35412. else
  35413. object.actionManager = actionManager;
  35414. // instanciate a new object
  35415. var instanciate = function (name, params) {
  35416. var newInstance = Object.create(BABYLON[name].prototype);
  35417. newInstance.constructor.apply(newInstance, params);
  35418. return newInstance;
  35419. };
  35420. var parseParameter = function (name, value, target, propertyPath) {
  35421. if (propertyPath === null) {
  35422. // String, boolean or float
  35423. var floatValue = parseFloat(value);
  35424. if (value === "true" || value === "false")
  35425. return value === "true";
  35426. else
  35427. return isNaN(floatValue) ? value : floatValue;
  35428. }
  35429. var effectiveTarget = propertyPath.split(".");
  35430. var values = value.split(",");
  35431. // Get effective Target
  35432. for (var i = 0; i < effectiveTarget.length; i++) {
  35433. target = target[effectiveTarget[i]];
  35434. }
  35435. // Return appropriate value with its type
  35436. if (typeof (target) === "boolean")
  35437. return values[0] === "true";
  35438. if (typeof (target) === "string")
  35439. return values[0];
  35440. // Parameters with multiple values such as Vector3 etc.
  35441. var split = new Array();
  35442. for (var i = 0; i < values.length; i++)
  35443. split.push(parseFloat(values[i]));
  35444. if (target instanceof BABYLON.Vector3)
  35445. return BABYLON.Vector3.FromArray(split);
  35446. if (target instanceof BABYLON.Vector4)
  35447. return BABYLON.Vector4.FromArray(split);
  35448. if (target instanceof BABYLON.Color3)
  35449. return BABYLON.Color3.FromArray(split);
  35450. if (target instanceof BABYLON.Color4)
  35451. return BABYLON.Color4.FromArray(split);
  35452. return parseFloat(values[0]);
  35453. };
  35454. // traverse graph per trigger
  35455. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35456. if (combineArray === void 0) { combineArray = null; }
  35457. if (parsedAction.detached)
  35458. return;
  35459. var parameters = new Array();
  35460. var target = null;
  35461. var propertyPath = null;
  35462. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35463. // Parameters
  35464. if (parsedAction.type === 2)
  35465. parameters.push(actionManager);
  35466. else
  35467. parameters.push(trigger);
  35468. if (combine) {
  35469. var actions = new Array();
  35470. for (var j = 0; j < parsedAction.combine.length; j++) {
  35471. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35472. }
  35473. parameters.push(actions);
  35474. }
  35475. else {
  35476. for (var i = 0; i < parsedAction.properties.length; i++) {
  35477. var value = parsedAction.properties[i].value;
  35478. var name = parsedAction.properties[i].name;
  35479. var targetType = parsedAction.properties[i].targetType;
  35480. if (name === "target")
  35481. if (targetType !== null && targetType === "SceneProperties")
  35482. value = target = scene;
  35483. else
  35484. value = target = scene.getNodeByName(value);
  35485. else if (name === "parent")
  35486. value = scene.getNodeByName(value);
  35487. else if (name === "sound")
  35488. value = scene.getSoundByName(value);
  35489. else if (name !== "propertyPath") {
  35490. if (parsedAction.type === 2 && name === "operator")
  35491. value = BABYLON.ValueCondition[value];
  35492. else
  35493. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35494. }
  35495. else {
  35496. propertyPath = value;
  35497. }
  35498. parameters.push(value);
  35499. }
  35500. }
  35501. if (combineArray === null) {
  35502. parameters.push(condition);
  35503. }
  35504. else {
  35505. parameters.push(null);
  35506. }
  35507. // If interpolate value action
  35508. if (parsedAction.name === "InterpolateValueAction") {
  35509. var param = parameters[parameters.length - 2];
  35510. parameters[parameters.length - 1] = param;
  35511. parameters[parameters.length - 2] = condition;
  35512. }
  35513. // Action or condition(s) and not CombineAction
  35514. var newAction = instanciate(parsedAction.name, parameters);
  35515. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35516. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35517. if (action)
  35518. action.then(nothing);
  35519. else
  35520. actionManager.registerAction(nothing);
  35521. action = nothing;
  35522. }
  35523. if (combineArray === null) {
  35524. if (newAction instanceof BABYLON.Condition) {
  35525. condition = newAction;
  35526. newAction = action;
  35527. }
  35528. else {
  35529. condition = null;
  35530. if (action)
  35531. action.then(newAction);
  35532. else
  35533. actionManager.registerAction(newAction);
  35534. }
  35535. }
  35536. else {
  35537. combineArray.push(newAction);
  35538. }
  35539. for (var i = 0; i < parsedAction.children.length; i++)
  35540. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35541. };
  35542. // triggers
  35543. for (var i = 0; i < parsedActions.children.length; i++) {
  35544. var triggerParams;
  35545. var trigger = parsedActions.children[i];
  35546. if (trigger.properties.length > 0) {
  35547. var param = trigger.properties[0].value;
  35548. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35549. if (value._meshId) {
  35550. value.mesh = scene.getMeshByID(value._meshId);
  35551. }
  35552. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35553. }
  35554. else
  35555. triggerParams = BABYLON.ActionManager[trigger.name];
  35556. for (var j = 0; j < trigger.children.length; j++) {
  35557. if (!trigger.detached)
  35558. traverse(trigger.children[j], triggerParams, null, null);
  35559. }
  35560. }
  35561. };
  35562. ActionManager.GetTriggerName = function (trigger) {
  35563. switch (trigger) {
  35564. case 0: return "NothingTrigger";
  35565. case 1: return "OnPickTrigger";
  35566. case 2: return "OnLeftPickTrigger";
  35567. case 3: return "OnRightPickTrigger";
  35568. case 4: return "OnCenterPickTrigger";
  35569. case 5: return "OnPickDownTrigger";
  35570. case 6: return "OnPickUpTrigger";
  35571. case 7: return "OnLongPressTrigger";
  35572. case 8: return "OnPointerOverTrigger";
  35573. case 9: return "OnPointerOutTrigger";
  35574. case 10: return "OnEveryFrameTrigger";
  35575. case 11: return "OnIntersectionEnterTrigger";
  35576. case 12: return "OnIntersectionExitTrigger";
  35577. case 13: return "OnKeyDownTrigger";
  35578. case 14: return "OnKeyUpTrigger";
  35579. case 15: return "OnPickOutTrigger";
  35580. default: return "";
  35581. }
  35582. };
  35583. // Statics
  35584. ActionManager._NothingTrigger = 0;
  35585. ActionManager._OnPickTrigger = 1;
  35586. ActionManager._OnLeftPickTrigger = 2;
  35587. ActionManager._OnRightPickTrigger = 3;
  35588. ActionManager._OnCenterPickTrigger = 4;
  35589. ActionManager._OnPickDownTrigger = 5;
  35590. ActionManager._OnPickUpTrigger = 6;
  35591. ActionManager._OnLongPressTrigger = 7;
  35592. ActionManager._OnPointerOverTrigger = 8;
  35593. ActionManager._OnPointerOutTrigger = 9;
  35594. ActionManager._OnEveryFrameTrigger = 10;
  35595. ActionManager._OnIntersectionEnterTrigger = 11;
  35596. ActionManager._OnIntersectionExitTrigger = 12;
  35597. ActionManager._OnKeyDownTrigger = 13;
  35598. ActionManager._OnKeyUpTrigger = 14;
  35599. ActionManager._OnPickOutTrigger = 15;
  35600. ActionManager.DragMovementThreshold = 10; // in pixels
  35601. ActionManager.LongPressDelay = 500; // in milliseconds
  35602. return ActionManager;
  35603. }());
  35604. BABYLON.ActionManager = ActionManager;
  35605. })(BABYLON || (BABYLON = {}));
  35606. //# sourceMappingURL=babylon.actionManager.js.map
  35607. var BABYLON;
  35608. (function (BABYLON) {
  35609. var InterpolateValueAction = (function (_super) {
  35610. __extends(InterpolateValueAction, _super);
  35611. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35612. if (duration === void 0) { duration = 1000; }
  35613. _super.call(this, triggerOptions, condition);
  35614. this.propertyPath = propertyPath;
  35615. this.value = value;
  35616. this.duration = duration;
  35617. this.stopOtherAnimations = stopOtherAnimations;
  35618. this.onInterpolationDone = onInterpolationDone;
  35619. this._target = this._effectiveTarget = target;
  35620. }
  35621. InterpolateValueAction.prototype._prepare = function () {
  35622. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35623. this._property = this._getProperty(this.propertyPath);
  35624. };
  35625. InterpolateValueAction.prototype.execute = function () {
  35626. var scene = this._actionManager.getScene();
  35627. var keys = [
  35628. {
  35629. frame: 0,
  35630. value: this._effectiveTarget[this._property]
  35631. }, {
  35632. frame: 100,
  35633. value: this.value
  35634. }
  35635. ];
  35636. var dataType;
  35637. if (typeof this.value === "number") {
  35638. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35639. }
  35640. else if (this.value instanceof BABYLON.Color3) {
  35641. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35642. }
  35643. else if (this.value instanceof BABYLON.Vector3) {
  35644. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35645. }
  35646. else if (this.value instanceof BABYLON.Matrix) {
  35647. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35648. }
  35649. else if (this.value instanceof BABYLON.Quaternion) {
  35650. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35651. }
  35652. else {
  35653. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35654. return;
  35655. }
  35656. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35657. animation.setKeys(keys);
  35658. if (this.stopOtherAnimations) {
  35659. scene.stopAnimation(this._effectiveTarget);
  35660. }
  35661. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35662. };
  35663. InterpolateValueAction.prototype.serialize = function (parent) {
  35664. return _super.prototype._serialize.call(this, {
  35665. name: "InterpolateValueAction",
  35666. properties: [
  35667. BABYLON.Action._GetTargetProperty(this._target),
  35668. { name: "propertyPath", value: this.propertyPath },
  35669. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35670. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35671. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35672. ]
  35673. }, parent);
  35674. };
  35675. return InterpolateValueAction;
  35676. }(BABYLON.Action));
  35677. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35678. })(BABYLON || (BABYLON = {}));
  35679. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  35680. var BABYLON;
  35681. (function (BABYLON) {
  35682. var SwitchBooleanAction = (function (_super) {
  35683. __extends(SwitchBooleanAction, _super);
  35684. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35685. _super.call(this, triggerOptions, condition);
  35686. this.propertyPath = propertyPath;
  35687. this._target = this._effectiveTarget = target;
  35688. }
  35689. SwitchBooleanAction.prototype._prepare = function () {
  35690. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35691. this._property = this._getProperty(this.propertyPath);
  35692. };
  35693. SwitchBooleanAction.prototype.execute = function () {
  35694. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35695. };
  35696. SwitchBooleanAction.prototype.serialize = function (parent) {
  35697. return _super.prototype._serialize.call(this, {
  35698. name: "SwitchBooleanAction",
  35699. properties: [
  35700. BABYLON.Action._GetTargetProperty(this._target),
  35701. { name: "propertyPath", value: this.propertyPath }
  35702. ]
  35703. }, parent);
  35704. };
  35705. return SwitchBooleanAction;
  35706. }(BABYLON.Action));
  35707. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35708. var SetStateAction = (function (_super) {
  35709. __extends(SetStateAction, _super);
  35710. function SetStateAction(triggerOptions, target, value, condition) {
  35711. _super.call(this, triggerOptions, condition);
  35712. this.value = value;
  35713. this._target = target;
  35714. }
  35715. SetStateAction.prototype.execute = function () {
  35716. this._target.state = this.value;
  35717. };
  35718. SetStateAction.prototype.serialize = function (parent) {
  35719. return _super.prototype._serialize.call(this, {
  35720. name: "SetStateAction",
  35721. properties: [
  35722. BABYLON.Action._GetTargetProperty(this._target),
  35723. { name: "value", value: this.value }
  35724. ]
  35725. }, parent);
  35726. };
  35727. return SetStateAction;
  35728. }(BABYLON.Action));
  35729. BABYLON.SetStateAction = SetStateAction;
  35730. var SetValueAction = (function (_super) {
  35731. __extends(SetValueAction, _super);
  35732. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35733. _super.call(this, triggerOptions, condition);
  35734. this.propertyPath = propertyPath;
  35735. this.value = value;
  35736. this._target = this._effectiveTarget = target;
  35737. }
  35738. SetValueAction.prototype._prepare = function () {
  35739. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35740. this._property = this._getProperty(this.propertyPath);
  35741. };
  35742. SetValueAction.prototype.execute = function () {
  35743. this._effectiveTarget[this._property] = this.value;
  35744. if (this._target.markAsDirty) {
  35745. this._target.markAsDirty(this._property);
  35746. }
  35747. };
  35748. SetValueAction.prototype.serialize = function (parent) {
  35749. return _super.prototype._serialize.call(this, {
  35750. name: "SetValueAction",
  35751. properties: [
  35752. BABYLON.Action._GetTargetProperty(this._target),
  35753. { name: "propertyPath", value: this.propertyPath },
  35754. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35755. ]
  35756. }, parent);
  35757. };
  35758. return SetValueAction;
  35759. }(BABYLON.Action));
  35760. BABYLON.SetValueAction = SetValueAction;
  35761. var IncrementValueAction = (function (_super) {
  35762. __extends(IncrementValueAction, _super);
  35763. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  35764. _super.call(this, triggerOptions, condition);
  35765. this.propertyPath = propertyPath;
  35766. this.value = value;
  35767. this._target = this._effectiveTarget = target;
  35768. }
  35769. IncrementValueAction.prototype._prepare = function () {
  35770. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35771. this._property = this._getProperty(this.propertyPath);
  35772. if (typeof this._effectiveTarget[this._property] !== "number") {
  35773. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  35774. }
  35775. };
  35776. IncrementValueAction.prototype.execute = function () {
  35777. this._effectiveTarget[this._property] += this.value;
  35778. if (this._target.markAsDirty) {
  35779. this._target.markAsDirty(this._property);
  35780. }
  35781. };
  35782. IncrementValueAction.prototype.serialize = function (parent) {
  35783. return _super.prototype._serialize.call(this, {
  35784. name: "IncrementValueAction",
  35785. properties: [
  35786. BABYLON.Action._GetTargetProperty(this._target),
  35787. { name: "propertyPath", value: this.propertyPath },
  35788. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35789. ]
  35790. }, parent);
  35791. };
  35792. return IncrementValueAction;
  35793. }(BABYLON.Action));
  35794. BABYLON.IncrementValueAction = IncrementValueAction;
  35795. var PlayAnimationAction = (function (_super) {
  35796. __extends(PlayAnimationAction, _super);
  35797. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  35798. _super.call(this, triggerOptions, condition);
  35799. this.from = from;
  35800. this.to = to;
  35801. this.loop = loop;
  35802. this._target = target;
  35803. }
  35804. PlayAnimationAction.prototype._prepare = function () {
  35805. };
  35806. PlayAnimationAction.prototype.execute = function () {
  35807. var scene = this._actionManager.getScene();
  35808. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  35809. };
  35810. PlayAnimationAction.prototype.serialize = function (parent) {
  35811. return _super.prototype._serialize.call(this, {
  35812. name: "PlayAnimationAction",
  35813. properties: [
  35814. BABYLON.Action._GetTargetProperty(this._target),
  35815. { name: "from", value: String(this.from) },
  35816. { name: "to", value: String(this.to) },
  35817. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  35818. ]
  35819. }, parent);
  35820. };
  35821. return PlayAnimationAction;
  35822. }(BABYLON.Action));
  35823. BABYLON.PlayAnimationAction = PlayAnimationAction;
  35824. var StopAnimationAction = (function (_super) {
  35825. __extends(StopAnimationAction, _super);
  35826. function StopAnimationAction(triggerOptions, target, condition) {
  35827. _super.call(this, triggerOptions, condition);
  35828. this._target = target;
  35829. }
  35830. StopAnimationAction.prototype._prepare = function () {
  35831. };
  35832. StopAnimationAction.prototype.execute = function () {
  35833. var scene = this._actionManager.getScene();
  35834. scene.stopAnimation(this._target);
  35835. };
  35836. StopAnimationAction.prototype.serialize = function (parent) {
  35837. return _super.prototype._serialize.call(this, {
  35838. name: "StopAnimationAction",
  35839. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  35840. }, parent);
  35841. };
  35842. return StopAnimationAction;
  35843. }(BABYLON.Action));
  35844. BABYLON.StopAnimationAction = StopAnimationAction;
  35845. var DoNothingAction = (function (_super) {
  35846. __extends(DoNothingAction, _super);
  35847. function DoNothingAction(triggerOptions, condition) {
  35848. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  35849. _super.call(this, triggerOptions, condition);
  35850. }
  35851. DoNothingAction.prototype.execute = function () {
  35852. };
  35853. DoNothingAction.prototype.serialize = function (parent) {
  35854. return _super.prototype._serialize.call(this, {
  35855. name: "DoNothingAction",
  35856. properties: []
  35857. }, parent);
  35858. };
  35859. return DoNothingAction;
  35860. }(BABYLON.Action));
  35861. BABYLON.DoNothingAction = DoNothingAction;
  35862. var CombineAction = (function (_super) {
  35863. __extends(CombineAction, _super);
  35864. function CombineAction(triggerOptions, children, condition) {
  35865. _super.call(this, triggerOptions, condition);
  35866. this.children = children;
  35867. }
  35868. CombineAction.prototype._prepare = function () {
  35869. for (var index = 0; index < this.children.length; index++) {
  35870. this.children[index]._actionManager = this._actionManager;
  35871. this.children[index]._prepare();
  35872. }
  35873. };
  35874. CombineAction.prototype.execute = function (evt) {
  35875. for (var index = 0; index < this.children.length; index++) {
  35876. this.children[index].execute(evt);
  35877. }
  35878. };
  35879. CombineAction.prototype.serialize = function (parent) {
  35880. var serializationObject = _super.prototype._serialize.call(this, {
  35881. name: "CombineAction",
  35882. properties: [],
  35883. combine: []
  35884. }, parent);
  35885. for (var i = 0; i < this.children.length; i++) {
  35886. serializationObject.combine.push(this.children[i].serialize(null));
  35887. }
  35888. return serializationObject;
  35889. };
  35890. return CombineAction;
  35891. }(BABYLON.Action));
  35892. BABYLON.CombineAction = CombineAction;
  35893. var ExecuteCodeAction = (function (_super) {
  35894. __extends(ExecuteCodeAction, _super);
  35895. function ExecuteCodeAction(triggerOptions, func, condition) {
  35896. _super.call(this, triggerOptions, condition);
  35897. this.func = func;
  35898. }
  35899. ExecuteCodeAction.prototype.execute = function (evt) {
  35900. this.func(evt);
  35901. };
  35902. return ExecuteCodeAction;
  35903. }(BABYLON.Action));
  35904. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  35905. var SetParentAction = (function (_super) {
  35906. __extends(SetParentAction, _super);
  35907. function SetParentAction(triggerOptions, target, parent, condition) {
  35908. _super.call(this, triggerOptions, condition);
  35909. this._target = target;
  35910. this._parent = parent;
  35911. }
  35912. SetParentAction.prototype._prepare = function () {
  35913. };
  35914. SetParentAction.prototype.execute = function () {
  35915. if (this._target.parent === this._parent) {
  35916. return;
  35917. }
  35918. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  35919. invertParentWorldMatrix.invert();
  35920. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  35921. this._target.parent = this._parent;
  35922. };
  35923. SetParentAction.prototype.serialize = function (parent) {
  35924. return _super.prototype._serialize.call(this, {
  35925. name: "SetParentAction",
  35926. properties: [
  35927. BABYLON.Action._GetTargetProperty(this._target),
  35928. BABYLON.Action._GetTargetProperty(this._parent),
  35929. ]
  35930. }, parent);
  35931. };
  35932. return SetParentAction;
  35933. }(BABYLON.Action));
  35934. BABYLON.SetParentAction = SetParentAction;
  35935. var PlaySoundAction = (function (_super) {
  35936. __extends(PlaySoundAction, _super);
  35937. function PlaySoundAction(triggerOptions, sound, condition) {
  35938. _super.call(this, triggerOptions, condition);
  35939. this._sound = sound;
  35940. }
  35941. PlaySoundAction.prototype._prepare = function () {
  35942. };
  35943. PlaySoundAction.prototype.execute = function () {
  35944. if (this._sound !== undefined)
  35945. this._sound.play();
  35946. };
  35947. PlaySoundAction.prototype.serialize = function (parent) {
  35948. return _super.prototype._serialize.call(this, {
  35949. name: "PlaySoundAction",
  35950. properties: [{ name: "sound", value: this._sound.name }]
  35951. }, parent);
  35952. };
  35953. return PlaySoundAction;
  35954. }(BABYLON.Action));
  35955. BABYLON.PlaySoundAction = PlaySoundAction;
  35956. var StopSoundAction = (function (_super) {
  35957. __extends(StopSoundAction, _super);
  35958. function StopSoundAction(triggerOptions, sound, condition) {
  35959. _super.call(this, triggerOptions, condition);
  35960. this._sound = sound;
  35961. }
  35962. StopSoundAction.prototype._prepare = function () {
  35963. };
  35964. StopSoundAction.prototype.execute = function () {
  35965. if (this._sound !== undefined)
  35966. this._sound.stop();
  35967. };
  35968. StopSoundAction.prototype.serialize = function (parent) {
  35969. return _super.prototype._serialize.call(this, {
  35970. name: "StopSoundAction",
  35971. properties: [{ name: "sound", value: this._sound.name }]
  35972. }, parent);
  35973. };
  35974. return StopSoundAction;
  35975. }(BABYLON.Action));
  35976. BABYLON.StopSoundAction = StopSoundAction;
  35977. })(BABYLON || (BABYLON = {}));
  35978. //# sourceMappingURL=babylon.directActions.js.map
  35979. var BABYLON;
  35980. (function (BABYLON) {
  35981. var Geometry = (function () {
  35982. function Geometry(id, scene, vertexData, updatable, mesh) {
  35983. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35984. this._totalVertices = 0;
  35985. this._isDisposed = false;
  35986. this.id = id;
  35987. this._engine = scene.getEngine();
  35988. this._meshes = [];
  35989. this._scene = scene;
  35990. //Init vertex buffer cache
  35991. this._vertexBuffers = {};
  35992. this._indices = [];
  35993. // vertexData
  35994. if (vertexData) {
  35995. this.setAllVerticesData(vertexData, updatable);
  35996. }
  35997. else {
  35998. this._totalVertices = 0;
  35999. this._indices = [];
  36000. }
  36001. // applyToMesh
  36002. if (mesh) {
  36003. if (mesh instanceof BABYLON.LinesMesh) {
  36004. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  36005. this.updateExtend();
  36006. }
  36007. this.applyToMesh(mesh);
  36008. mesh.computeWorldMatrix(true);
  36009. }
  36010. }
  36011. Object.defineProperty(Geometry.prototype, "boundingBias", {
  36012. /**
  36013. * 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
  36014. * @returns The Bias Vector
  36015. */
  36016. get: function () {
  36017. return this._boundingBias;
  36018. },
  36019. set: function (value) {
  36020. if (this._boundingBias && this._boundingBias.equals(value)) {
  36021. return;
  36022. }
  36023. this._boundingBias = value.clone();
  36024. this.updateBoundingInfo(true, null);
  36025. },
  36026. enumerable: true,
  36027. configurable: true
  36028. });
  36029. Object.defineProperty(Geometry.prototype, "extend", {
  36030. get: function () {
  36031. return this._extend;
  36032. },
  36033. enumerable: true,
  36034. configurable: true
  36035. });
  36036. Geometry.prototype.getScene = function () {
  36037. return this._scene;
  36038. };
  36039. Geometry.prototype.getEngine = function () {
  36040. return this._engine;
  36041. };
  36042. Geometry.prototype.isReady = function () {
  36043. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  36044. };
  36045. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  36046. get: function () {
  36047. for (var index = 0; index < this._meshes.length; index++) {
  36048. if (!this._meshes[index].doNotSerialize) {
  36049. return false;
  36050. }
  36051. }
  36052. return true;
  36053. },
  36054. enumerable: true,
  36055. configurable: true
  36056. });
  36057. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36058. vertexData.applyToGeometry(this, updatable);
  36059. this.notifyUpdate();
  36060. };
  36061. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  36062. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  36063. this.setVerticesBuffer(buffer);
  36064. };
  36065. Geometry.prototype.setVerticesBuffer = function (buffer) {
  36066. var kind = buffer.getKind();
  36067. if (this._vertexBuffers[kind]) {
  36068. this._vertexBuffers[kind].dispose();
  36069. }
  36070. this._vertexBuffers[kind] = buffer;
  36071. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36072. var data = buffer.getData();
  36073. var stride = buffer.getStrideSize();
  36074. this._totalVertices = data.length / stride;
  36075. this.updateExtend(data, stride);
  36076. var meshes = this._meshes;
  36077. var numOfMeshes = meshes.length;
  36078. for (var index = 0; index < numOfMeshes; index++) {
  36079. var mesh = meshes[index];
  36080. mesh._resetPointsArrayCache();
  36081. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36082. mesh._createGlobalSubMesh();
  36083. mesh.computeWorldMatrix(true);
  36084. }
  36085. }
  36086. this.notifyUpdate(kind);
  36087. };
  36088. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  36089. var vertexBuffer = this.getVertexBuffer(kind);
  36090. if (!vertexBuffer) {
  36091. return;
  36092. }
  36093. vertexBuffer.updateDirectly(data, offset);
  36094. this.notifyUpdate(kind);
  36095. };
  36096. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  36097. var vertexBuffer = this.getVertexBuffer(kind);
  36098. if (!vertexBuffer) {
  36099. return;
  36100. }
  36101. vertexBuffer.update(data);
  36102. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36103. var stride = vertexBuffer.getStrideSize();
  36104. this._totalVertices = data.length / stride;
  36105. this.updateBoundingInfo(updateExtends, data);
  36106. }
  36107. this.notifyUpdate(kind);
  36108. };
  36109. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  36110. if (updateExtends) {
  36111. this.updateExtend(data);
  36112. }
  36113. var meshes = this._meshes;
  36114. var numOfMeshes = meshes.length;
  36115. for (var index = 0; index < numOfMeshes; index++) {
  36116. var mesh = meshes[index];
  36117. mesh._resetPointsArrayCache();
  36118. if (updateExtends) {
  36119. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36120. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36121. var subMesh = mesh.subMeshes[subIndex];
  36122. subMesh.refreshBoundingInfo();
  36123. }
  36124. }
  36125. }
  36126. };
  36127. Geometry.prototype.getTotalVertices = function () {
  36128. if (!this.isReady()) {
  36129. return 0;
  36130. }
  36131. return this._totalVertices;
  36132. };
  36133. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  36134. var vertexBuffer = this.getVertexBuffer(kind);
  36135. if (!vertexBuffer) {
  36136. return null;
  36137. }
  36138. var orig = vertexBuffer.getData();
  36139. if (!copyWhenShared || this._meshes.length === 1) {
  36140. return orig;
  36141. }
  36142. else {
  36143. var len = orig.length;
  36144. var copy = [];
  36145. for (var i = 0; i < len; i++) {
  36146. copy.push(orig[i]);
  36147. }
  36148. return copy;
  36149. }
  36150. };
  36151. Geometry.prototype.getVertexBuffer = function (kind) {
  36152. if (!this.isReady()) {
  36153. return null;
  36154. }
  36155. return this._vertexBuffers[kind];
  36156. };
  36157. Geometry.prototype.getVertexBuffers = function () {
  36158. if (!this.isReady()) {
  36159. return null;
  36160. }
  36161. return this._vertexBuffers;
  36162. };
  36163. Geometry.prototype.isVerticesDataPresent = function (kind) {
  36164. if (!this._vertexBuffers) {
  36165. if (this._delayInfo) {
  36166. return this._delayInfo.indexOf(kind) !== -1;
  36167. }
  36168. return false;
  36169. }
  36170. return this._vertexBuffers[kind] !== undefined;
  36171. };
  36172. Geometry.prototype.getVerticesDataKinds = function () {
  36173. var result = [];
  36174. var kind;
  36175. if (!this._vertexBuffers && this._delayInfo) {
  36176. for (kind in this._delayInfo) {
  36177. result.push(kind);
  36178. }
  36179. }
  36180. else {
  36181. for (kind in this._vertexBuffers) {
  36182. result.push(kind);
  36183. }
  36184. }
  36185. return result;
  36186. };
  36187. Geometry.prototype.setIndices = function (indices, totalVertices) {
  36188. if (this._indexBuffer) {
  36189. this._engine._releaseBuffer(this._indexBuffer);
  36190. }
  36191. this._indices = indices;
  36192. if (this._meshes.length !== 0 && this._indices) {
  36193. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36194. }
  36195. if (totalVertices !== undefined) {
  36196. this._totalVertices = totalVertices;
  36197. }
  36198. var meshes = this._meshes;
  36199. var numOfMeshes = meshes.length;
  36200. for (var index = 0; index < numOfMeshes; index++) {
  36201. meshes[index]._createGlobalSubMesh();
  36202. }
  36203. this.notifyUpdate();
  36204. };
  36205. Geometry.prototype.getTotalIndices = function () {
  36206. if (!this.isReady()) {
  36207. return 0;
  36208. }
  36209. return this._indices.length;
  36210. };
  36211. Geometry.prototype.getIndices = function (copyWhenShared) {
  36212. if (!this.isReady()) {
  36213. return null;
  36214. }
  36215. var orig = this._indices;
  36216. if (!copyWhenShared || this._meshes.length === 1) {
  36217. return orig;
  36218. }
  36219. else {
  36220. var len = orig.length;
  36221. var copy = [];
  36222. for (var i = 0; i < len; i++) {
  36223. copy.push(orig[i]);
  36224. }
  36225. return copy;
  36226. }
  36227. };
  36228. Geometry.prototype.getIndexBuffer = function () {
  36229. if (!this.isReady()) {
  36230. return null;
  36231. }
  36232. return this._indexBuffer;
  36233. };
  36234. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  36235. var meshes = this._meshes;
  36236. var index = meshes.indexOf(mesh);
  36237. if (index === -1) {
  36238. return;
  36239. }
  36240. for (var kind in this._vertexBuffers) {
  36241. this._vertexBuffers[kind].dispose();
  36242. }
  36243. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  36244. this._indexBuffer = null;
  36245. }
  36246. meshes.splice(index, 1);
  36247. mesh._geometry = null;
  36248. if (meshes.length === 0 && shouldDispose) {
  36249. this.dispose();
  36250. }
  36251. };
  36252. Geometry.prototype.applyToMesh = function (mesh) {
  36253. if (mesh._geometry === this) {
  36254. return;
  36255. }
  36256. var previousGeometry = mesh._geometry;
  36257. if (previousGeometry) {
  36258. previousGeometry.releaseForMesh(mesh);
  36259. }
  36260. var meshes = this._meshes;
  36261. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  36262. mesh._geometry = this;
  36263. this._scene.pushGeometry(this);
  36264. meshes.push(mesh);
  36265. if (this.isReady()) {
  36266. this._applyToMesh(mesh);
  36267. }
  36268. else {
  36269. mesh._boundingInfo = this._boundingInfo;
  36270. }
  36271. };
  36272. Geometry.prototype.updateExtend = function (data, stride) {
  36273. if (data === void 0) { data = null; }
  36274. if (!data) {
  36275. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  36276. }
  36277. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  36278. };
  36279. Geometry.prototype._applyToMesh = function (mesh) {
  36280. var numOfMeshes = this._meshes.length;
  36281. // vertexBuffers
  36282. for (var kind in this._vertexBuffers) {
  36283. if (numOfMeshes === 1) {
  36284. this._vertexBuffers[kind].create();
  36285. }
  36286. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  36287. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36288. mesh._resetPointsArrayCache();
  36289. if (!this._extend) {
  36290. this.updateExtend(this._vertexBuffers[kind].getData());
  36291. }
  36292. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36293. mesh._createGlobalSubMesh();
  36294. //bounding info was just created again, world matrix should be applied again.
  36295. mesh._updateBoundingInfo();
  36296. }
  36297. }
  36298. // indexBuffer
  36299. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  36300. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36301. }
  36302. if (this._indexBuffer) {
  36303. this._indexBuffer.references = numOfMeshes;
  36304. }
  36305. };
  36306. Geometry.prototype.notifyUpdate = function (kind) {
  36307. if (this.onGeometryUpdated) {
  36308. this.onGeometryUpdated(this, kind);
  36309. }
  36310. };
  36311. Geometry.prototype.load = function (scene, onLoaded) {
  36312. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36313. return;
  36314. }
  36315. if (this.isReady()) {
  36316. if (onLoaded) {
  36317. onLoaded();
  36318. }
  36319. return;
  36320. }
  36321. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36322. this._queueLoad(scene, onLoaded);
  36323. };
  36324. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36325. var _this = this;
  36326. scene._addPendingData(this);
  36327. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  36328. _this._delayLoadingFunction(JSON.parse(data), _this);
  36329. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36330. _this._delayInfo = [];
  36331. scene._removePendingData(_this);
  36332. var meshes = _this._meshes;
  36333. var numOfMeshes = meshes.length;
  36334. for (var index = 0; index < numOfMeshes; index++) {
  36335. _this._applyToMesh(meshes[index]);
  36336. }
  36337. if (onLoaded) {
  36338. onLoaded();
  36339. }
  36340. }, function () { }, scene.database);
  36341. };
  36342. /**
  36343. * Invert the geometry to move from a right handed system to a left handed one.
  36344. */
  36345. Geometry.prototype.toLeftHanded = function () {
  36346. // Flip faces
  36347. var tIndices = this.getIndices(false);
  36348. if (tIndices != null && tIndices.length > 0) {
  36349. for (var i = 0; i < tIndices.length; i += 3) {
  36350. var tTemp = tIndices[i + 0];
  36351. tIndices[i + 0] = tIndices[i + 2];
  36352. tIndices[i + 2] = tTemp;
  36353. }
  36354. this.setIndices(tIndices);
  36355. }
  36356. // Negate position.z
  36357. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36358. if (tPositions != null && tPositions.length > 0) {
  36359. for (var i = 0; i < tPositions.length; i += 3) {
  36360. tPositions[i + 2] = -tPositions[i + 2];
  36361. }
  36362. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36363. }
  36364. // Negate normal.z
  36365. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36366. if (tNormals != null && tNormals.length > 0) {
  36367. for (var i = 0; i < tNormals.length; i += 3) {
  36368. tNormals[i + 2] = -tNormals[i + 2];
  36369. }
  36370. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36371. }
  36372. };
  36373. Geometry.prototype.isDisposed = function () {
  36374. return this._isDisposed;
  36375. };
  36376. Geometry.prototype.dispose = function () {
  36377. var meshes = this._meshes;
  36378. var numOfMeshes = meshes.length;
  36379. var index;
  36380. for (index = 0; index < numOfMeshes; index++) {
  36381. this.releaseForMesh(meshes[index]);
  36382. }
  36383. this._meshes = [];
  36384. for (var kind in this._vertexBuffers) {
  36385. this._vertexBuffers[kind].dispose();
  36386. }
  36387. this._vertexBuffers = {};
  36388. this._totalVertices = 0;
  36389. if (this._indexBuffer) {
  36390. this._engine._releaseBuffer(this._indexBuffer);
  36391. }
  36392. this._indexBuffer = null;
  36393. this._indices = [];
  36394. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36395. this.delayLoadingFile = null;
  36396. this._delayLoadingFunction = null;
  36397. this._delayInfo = [];
  36398. this._boundingInfo = null;
  36399. this._scene.removeGeometry(this);
  36400. this._isDisposed = true;
  36401. };
  36402. Geometry.prototype.copy = function (id) {
  36403. var vertexData = new BABYLON.VertexData();
  36404. vertexData.indices = [];
  36405. var indices = this.getIndices();
  36406. for (var index = 0; index < indices.length; index++) {
  36407. vertexData.indices.push(indices[index]);
  36408. }
  36409. var updatable = false;
  36410. var stopChecking = false;
  36411. var kind;
  36412. for (kind in this._vertexBuffers) {
  36413. // using slice() to make a copy of the array and not just reference it
  36414. var data = this.getVerticesData(kind);
  36415. if (data instanceof Float32Array) {
  36416. vertexData.set(new Float32Array(data), kind);
  36417. }
  36418. else {
  36419. vertexData.set(data.slice(0), kind);
  36420. }
  36421. if (!stopChecking) {
  36422. updatable = this.getVertexBuffer(kind).isUpdatable();
  36423. stopChecking = !updatable;
  36424. }
  36425. }
  36426. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  36427. geometry.delayLoadState = this.delayLoadState;
  36428. geometry.delayLoadingFile = this.delayLoadingFile;
  36429. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36430. for (kind in this._delayInfo) {
  36431. geometry._delayInfo = geometry._delayInfo || [];
  36432. geometry._delayInfo.push(kind);
  36433. }
  36434. // Bounding info
  36435. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36436. return geometry;
  36437. };
  36438. Geometry.prototype.serialize = function () {
  36439. var serializationObject = {};
  36440. serializationObject.id = this.id;
  36441. if (BABYLON.Tags.HasTags(this)) {
  36442. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36443. }
  36444. return serializationObject;
  36445. };
  36446. Geometry.prototype.serializeVerticeData = function () {
  36447. var serializationObject = this.serialize();
  36448. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36449. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36450. }
  36451. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36452. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36453. }
  36454. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36455. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36456. }
  36457. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36458. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  36459. }
  36460. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36461. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  36462. }
  36463. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36464. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  36465. }
  36466. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36467. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  36468. }
  36469. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36470. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  36471. }
  36472. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36473. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36474. }
  36475. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36476. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36477. serializationObject.matricesIndices._isExpanded = true;
  36478. }
  36479. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36480. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  36481. }
  36482. serializationObject.indices = this.getIndices();
  36483. return serializationObject;
  36484. };
  36485. // Statics
  36486. Geometry.ExtractFromMesh = function (mesh, id) {
  36487. var geometry = mesh._geometry;
  36488. if (!geometry) {
  36489. return null;
  36490. }
  36491. return geometry.copy(id);
  36492. };
  36493. /**
  36494. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36495. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36496. * Be aware Math.random() could cause collisions, but:
  36497. * "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"
  36498. */
  36499. Geometry.RandomId = function () {
  36500. return BABYLON.Tools.RandomId();
  36501. };
  36502. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  36503. var scene = mesh.getScene();
  36504. // Geometry
  36505. var geometryId = parsedGeometry.geometryId;
  36506. if (geometryId) {
  36507. var geometry = scene.getGeometryByID(geometryId);
  36508. if (geometry) {
  36509. geometry.applyToMesh(mesh);
  36510. }
  36511. }
  36512. else if (parsedGeometry instanceof ArrayBuffer) {
  36513. var binaryInfo = mesh._binaryInfo;
  36514. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36515. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36516. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36517. }
  36518. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36519. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36520. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36521. }
  36522. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36523. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36524. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36525. }
  36526. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36527. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36528. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36529. }
  36530. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36531. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36532. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36533. }
  36534. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36535. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36536. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36537. }
  36538. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36539. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36540. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36541. }
  36542. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36543. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36544. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36545. }
  36546. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36547. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36548. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36549. }
  36550. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36551. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36552. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36553. }
  36554. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36555. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36556. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36557. }
  36558. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36559. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36560. mesh.setIndices(indicesData);
  36561. }
  36562. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36563. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36564. mesh.subMeshes = [];
  36565. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36566. var materialIndex = subMeshesData[(i * 5) + 0];
  36567. var verticesStart = subMeshesData[(i * 5) + 1];
  36568. var verticesCount = subMeshesData[(i * 5) + 2];
  36569. var indexStart = subMeshesData[(i * 5) + 3];
  36570. var indexCount = subMeshesData[(i * 5) + 4];
  36571. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36572. }
  36573. }
  36574. }
  36575. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36576. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  36577. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  36578. if (parsedGeometry.uvs) {
  36579. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  36580. }
  36581. if (parsedGeometry.uvs2) {
  36582. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  36583. }
  36584. if (parsedGeometry.uvs3) {
  36585. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  36586. }
  36587. if (parsedGeometry.uvs4) {
  36588. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  36589. }
  36590. if (parsedGeometry.uvs5) {
  36591. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  36592. }
  36593. if (parsedGeometry.uvs6) {
  36594. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  36595. }
  36596. if (parsedGeometry.colors) {
  36597. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  36598. }
  36599. if (parsedGeometry.matricesIndices) {
  36600. if (!parsedGeometry.matricesIndices._isExpanded) {
  36601. var floatIndices = [];
  36602. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36603. var matricesIndex = parsedGeometry.matricesIndices[i];
  36604. floatIndices.push(matricesIndex & 0x000000FF);
  36605. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36606. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36607. floatIndices.push(matricesIndex >> 24);
  36608. }
  36609. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  36610. }
  36611. else {
  36612. delete parsedGeometry.matricesIndices._isExpanded;
  36613. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  36614. }
  36615. }
  36616. if (parsedGeometry.matricesIndicesExtra) {
  36617. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36618. var floatIndices = [];
  36619. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36620. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36621. floatIndices.push(matricesIndex & 0x000000FF);
  36622. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36623. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36624. floatIndices.push(matricesIndex >> 24);
  36625. }
  36626. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  36627. }
  36628. else {
  36629. delete parsedGeometry.matricesIndices._isExpanded;
  36630. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  36631. }
  36632. }
  36633. if (parsedGeometry.matricesWeights) {
  36634. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  36635. }
  36636. if (parsedGeometry.matricesWeightsExtra) {
  36637. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  36638. }
  36639. mesh.setIndices(parsedGeometry.indices);
  36640. }
  36641. // SubMeshes
  36642. if (parsedGeometry.subMeshes) {
  36643. mesh.subMeshes = [];
  36644. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36645. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36646. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36647. }
  36648. }
  36649. // Flat shading
  36650. if (mesh._shouldGenerateFlatShading) {
  36651. mesh.convertToFlatShadedMesh();
  36652. delete mesh._shouldGenerateFlatShading;
  36653. }
  36654. // Update
  36655. mesh.computeWorldMatrix(true);
  36656. // Octree
  36657. if (scene['_selectionOctree']) {
  36658. scene['_selectionOctree'].addMesh(mesh);
  36659. }
  36660. };
  36661. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36662. if (scene.getGeometryByID(parsedVertexData.id)) {
  36663. return null; // null since geometry could be something else than a box...
  36664. }
  36665. var geometry = new Geometry(parsedVertexData.id, scene);
  36666. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36667. if (parsedVertexData.delayLoadingFile) {
  36668. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36669. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36670. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36671. geometry._delayInfo = [];
  36672. if (parsedVertexData.hasUVs) {
  36673. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36674. }
  36675. if (parsedVertexData.hasUVs2) {
  36676. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36677. }
  36678. if (parsedVertexData.hasUVs3) {
  36679. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36680. }
  36681. if (parsedVertexData.hasUVs4) {
  36682. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36683. }
  36684. if (parsedVertexData.hasUVs5) {
  36685. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36686. }
  36687. if (parsedVertexData.hasUVs6) {
  36688. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36689. }
  36690. if (parsedVertexData.hasColors) {
  36691. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36692. }
  36693. if (parsedVertexData.hasMatricesIndices) {
  36694. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36695. }
  36696. if (parsedVertexData.hasMatricesWeights) {
  36697. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36698. }
  36699. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36700. }
  36701. else {
  36702. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36703. }
  36704. scene.pushGeometry(geometry, true);
  36705. return geometry;
  36706. };
  36707. return Geometry;
  36708. }());
  36709. BABYLON.Geometry = Geometry;
  36710. /////// Primitives //////////////////////////////////////////////
  36711. var Geometry;
  36712. (function (Geometry) {
  36713. var Primitives;
  36714. (function (Primitives) {
  36715. /// Abstract class
  36716. var _Primitive = (function (_super) {
  36717. __extends(_Primitive, _super);
  36718. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  36719. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  36720. this._canBeRegenerated = _canBeRegenerated;
  36721. this._beingRegenerated = true;
  36722. this.regenerate();
  36723. this._beingRegenerated = false;
  36724. }
  36725. _Primitive.prototype.canBeRegenerated = function () {
  36726. return this._canBeRegenerated;
  36727. };
  36728. _Primitive.prototype.regenerate = function () {
  36729. if (!this._canBeRegenerated) {
  36730. return;
  36731. }
  36732. this._beingRegenerated = true;
  36733. this.setAllVerticesData(this._regenerateVertexData(), false);
  36734. this._beingRegenerated = false;
  36735. };
  36736. _Primitive.prototype.asNewGeometry = function (id) {
  36737. return _super.prototype.copy.call(this, id);
  36738. };
  36739. // overrides
  36740. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  36741. if (!this._beingRegenerated) {
  36742. return;
  36743. }
  36744. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36745. };
  36746. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  36747. if (!this._beingRegenerated) {
  36748. return;
  36749. }
  36750. _super.prototype.setVerticesData.call(this, kind, data, false);
  36751. };
  36752. // to override
  36753. // protected
  36754. _Primitive.prototype._regenerateVertexData = function () {
  36755. throw new Error("Abstract method");
  36756. };
  36757. _Primitive.prototype.copy = function (id) {
  36758. throw new Error("Must be overriden in sub-classes.");
  36759. };
  36760. _Primitive.prototype.serialize = function () {
  36761. var serializationObject = _super.prototype.serialize.call(this);
  36762. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36763. return serializationObject;
  36764. };
  36765. return _Primitive;
  36766. }(Geometry));
  36767. Primitives._Primitive = _Primitive;
  36768. var Ribbon = (function (_super) {
  36769. __extends(Ribbon, _super);
  36770. // Members
  36771. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  36772. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36773. _super.call(this, id, scene, canBeRegenerated, mesh);
  36774. this.pathArray = pathArray;
  36775. this.closeArray = closeArray;
  36776. this.closePath = closePath;
  36777. this.offset = offset;
  36778. this.side = side;
  36779. }
  36780. Ribbon.prototype._regenerateVertexData = function () {
  36781. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36782. };
  36783. Ribbon.prototype.copy = function (id) {
  36784. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  36785. };
  36786. return Ribbon;
  36787. }(_Primitive));
  36788. Primitives.Ribbon = Ribbon;
  36789. var Box = (function (_super) {
  36790. __extends(Box, _super);
  36791. // Members
  36792. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  36793. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36794. _super.call(this, id, scene, canBeRegenerated, mesh);
  36795. this.size = size;
  36796. this.side = side;
  36797. }
  36798. Box.prototype._regenerateVertexData = function () {
  36799. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36800. };
  36801. Box.prototype.copy = function (id) {
  36802. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36803. };
  36804. Box.prototype.serialize = function () {
  36805. var serializationObject = _super.prototype.serialize.call(this);
  36806. serializationObject.size = this.size;
  36807. return serializationObject;
  36808. };
  36809. Box.Parse = function (parsedBox, scene) {
  36810. if (scene.getGeometryByID(parsedBox.id)) {
  36811. return null; // null since geometry could be something else than a box...
  36812. }
  36813. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36814. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36815. scene.pushGeometry(box, true);
  36816. return box;
  36817. };
  36818. return Box;
  36819. }(_Primitive));
  36820. Primitives.Box = Box;
  36821. var Sphere = (function (_super) {
  36822. __extends(Sphere, _super);
  36823. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  36824. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36825. _super.call(this, id, scene, canBeRegenerated, mesh);
  36826. this.segments = segments;
  36827. this.diameter = diameter;
  36828. this.side = side;
  36829. }
  36830. Sphere.prototype._regenerateVertexData = function () {
  36831. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36832. };
  36833. Sphere.prototype.copy = function (id) {
  36834. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36835. };
  36836. Sphere.prototype.serialize = function () {
  36837. var serializationObject = _super.prototype.serialize.call(this);
  36838. serializationObject.segments = this.segments;
  36839. serializationObject.diameter = this.diameter;
  36840. return serializationObject;
  36841. };
  36842. Sphere.Parse = function (parsedSphere, scene) {
  36843. if (scene.getGeometryByID(parsedSphere.id)) {
  36844. return null; // null since geometry could be something else than a sphere...
  36845. }
  36846. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36847. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36848. scene.pushGeometry(sphere, true);
  36849. return sphere;
  36850. };
  36851. return Sphere;
  36852. }(_Primitive));
  36853. Primitives.Sphere = Sphere;
  36854. var Disc = (function (_super) {
  36855. __extends(Disc, _super);
  36856. // Members
  36857. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  36858. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36859. _super.call(this, id, scene, canBeRegenerated, mesh);
  36860. this.radius = radius;
  36861. this.tessellation = tessellation;
  36862. this.side = side;
  36863. }
  36864. Disc.prototype._regenerateVertexData = function () {
  36865. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36866. };
  36867. Disc.prototype.copy = function (id) {
  36868. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36869. };
  36870. return Disc;
  36871. }(_Primitive));
  36872. Primitives.Disc = Disc;
  36873. var Cylinder = (function (_super) {
  36874. __extends(Cylinder, _super);
  36875. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  36876. if (subdivisions === void 0) { subdivisions = 1; }
  36877. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36878. _super.call(this, id, scene, canBeRegenerated, mesh);
  36879. this.height = height;
  36880. this.diameterTop = diameterTop;
  36881. this.diameterBottom = diameterBottom;
  36882. this.tessellation = tessellation;
  36883. this.subdivisions = subdivisions;
  36884. this.side = side;
  36885. }
  36886. Cylinder.prototype._regenerateVertexData = function () {
  36887. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36888. };
  36889. Cylinder.prototype.copy = function (id) {
  36890. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36891. };
  36892. Cylinder.prototype.serialize = function () {
  36893. var serializationObject = _super.prototype.serialize.call(this);
  36894. serializationObject.height = this.height;
  36895. serializationObject.diameterTop = this.diameterTop;
  36896. serializationObject.diameterBottom = this.diameterBottom;
  36897. serializationObject.tessellation = this.tessellation;
  36898. return serializationObject;
  36899. };
  36900. Cylinder.Parse = function (parsedCylinder, scene) {
  36901. if (scene.getGeometryByID(parsedCylinder.id)) {
  36902. return null; // null since geometry could be something else than a cylinder...
  36903. }
  36904. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36905. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36906. scene.pushGeometry(cylinder, true);
  36907. return cylinder;
  36908. };
  36909. return Cylinder;
  36910. }(_Primitive));
  36911. Primitives.Cylinder = Cylinder;
  36912. var Torus = (function (_super) {
  36913. __extends(Torus, _super);
  36914. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  36915. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36916. _super.call(this, id, scene, canBeRegenerated, mesh);
  36917. this.diameter = diameter;
  36918. this.thickness = thickness;
  36919. this.tessellation = tessellation;
  36920. this.side = side;
  36921. }
  36922. Torus.prototype._regenerateVertexData = function () {
  36923. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36924. };
  36925. Torus.prototype.copy = function (id) {
  36926. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36927. };
  36928. Torus.prototype.serialize = function () {
  36929. var serializationObject = _super.prototype.serialize.call(this);
  36930. serializationObject.diameter = this.diameter;
  36931. serializationObject.thickness = this.thickness;
  36932. serializationObject.tessellation = this.tessellation;
  36933. return serializationObject;
  36934. };
  36935. Torus.Parse = function (parsedTorus, scene) {
  36936. if (scene.getGeometryByID(parsedTorus.id)) {
  36937. return null; // null since geometry could be something else than a torus...
  36938. }
  36939. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36940. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36941. scene.pushGeometry(torus, true);
  36942. return torus;
  36943. };
  36944. return Torus;
  36945. }(_Primitive));
  36946. Primitives.Torus = Torus;
  36947. var Ground = (function (_super) {
  36948. __extends(Ground, _super);
  36949. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  36950. _super.call(this, id, scene, canBeRegenerated, mesh);
  36951. this.width = width;
  36952. this.height = height;
  36953. this.subdivisions = subdivisions;
  36954. }
  36955. Ground.prototype._regenerateVertexData = function () {
  36956. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36957. };
  36958. Ground.prototype.copy = function (id) {
  36959. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36960. };
  36961. Ground.prototype.serialize = function () {
  36962. var serializationObject = _super.prototype.serialize.call(this);
  36963. serializationObject.width = this.width;
  36964. serializationObject.height = this.height;
  36965. serializationObject.subdivisions = this.subdivisions;
  36966. return serializationObject;
  36967. };
  36968. Ground.Parse = function (parsedGround, scene) {
  36969. if (scene.getGeometryByID(parsedGround.id)) {
  36970. return null; // null since geometry could be something else than a ground...
  36971. }
  36972. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36973. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36974. scene.pushGeometry(ground, true);
  36975. return ground;
  36976. };
  36977. return Ground;
  36978. }(_Primitive));
  36979. Primitives.Ground = Ground;
  36980. var TiledGround = (function (_super) {
  36981. __extends(TiledGround, _super);
  36982. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  36983. _super.call(this, id, scene, canBeRegenerated, mesh);
  36984. this.xmin = xmin;
  36985. this.zmin = zmin;
  36986. this.xmax = xmax;
  36987. this.zmax = zmax;
  36988. this.subdivisions = subdivisions;
  36989. this.precision = precision;
  36990. }
  36991. TiledGround.prototype._regenerateVertexData = function () {
  36992. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36993. };
  36994. TiledGround.prototype.copy = function (id) {
  36995. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36996. };
  36997. return TiledGround;
  36998. }(_Primitive));
  36999. Primitives.TiledGround = TiledGround;
  37000. var Plane = (function (_super) {
  37001. __extends(Plane, _super);
  37002. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  37003. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37004. _super.call(this, id, scene, canBeRegenerated, mesh);
  37005. this.size = size;
  37006. this.side = side;
  37007. }
  37008. Plane.prototype._regenerateVertexData = function () {
  37009. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37010. };
  37011. Plane.prototype.copy = function (id) {
  37012. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37013. };
  37014. Plane.prototype.serialize = function () {
  37015. var serializationObject = _super.prototype.serialize.call(this);
  37016. serializationObject.size = this.size;
  37017. return serializationObject;
  37018. };
  37019. Plane.Parse = function (parsedPlane, scene) {
  37020. if (scene.getGeometryByID(parsedPlane.id)) {
  37021. return null; // null since geometry could be something else than a ground...
  37022. }
  37023. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37024. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37025. scene.pushGeometry(plane, true);
  37026. return plane;
  37027. };
  37028. return Plane;
  37029. }(_Primitive));
  37030. Primitives.Plane = Plane;
  37031. var TorusKnot = (function (_super) {
  37032. __extends(TorusKnot, _super);
  37033. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  37034. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37035. _super.call(this, id, scene, canBeRegenerated, mesh);
  37036. this.radius = radius;
  37037. this.tube = tube;
  37038. this.radialSegments = radialSegments;
  37039. this.tubularSegments = tubularSegments;
  37040. this.p = p;
  37041. this.q = q;
  37042. this.side = side;
  37043. }
  37044. TorusKnot.prototype._regenerateVertexData = function () {
  37045. 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 });
  37046. };
  37047. TorusKnot.prototype.copy = function (id) {
  37048. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37049. };
  37050. TorusKnot.prototype.serialize = function () {
  37051. var serializationObject = _super.prototype.serialize.call(this);
  37052. serializationObject.radius = this.radius;
  37053. serializationObject.tube = this.tube;
  37054. serializationObject.radialSegments = this.radialSegments;
  37055. serializationObject.tubularSegments = this.tubularSegments;
  37056. serializationObject.p = this.p;
  37057. serializationObject.q = this.q;
  37058. return serializationObject;
  37059. };
  37060. ;
  37061. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  37062. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37063. return null; // null since geometry could be something else than a ground...
  37064. }
  37065. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37066. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37067. scene.pushGeometry(torusKnot, true);
  37068. return torusKnot;
  37069. };
  37070. return TorusKnot;
  37071. }(_Primitive));
  37072. Primitives.TorusKnot = TorusKnot;
  37073. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  37074. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  37075. })(BABYLON || (BABYLON = {}));
  37076. //# sourceMappingURL=babylon.geometry.js.map
  37077. var BABYLON;
  37078. (function (BABYLON) {
  37079. var GroundMesh = (function (_super) {
  37080. __extends(GroundMesh, _super);
  37081. function GroundMesh(name, scene) {
  37082. _super.call(this, name, scene);
  37083. this.generateOctree = false;
  37084. this._worldInverse = new BABYLON.Matrix();
  37085. }
  37086. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37087. get: function () {
  37088. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37089. },
  37090. enumerable: true,
  37091. configurable: true
  37092. });
  37093. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37094. get: function () {
  37095. return this._subdivisionsX;
  37096. },
  37097. enumerable: true,
  37098. configurable: true
  37099. });
  37100. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37101. get: function () {
  37102. return this._subdivisionsY;
  37103. },
  37104. enumerable: true,
  37105. configurable: true
  37106. });
  37107. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37108. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37109. this._subdivisionsX = chunksCount;
  37110. this._subdivisionsY = chunksCount;
  37111. this.subdivide(chunksCount);
  37112. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37113. };
  37114. /**
  37115. * Returns a height (y) value in the Worl system :
  37116. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37117. * Returns the ground y position if (x, z) are outside the ground surface.
  37118. * Not pertinent if the ground is rotated.
  37119. */
  37120. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37121. // express x and y in the ground local system
  37122. x -= this.position.x;
  37123. z -= this.position.z;
  37124. x /= this.scaling.x;
  37125. z /= this.scaling.z;
  37126. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37127. return this.position.y;
  37128. }
  37129. if (!this._heightQuads || this._heightQuads.length == 0) {
  37130. this._initHeightQuads();
  37131. this._computeHeightQuads();
  37132. }
  37133. var facet = this._getFacetAt(x, z);
  37134. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37135. // return y in the World system
  37136. return y * this.scaling.y + this.position.y;
  37137. };
  37138. /**
  37139. * Returns a normalized vector (Vector3) orthogonal to the ground
  37140. * at the ground coordinates (x, z) expressed in the World system.
  37141. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  37142. * Not pertinent if the ground is rotated.
  37143. */
  37144. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37145. var normal = new BABYLON.Vector3(0, 1, 0);
  37146. this.getNormalAtCoordinatesToRef(x, z, normal);
  37147. return normal;
  37148. };
  37149. /**
  37150. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37151. * at the ground coordinates (x, z) expressed in the World system.
  37152. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37153. * Not pertinent if the ground is rotated.
  37154. */
  37155. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37156. // express x and y in the ground local system
  37157. x -= this.position.x;
  37158. z -= this.position.z;
  37159. x /= this.scaling.x;
  37160. z /= this.scaling.z;
  37161. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37162. return;
  37163. }
  37164. if (!this._heightQuads || this._heightQuads.length == 0) {
  37165. this._initHeightQuads();
  37166. this._computeHeightQuads();
  37167. }
  37168. var facet = this._getFacetAt(x, z);
  37169. ref.x = facet.x;
  37170. ref.y = facet.y;
  37171. ref.z = facet.z;
  37172. };
  37173. /**
  37174. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37175. * if the ground has been updated.
  37176. * This can be used in the render loop
  37177. */
  37178. GroundMesh.prototype.updateCoordinateHeights = function () {
  37179. if (!this._heightQuads || this._heightQuads.length == 0) {
  37180. this._initHeightQuads();
  37181. }
  37182. this._computeHeightQuads();
  37183. };
  37184. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37185. GroundMesh.prototype._getFacetAt = function (x, z) {
  37186. // retrieve col and row from x, z coordinates in the ground local system
  37187. var subdivisionsX = this._subdivisionsX;
  37188. var subdivisionsY = this._subdivisionsY;
  37189. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37190. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37191. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37192. var facet;
  37193. if (z < quad.slope.x * x + quad.slope.y) {
  37194. facet = quad.facet1;
  37195. }
  37196. else {
  37197. facet = quad.facet2;
  37198. }
  37199. return facet;
  37200. };
  37201. // Creates and populates the heightMap array with "facet" elements :
  37202. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37203. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37204. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37205. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37206. GroundMesh.prototype._initHeightQuads = function () {
  37207. var subdivisionsX = this._subdivisionsX;
  37208. var subdivisionsY = this._subdivisionsY;
  37209. this._heightQuads = new Array();
  37210. for (var row = 0; row < subdivisionsY; row++) {
  37211. for (var col = 0; col < subdivisionsX; col++) {
  37212. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  37213. this._heightQuads[row * subdivisionsX + col] = quad;
  37214. }
  37215. }
  37216. };
  37217. // Compute each quad element values and update the the heightMap array :
  37218. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37219. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37220. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37221. GroundMesh.prototype._computeHeightQuads = function () {
  37222. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37223. var v1 = BABYLON.Tmp.Vector3[3];
  37224. var v2 = BABYLON.Tmp.Vector3[2];
  37225. var v3 = BABYLON.Tmp.Vector3[1];
  37226. var v4 = BABYLON.Tmp.Vector3[0];
  37227. var v1v2 = BABYLON.Tmp.Vector3[4];
  37228. var v1v3 = BABYLON.Tmp.Vector3[5];
  37229. var v1v4 = BABYLON.Tmp.Vector3[6];
  37230. var norm1 = BABYLON.Tmp.Vector3[7];
  37231. var norm2 = BABYLON.Tmp.Vector3[8];
  37232. var i = 0;
  37233. var j = 0;
  37234. var k = 0;
  37235. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37236. var h = 0;
  37237. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37238. var d2 = 0;
  37239. var subdivisionsX = this._subdivisionsX;
  37240. var subdivisionsY = this._subdivisionsY;
  37241. for (var row = 0; row < subdivisionsY; row++) {
  37242. for (var col = 0; col < subdivisionsX; col++) {
  37243. i = col * 3;
  37244. j = row * (subdivisionsX + 1) * 3;
  37245. k = (row + 1) * (subdivisionsX + 1) * 3;
  37246. v1.x = positions[j + i];
  37247. v1.y = positions[j + i + 1];
  37248. v1.z = positions[j + i + 2];
  37249. v2.x = positions[j + i + 3];
  37250. v2.y = positions[j + i + 4];
  37251. v2.z = positions[j + i + 5];
  37252. v3.x = positions[k + i];
  37253. v3.y = positions[k + i + 1];
  37254. v3.z = positions[k + i + 2];
  37255. v4.x = positions[k + i + 3];
  37256. v4.y = positions[k + i + 4];
  37257. v4.z = positions[k + i + 5];
  37258. // 2D slope V1V4
  37259. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37260. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37261. // facet equations :
  37262. // we compute each facet normal vector
  37263. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37264. // we compute the value d by applying the equation to v1 which belongs to the plane
  37265. // then we store the facet equation in a Vector4
  37266. v2.subtractToRef(v1, v1v2);
  37267. v3.subtractToRef(v1, v1v3);
  37268. v4.subtractToRef(v1, v1v4);
  37269. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37270. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37271. norm1.normalize();
  37272. norm2.normalize();
  37273. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37274. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37275. var quad = this._heightQuads[row * subdivisionsX + col];
  37276. quad.slope.copyFromFloats(cd, h);
  37277. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37278. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37279. }
  37280. }
  37281. };
  37282. return GroundMesh;
  37283. }(BABYLON.Mesh));
  37284. BABYLON.GroundMesh = GroundMesh;
  37285. })(BABYLON || (BABYLON = {}));
  37286. //# sourceMappingURL=babylon.groundMesh.js.map
  37287. var BABYLON;
  37288. (function (BABYLON) {
  37289. var LinesMesh = (function (_super) {
  37290. __extends(LinesMesh, _super);
  37291. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  37292. if (parent === void 0) { parent = null; }
  37293. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  37294. this.color = new BABYLON.Color3(1, 1, 1);
  37295. this.alpha = 1;
  37296. this._positionBuffer = {};
  37297. if (source) {
  37298. this.color = source.color.clone();
  37299. this.alpha = source.alpha;
  37300. }
  37301. this._intersectionThreshold = 0.1;
  37302. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  37303. attributes: [BABYLON.VertexBuffer.PositionKind],
  37304. uniforms: ["worldViewProjection", "color"],
  37305. needAlphaBlending: true
  37306. });
  37307. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37308. }
  37309. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37310. /**
  37311. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37312. * This margin is expressed in world space coordinates, so its value may vary.
  37313. * Default value is 0.1
  37314. * @returns the intersection Threshold value.
  37315. */
  37316. get: function () {
  37317. return this._intersectionThreshold;
  37318. },
  37319. /**
  37320. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37321. * This margin is expressed in world space coordinates, so its value may vary.
  37322. * @param value the new threshold to apply
  37323. */
  37324. set: function (value) {
  37325. if (this._intersectionThreshold === value) {
  37326. return;
  37327. }
  37328. this._intersectionThreshold = value;
  37329. if (this.geometry) {
  37330. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37331. }
  37332. },
  37333. enumerable: true,
  37334. configurable: true
  37335. });
  37336. Object.defineProperty(LinesMesh.prototype, "material", {
  37337. get: function () {
  37338. return this._colorShader;
  37339. },
  37340. enumerable: true,
  37341. configurable: true
  37342. });
  37343. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37344. get: function () {
  37345. return false;
  37346. },
  37347. enumerable: true,
  37348. configurable: true
  37349. });
  37350. LinesMesh.prototype.createInstance = function (name) {
  37351. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37352. return null;
  37353. };
  37354. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37355. var engine = this.getScene().getEngine();
  37356. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37357. // VBOs
  37358. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37359. // Color
  37360. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37361. };
  37362. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37363. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37364. return;
  37365. }
  37366. var engine = this.getScene().getEngine();
  37367. // Draw order
  37368. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37369. };
  37370. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37371. this._colorShader.dispose();
  37372. _super.prototype.dispose.call(this, doNotRecurse);
  37373. };
  37374. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37375. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37376. };
  37377. return LinesMesh;
  37378. }(BABYLON.Mesh));
  37379. BABYLON.LinesMesh = LinesMesh;
  37380. })(BABYLON || (BABYLON = {}));
  37381. //# sourceMappingURL=babylon.linesMesh.js.map
  37382. var BABYLON;
  37383. (function (BABYLON) {
  37384. var DefaultLoadingScreen = (function () {
  37385. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  37386. var _this = this;
  37387. if (_loadingText === void 0) { _loadingText = ""; }
  37388. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  37389. this._renderingCanvas = _renderingCanvas;
  37390. this._loadingText = _loadingText;
  37391. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  37392. // Resize
  37393. this._resizeLoadingUI = function () {
  37394. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  37395. _this._loadingDiv.style.position = "absolute";
  37396. _this._loadingDiv.style.left = canvasRect.left + "px";
  37397. _this._loadingDiv.style.top = canvasRect.top + "px";
  37398. _this._loadingDiv.style.width = canvasRect.width + "px";
  37399. _this._loadingDiv.style.height = canvasRect.height + "px";
  37400. };
  37401. }
  37402. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  37403. var _this = this;
  37404. if (this._loadingDiv) {
  37405. // Do not add a loading screen if there is already one
  37406. return;
  37407. }
  37408. this._loadingDiv = document.createElement("div");
  37409. this._loadingDiv.id = "babylonjsLoadingDiv";
  37410. this._loadingDiv.style.opacity = "0";
  37411. this._loadingDiv.style.transition = "opacity 1.5s ease";
  37412. // Loading text
  37413. this._loadingTextDiv = document.createElement("div");
  37414. this._loadingTextDiv.style.position = "absolute";
  37415. this._loadingTextDiv.style.left = "0";
  37416. this._loadingTextDiv.style.top = "50%";
  37417. this._loadingTextDiv.style.marginTop = "80px";
  37418. this._loadingTextDiv.style.width = "100%";
  37419. this._loadingTextDiv.style.height = "20px";
  37420. this._loadingTextDiv.style.fontFamily = "Arial";
  37421. this._loadingTextDiv.style.fontSize = "14px";
  37422. this._loadingTextDiv.style.color = "white";
  37423. this._loadingTextDiv.style.textAlign = "center";
  37424. this._loadingTextDiv.innerHTML = "Loading";
  37425. this._loadingDiv.appendChild(this._loadingTextDiv);
  37426. //set the predefined text
  37427. this._loadingTextDiv.innerHTML = this._loadingText;
  37428. // Loading img
  37429. var imgBack = new Image();
  37430. 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==";
  37431. imgBack.style.position = "absolute";
  37432. imgBack.style.left = "50%";
  37433. imgBack.style.top = "50%";
  37434. imgBack.style.marginLeft = "-50px";
  37435. imgBack.style.marginTop = "-50px";
  37436. imgBack.style.transition = "transform 1.0s ease";
  37437. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  37438. var deg = 360;
  37439. var onTransitionEnd = function () {
  37440. deg += 360;
  37441. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  37442. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  37443. };
  37444. imgBack.addEventListener("transitionend", onTransitionEnd);
  37445. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  37446. this._loadingDiv.appendChild(imgBack);
  37447. // front image
  37448. var imgFront = new Image();
  37449. 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=";
  37450. imgFront.style.position = "absolute";
  37451. imgFront.style.left = "50%";
  37452. imgFront.style.top = "50%";
  37453. imgFront.style.marginLeft = "-50px";
  37454. imgFront.style.marginTop = "-50px";
  37455. this._loadingDiv.appendChild(imgFront);
  37456. this._resizeLoadingUI();
  37457. window.addEventListener("resize", this._resizeLoadingUI);
  37458. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37459. document.body.appendChild(this._loadingDiv);
  37460. setTimeout(function () {
  37461. _this._loadingDiv.style.opacity = "1";
  37462. imgBack.style.transform = "rotateZ(360deg)";
  37463. imgBack.style.webkitTransform = "rotateZ(360deg)";
  37464. }, 0);
  37465. };
  37466. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  37467. var _this = this;
  37468. if (!this._loadingDiv) {
  37469. return;
  37470. }
  37471. var onTransitionEnd = function () {
  37472. if (!_this._loadingDiv) {
  37473. return;
  37474. }
  37475. document.body.removeChild(_this._loadingDiv);
  37476. window.removeEventListener("resize", _this._resizeLoadingUI);
  37477. _this._loadingDiv = null;
  37478. };
  37479. this._loadingDiv.style.opacity = "0";
  37480. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  37481. };
  37482. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  37483. set: function (text) {
  37484. this._loadingText = text;
  37485. if (this._loadingTextDiv) {
  37486. this._loadingTextDiv.innerHTML = this._loadingText;
  37487. }
  37488. },
  37489. enumerable: true,
  37490. configurable: true
  37491. });
  37492. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  37493. get: function () {
  37494. return this._loadingDivBackgroundColor;
  37495. },
  37496. set: function (color) {
  37497. this._loadingDivBackgroundColor = color;
  37498. if (!this._loadingDiv) {
  37499. return;
  37500. }
  37501. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37502. },
  37503. enumerable: true,
  37504. configurable: true
  37505. });
  37506. return DefaultLoadingScreen;
  37507. }());
  37508. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  37509. })(BABYLON || (BABYLON = {}));
  37510. //# sourceMappingURL=babylon.loadingScreen.js.map
  37511. var BABYLON;
  37512. (function (BABYLON) {
  37513. var AudioEngine = (function () {
  37514. function AudioEngine() {
  37515. this._audioContext = null;
  37516. this._audioContextInitialized = false;
  37517. this.canUseWebAudio = false;
  37518. this.WarnedWebAudioUnsupported = false;
  37519. this.unlocked = false;
  37520. this.isMP3supported = false;
  37521. this.isOGGsupported = false;
  37522. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  37523. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  37524. this.canUseWebAudio = true;
  37525. }
  37526. var audioElem = document.createElement('audio');
  37527. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  37528. this.isMP3supported = true;
  37529. }
  37530. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  37531. this.isOGGsupported = true;
  37532. }
  37533. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  37534. this._unlockiOSaudio();
  37535. }
  37536. else {
  37537. this.unlocked = true;
  37538. }
  37539. }
  37540. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  37541. get: function () {
  37542. if (!this._audioContextInitialized) {
  37543. this._initializeAudioContext();
  37544. }
  37545. return this._audioContext;
  37546. },
  37547. enumerable: true,
  37548. configurable: true
  37549. });
  37550. AudioEngine.prototype._unlockiOSaudio = function () {
  37551. var _this = this;
  37552. var unlockaudio = function () {
  37553. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  37554. var source = _this.audioContext.createBufferSource();
  37555. source.buffer = buffer;
  37556. source.connect(_this.audioContext.destination);
  37557. source.start(0);
  37558. setTimeout(function () {
  37559. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  37560. _this.unlocked = true;
  37561. window.removeEventListener('touchend', unlockaudio, false);
  37562. if (_this.onAudioUnlocked) {
  37563. _this.onAudioUnlocked();
  37564. }
  37565. }
  37566. }, 0);
  37567. };
  37568. window.addEventListener('touchend', unlockaudio, false);
  37569. };
  37570. AudioEngine.prototype._initializeAudioContext = function () {
  37571. try {
  37572. if (this.canUseWebAudio) {
  37573. this._audioContext = new AudioContext();
  37574. // create a global volume gain node
  37575. this.masterGain = this._audioContext.createGain();
  37576. this.masterGain.gain.value = 1;
  37577. this.masterGain.connect(this._audioContext.destination);
  37578. this._audioContextInitialized = true;
  37579. }
  37580. }
  37581. catch (e) {
  37582. this.canUseWebAudio = false;
  37583. BABYLON.Tools.Error("Web Audio: " + e.message);
  37584. }
  37585. };
  37586. AudioEngine.prototype.dispose = function () {
  37587. if (this.canUseWebAudio && this._audioContextInitialized) {
  37588. if (this._connectedAnalyser) {
  37589. this._connectedAnalyser.stopDebugCanvas();
  37590. this._connectedAnalyser.dispose();
  37591. this.masterGain.disconnect();
  37592. this.masterGain.connect(this._audioContext.destination);
  37593. this._connectedAnalyser = null;
  37594. }
  37595. this.masterGain.gain.value = 1;
  37596. }
  37597. this.WarnedWebAudioUnsupported = false;
  37598. };
  37599. AudioEngine.prototype.getGlobalVolume = function () {
  37600. if (this.canUseWebAudio && this._audioContextInitialized) {
  37601. return this.masterGain.gain.value;
  37602. }
  37603. else {
  37604. return -1;
  37605. }
  37606. };
  37607. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  37608. if (this.canUseWebAudio && this._audioContextInitialized) {
  37609. this.masterGain.gain.value = newVolume;
  37610. }
  37611. };
  37612. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  37613. if (this._connectedAnalyser) {
  37614. this._connectedAnalyser.stopDebugCanvas();
  37615. }
  37616. if (this.canUseWebAudio && this._audioContextInitialized) {
  37617. this._connectedAnalyser = analyser;
  37618. this.masterGain.disconnect();
  37619. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  37620. }
  37621. };
  37622. return AudioEngine;
  37623. }());
  37624. BABYLON.AudioEngine = AudioEngine;
  37625. })(BABYLON || (BABYLON = {}));
  37626. //# sourceMappingURL=babylon.audioEngine.js.map
  37627. var BABYLON;
  37628. (function (BABYLON) {
  37629. var Sound = (function () {
  37630. /**
  37631. * Create a sound and attach it to a scene
  37632. * @param name Name of your sound
  37633. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  37634. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  37635. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  37636. */
  37637. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  37638. var _this = this;
  37639. this.autoplay = false;
  37640. this.loop = false;
  37641. this.useCustomAttenuation = false;
  37642. this.spatialSound = false;
  37643. this.refDistance = 1;
  37644. this.rolloffFactor = 1;
  37645. this.maxDistance = 100;
  37646. this.distanceModel = "linear";
  37647. this._panningModel = "equalpower";
  37648. this._playbackRate = 1;
  37649. this._streaming = false;
  37650. this._startTime = 0;
  37651. this._startOffset = 0;
  37652. this._position = BABYLON.Vector3.Zero();
  37653. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  37654. this._volume = 1;
  37655. this._isLoaded = false;
  37656. this._isReadyToPlay = false;
  37657. this.isPlaying = false;
  37658. this.isPaused = false;
  37659. this._isDirectional = false;
  37660. // Used if you'd like to create a directional sound.
  37661. // If not set, the sound will be omnidirectional
  37662. this._coneInnerAngle = 360;
  37663. this._coneOuterAngle = 360;
  37664. this._coneOuterGain = 0;
  37665. this._isOutputConnected = false;
  37666. this._urlType = "Unknown";
  37667. this.name = name;
  37668. this._scene = scene;
  37669. this._readyToPlayCallback = readyToPlayCallback;
  37670. // Default custom attenuation function is a linear attenuation
  37671. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  37672. if (currentDistance < maxDistance) {
  37673. return currentVolume * (1 - currentDistance / maxDistance);
  37674. }
  37675. else {
  37676. return 0;
  37677. }
  37678. };
  37679. if (options) {
  37680. this.autoplay = options.autoplay || false;
  37681. this.loop = options.loop || false;
  37682. // if volume === 0, we need another way to check this option
  37683. if (options.volume !== undefined) {
  37684. this._volume = options.volume;
  37685. }
  37686. this.spatialSound = options.spatialSound || false;
  37687. this.maxDistance = options.maxDistance || 100;
  37688. this.useCustomAttenuation = options.useCustomAttenuation || false;
  37689. this.rolloffFactor = options.rolloffFactor || 1;
  37690. this.refDistance = options.refDistance || 1;
  37691. this.distanceModel = options.distanceModel || "linear";
  37692. this._playbackRate = options.playbackRate || 1;
  37693. this._streaming = options.streaming || false;
  37694. }
  37695. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37696. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  37697. this._soundGain.gain.value = this._volume;
  37698. this._inputAudioNode = this._soundGain;
  37699. this._ouputAudioNode = this._soundGain;
  37700. if (this.spatialSound) {
  37701. this._createSpatialParameters();
  37702. }
  37703. this._scene.mainSoundTrack.AddSound(this);
  37704. var validParameter = true;
  37705. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  37706. if (urlOrArrayBuffer) {
  37707. if (typeof (urlOrArrayBuffer) === "string")
  37708. this._urlType = "String";
  37709. if (Array.isArray(urlOrArrayBuffer))
  37710. this._urlType = "Array";
  37711. if (urlOrArrayBuffer instanceof ArrayBuffer)
  37712. this._urlType = "ArrayBuffer";
  37713. var urls = [];
  37714. var codecSupportedFound = false;
  37715. switch (this._urlType) {
  37716. case "ArrayBuffer":
  37717. if (urlOrArrayBuffer.byteLength > 0) {
  37718. codecSupportedFound = true;
  37719. this._soundLoaded(urlOrArrayBuffer);
  37720. }
  37721. break;
  37722. case "String":
  37723. urls.push(urlOrArrayBuffer);
  37724. case "Array":
  37725. if (urls.length === 0)
  37726. urls = urlOrArrayBuffer;
  37727. // If we found a supported format, we load it immediately and stop the loop
  37728. for (var i = 0; i < urls.length; i++) {
  37729. var url = urls[i];
  37730. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  37731. codecSupportedFound = true;
  37732. }
  37733. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  37734. codecSupportedFound = true;
  37735. }
  37736. if (url.indexOf(".wav", url.length - 4) !== -1) {
  37737. codecSupportedFound = true;
  37738. }
  37739. if (codecSupportedFound) {
  37740. // Loading sound using XHR2
  37741. if (!this._streaming) {
  37742. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  37743. }
  37744. else {
  37745. this._htmlAudioElement = new Audio(url);
  37746. this._htmlAudioElement.controls = false;
  37747. this._htmlAudioElement.loop = this.loop;
  37748. this._htmlAudioElement.crossOrigin = "anonymous";
  37749. this._htmlAudioElement.preload = "auto";
  37750. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  37751. _this._isReadyToPlay = true;
  37752. if (_this.autoplay) {
  37753. _this.play();
  37754. }
  37755. if (_this._readyToPlayCallback) {
  37756. _this._readyToPlayCallback();
  37757. }
  37758. });
  37759. document.body.appendChild(this._htmlAudioElement);
  37760. }
  37761. break;
  37762. }
  37763. }
  37764. break;
  37765. default:
  37766. validParameter = false;
  37767. break;
  37768. }
  37769. if (!validParameter) {
  37770. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  37771. }
  37772. else {
  37773. if (!codecSupportedFound) {
  37774. this._isReadyToPlay = true;
  37775. // Simulating a ready to play event to avoid breaking code path
  37776. if (this._readyToPlayCallback) {
  37777. window.setTimeout(function () {
  37778. _this._readyToPlayCallback();
  37779. }, 1000);
  37780. }
  37781. }
  37782. }
  37783. }
  37784. }
  37785. else {
  37786. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  37787. this._scene.mainSoundTrack.AddSound(this);
  37788. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  37789. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  37790. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  37791. }
  37792. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  37793. if (this._readyToPlayCallback) {
  37794. window.setTimeout(function () {
  37795. _this._readyToPlayCallback();
  37796. }, 1000);
  37797. }
  37798. }
  37799. }
  37800. Sound.prototype.dispose = function () {
  37801. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  37802. if (this.isPlaying) {
  37803. this.stop();
  37804. }
  37805. this._isReadyToPlay = false;
  37806. if (this.soundTrackId === -1) {
  37807. this._scene.mainSoundTrack.RemoveSound(this);
  37808. }
  37809. else {
  37810. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  37811. }
  37812. if (this._soundGain) {
  37813. this._soundGain.disconnect();
  37814. this._soundGain = null;
  37815. }
  37816. if (this._soundPanner) {
  37817. this._soundPanner.disconnect();
  37818. this._soundPanner = null;
  37819. }
  37820. if (this._soundSource) {
  37821. this._soundSource.disconnect();
  37822. this._soundSource = null;
  37823. }
  37824. this._audioBuffer = null;
  37825. if (this._htmlAudioElement) {
  37826. this._htmlAudioElement.pause();
  37827. this._htmlAudioElement.src = "";
  37828. document.body.removeChild(this._htmlAudioElement);
  37829. }
  37830. if (this._connectedMesh) {
  37831. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37832. this._connectedMesh = null;
  37833. }
  37834. }
  37835. };
  37836. Sound.prototype._soundLoaded = function (audioData) {
  37837. var _this = this;
  37838. this._isLoaded = true;
  37839. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  37840. _this._audioBuffer = buffer;
  37841. _this._isReadyToPlay = true;
  37842. if (_this.autoplay) {
  37843. _this.play();
  37844. }
  37845. if (_this._readyToPlayCallback) {
  37846. _this._readyToPlayCallback();
  37847. }
  37848. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  37849. };
  37850. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  37851. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37852. this._audioBuffer = audioBuffer;
  37853. this._isReadyToPlay = true;
  37854. }
  37855. };
  37856. Sound.prototype.updateOptions = function (options) {
  37857. if (options) {
  37858. this.loop = options.loop || this.loop;
  37859. this.maxDistance = options.maxDistance || this.maxDistance;
  37860. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  37861. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  37862. this.refDistance = options.refDistance || this.refDistance;
  37863. this.distanceModel = options.distanceModel || this.distanceModel;
  37864. this._playbackRate = options.playbackRate || this._playbackRate;
  37865. this._updateSpatialParameters();
  37866. if (this.isPlaying) {
  37867. if (this._streaming) {
  37868. this._htmlAudioElement.playbackRate = this._playbackRate;
  37869. }
  37870. else {
  37871. this._soundSource.playbackRate.value = this._playbackRate;
  37872. }
  37873. }
  37874. }
  37875. };
  37876. Sound.prototype._createSpatialParameters = function () {
  37877. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37878. if (this._scene.headphone) {
  37879. this._panningModel = "HRTF";
  37880. }
  37881. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  37882. this._updateSpatialParameters();
  37883. this._soundPanner.connect(this._ouputAudioNode);
  37884. this._inputAudioNode = this._soundPanner;
  37885. }
  37886. };
  37887. Sound.prototype._updateSpatialParameters = function () {
  37888. if (this.spatialSound) {
  37889. if (this.useCustomAttenuation) {
  37890. // Tricks to disable in a way embedded Web Audio attenuation
  37891. this._soundPanner.distanceModel = "linear";
  37892. this._soundPanner.maxDistance = Number.MAX_VALUE;
  37893. this._soundPanner.refDistance = 1;
  37894. this._soundPanner.rolloffFactor = 1;
  37895. this._soundPanner.panningModel = this._panningModel;
  37896. }
  37897. else {
  37898. this._soundPanner.distanceModel = this.distanceModel;
  37899. this._soundPanner.maxDistance = this.maxDistance;
  37900. this._soundPanner.refDistance = this.refDistance;
  37901. this._soundPanner.rolloffFactor = this.rolloffFactor;
  37902. this._soundPanner.panningModel = this._panningModel;
  37903. }
  37904. }
  37905. };
  37906. Sound.prototype.switchPanningModelToHRTF = function () {
  37907. this._panningModel = "HRTF";
  37908. this._switchPanningModel();
  37909. };
  37910. Sound.prototype.switchPanningModelToEqualPower = function () {
  37911. this._panningModel = "equalpower";
  37912. this._switchPanningModel();
  37913. };
  37914. Sound.prototype._switchPanningModel = function () {
  37915. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  37916. this._soundPanner.panningModel = this._panningModel;
  37917. }
  37918. };
  37919. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  37920. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37921. if (this._isOutputConnected) {
  37922. this._ouputAudioNode.disconnect();
  37923. }
  37924. this._ouputAudioNode.connect(soundTrackAudioNode);
  37925. this._isOutputConnected = true;
  37926. }
  37927. };
  37928. /**
  37929. * Transform this sound into a directional source
  37930. * @param coneInnerAngle Size of the inner cone in degree
  37931. * @param coneOuterAngle Size of the outer cone in degree
  37932. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  37933. */
  37934. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  37935. if (coneOuterAngle < coneInnerAngle) {
  37936. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  37937. return;
  37938. }
  37939. this._coneInnerAngle = coneInnerAngle;
  37940. this._coneOuterAngle = coneOuterAngle;
  37941. this._coneOuterGain = coneOuterGain;
  37942. this._isDirectional = true;
  37943. if (this.isPlaying && this.loop) {
  37944. this.stop();
  37945. this.play();
  37946. }
  37947. };
  37948. Sound.prototype.setPosition = function (newPosition) {
  37949. this._position = newPosition;
  37950. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  37951. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  37952. }
  37953. };
  37954. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  37955. this._localDirection = newLocalDirection;
  37956. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  37957. this._updateDirection();
  37958. }
  37959. };
  37960. Sound.prototype._updateDirection = function () {
  37961. var mat = this._connectedMesh.getWorldMatrix();
  37962. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  37963. direction.normalize();
  37964. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  37965. };
  37966. Sound.prototype.updateDistanceFromListener = function () {
  37967. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  37968. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  37969. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  37970. }
  37971. };
  37972. Sound.prototype.setAttenuationFunction = function (callback) {
  37973. this._customAttenuationFunction = callback;
  37974. };
  37975. /**
  37976. * Play the sound
  37977. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  37978. * @param offset (optional) Start the sound setting it at a specific time
  37979. */
  37980. Sound.prototype.play = function (time, offset) {
  37981. var _this = this;
  37982. if (this._isReadyToPlay && this._scene.audioEnabled) {
  37983. try {
  37984. if (this._startOffset < 0) {
  37985. time = -this._startOffset;
  37986. this._startOffset = 0;
  37987. }
  37988. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  37989. if (!this._soundSource || !this._streamingSource) {
  37990. if (this.spatialSound) {
  37991. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  37992. if (this._isDirectional) {
  37993. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  37994. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  37995. this._soundPanner.coneOuterGain = this._coneOuterGain;
  37996. if (this._connectedMesh) {
  37997. this._updateDirection();
  37998. }
  37999. else {
  38000. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  38001. }
  38002. }
  38003. }
  38004. }
  38005. if (this._streaming) {
  38006. if (!this._streamingSource) {
  38007. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  38008. this._htmlAudioElement.onended = function () { _this._onended(); };
  38009. this._htmlAudioElement.playbackRate = this._playbackRate;
  38010. }
  38011. this._streamingSource.disconnect();
  38012. this._streamingSource.connect(this._inputAudioNode);
  38013. this._htmlAudioElement.play();
  38014. }
  38015. else {
  38016. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  38017. this._soundSource.buffer = this._audioBuffer;
  38018. this._soundSource.connect(this._inputAudioNode);
  38019. this._soundSource.loop = this.loop;
  38020. this._soundSource.playbackRate.value = this._playbackRate;
  38021. this._soundSource.onended = function () { _this._onended(); };
  38022. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  38023. }
  38024. this._startTime = startTime;
  38025. this.isPlaying = true;
  38026. this.isPaused = false;
  38027. }
  38028. catch (ex) {
  38029. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  38030. }
  38031. }
  38032. };
  38033. Sound.prototype._onended = function () {
  38034. this.isPlaying = false;
  38035. if (this.onended) {
  38036. this.onended();
  38037. }
  38038. };
  38039. /**
  38040. * Stop the sound
  38041. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  38042. */
  38043. Sound.prototype.stop = function (time) {
  38044. if (this.isPlaying) {
  38045. if (this._streaming) {
  38046. this._htmlAudioElement.pause();
  38047. // Test needed for Firefox or it will generate an Invalid State Error
  38048. if (this._htmlAudioElement.currentTime > 0) {
  38049. this._htmlAudioElement.currentTime = 0;
  38050. }
  38051. }
  38052. else {
  38053. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38054. this._soundSource.stop(stopTime);
  38055. this._soundSource.onended = null;
  38056. if (!this.isPaused) {
  38057. this._startOffset = 0;
  38058. }
  38059. }
  38060. this.isPlaying = false;
  38061. }
  38062. };
  38063. Sound.prototype.pause = function () {
  38064. if (this.isPlaying) {
  38065. this.isPaused = true;
  38066. if (this._streaming) {
  38067. this._htmlAudioElement.pause();
  38068. }
  38069. else {
  38070. this.stop(0);
  38071. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  38072. }
  38073. }
  38074. };
  38075. Sound.prototype.setVolume = function (newVolume, time) {
  38076. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38077. if (time) {
  38078. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  38079. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  38080. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  38081. }
  38082. else {
  38083. this._soundGain.gain.value = newVolume;
  38084. }
  38085. }
  38086. this._volume = newVolume;
  38087. };
  38088. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  38089. this._playbackRate = newPlaybackRate;
  38090. if (this.isPlaying) {
  38091. if (this._streaming) {
  38092. this._htmlAudioElement.playbackRate = this._playbackRate;
  38093. }
  38094. else {
  38095. this._soundSource.playbackRate.value = this._playbackRate;
  38096. }
  38097. }
  38098. };
  38099. Sound.prototype.getVolume = function () {
  38100. return this._volume;
  38101. };
  38102. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  38103. var _this = this;
  38104. if (this._connectedMesh) {
  38105. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38106. this._registerFunc = null;
  38107. }
  38108. this._connectedMesh = meshToConnectTo;
  38109. if (!this.spatialSound) {
  38110. this.spatialSound = true;
  38111. this._createSpatialParameters();
  38112. if (this.isPlaying && this.loop) {
  38113. this.stop();
  38114. this.play();
  38115. }
  38116. }
  38117. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  38118. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  38119. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  38120. };
  38121. Sound.prototype.detachFromMesh = function () {
  38122. if (this._connectedMesh) {
  38123. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38124. this._registerFunc = null;
  38125. this._connectedMesh = null;
  38126. }
  38127. };
  38128. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  38129. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  38130. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  38131. this._updateDirection();
  38132. }
  38133. };
  38134. Sound.prototype.clone = function () {
  38135. var _this = this;
  38136. if (!this._streaming) {
  38137. var setBufferAndRun = function () {
  38138. if (_this._isReadyToPlay) {
  38139. clonedSound._audioBuffer = _this.getAudioBuffer();
  38140. clonedSound._isReadyToPlay = true;
  38141. if (clonedSound.autoplay) {
  38142. clonedSound.play();
  38143. }
  38144. }
  38145. else {
  38146. window.setTimeout(setBufferAndRun, 300);
  38147. }
  38148. };
  38149. var currentOptions = {
  38150. autoplay: this.autoplay, loop: this.loop,
  38151. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  38152. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  38153. refDistance: this.refDistance, distanceModel: this.distanceModel
  38154. };
  38155. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  38156. if (this.useCustomAttenuation) {
  38157. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  38158. }
  38159. clonedSound.setPosition(this._position);
  38160. clonedSound.setPlaybackRate(this._playbackRate);
  38161. setBufferAndRun();
  38162. return clonedSound;
  38163. }
  38164. else {
  38165. return null;
  38166. }
  38167. };
  38168. Sound.prototype.getAudioBuffer = function () {
  38169. return this._audioBuffer;
  38170. };
  38171. Sound.prototype.serialize = function () {
  38172. var serializationObject = {
  38173. name: this.name,
  38174. url: this.name,
  38175. autoplay: this.autoplay,
  38176. loop: this.loop,
  38177. volume: this._volume,
  38178. spatialSound: this.spatialSound,
  38179. maxDistance: this.maxDistance,
  38180. rolloffFactor: this.rolloffFactor,
  38181. refDistance: this.refDistance,
  38182. distanceModel: this.distanceModel,
  38183. playbackRate: this._playbackRate,
  38184. panningModel: this._panningModel,
  38185. soundTrackId: this.soundTrackId
  38186. };
  38187. if (this.spatialSound) {
  38188. if (this._connectedMesh)
  38189. serializationObject.connectedMeshId = this._connectedMesh.id;
  38190. serializationObject.position = this._position.asArray();
  38191. serializationObject.refDistance = this.refDistance;
  38192. serializationObject.distanceModel = this.distanceModel;
  38193. serializationObject.isDirectional = this._isDirectional;
  38194. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  38195. serializationObject.coneInnerAngle = this._coneInnerAngle;
  38196. serializationObject.coneOuterAngle = this._coneOuterAngle;
  38197. serializationObject.coneOuterGain = this._coneOuterGain;
  38198. }
  38199. return serializationObject;
  38200. };
  38201. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  38202. var soundName = parsedSound.name;
  38203. var soundUrl;
  38204. if (parsedSound.url) {
  38205. soundUrl = rootUrl + parsedSound.url;
  38206. }
  38207. else {
  38208. soundUrl = rootUrl + soundName;
  38209. }
  38210. var options = {
  38211. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  38212. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  38213. rolloffFactor: parsedSound.rolloffFactor,
  38214. refDistance: parsedSound.refDistance,
  38215. distanceModel: parsedSound.distanceModel,
  38216. playbackRate: parsedSound.playbackRate
  38217. };
  38218. var newSound;
  38219. if (!sourceSound) {
  38220. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  38221. scene._addPendingData(newSound);
  38222. }
  38223. else {
  38224. var setBufferAndRun = function () {
  38225. if (sourceSound._isReadyToPlay) {
  38226. newSound._audioBuffer = sourceSound.getAudioBuffer();
  38227. newSound._isReadyToPlay = true;
  38228. if (newSound.autoplay) {
  38229. newSound.play();
  38230. }
  38231. }
  38232. else {
  38233. window.setTimeout(setBufferAndRun, 300);
  38234. }
  38235. };
  38236. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  38237. setBufferAndRun();
  38238. }
  38239. if (parsedSound.position) {
  38240. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  38241. newSound.setPosition(soundPosition);
  38242. }
  38243. if (parsedSound.isDirectional) {
  38244. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  38245. if (parsedSound.localDirectionToMesh) {
  38246. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  38247. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  38248. }
  38249. }
  38250. if (parsedSound.connectedMeshId) {
  38251. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  38252. if (connectedMesh) {
  38253. newSound.attachToMesh(connectedMesh);
  38254. }
  38255. }
  38256. return newSound;
  38257. };
  38258. return Sound;
  38259. }());
  38260. BABYLON.Sound = Sound;
  38261. })(BABYLON || (BABYLON = {}));
  38262. //# sourceMappingURL=babylon.sound.js.map
  38263. var BABYLON;
  38264. (function (BABYLON) {
  38265. var SoundTrack = (function () {
  38266. function SoundTrack(scene, options) {
  38267. this.id = -1;
  38268. this._isMainTrack = false;
  38269. this._isInitialized = false;
  38270. this._scene = scene;
  38271. this.soundCollection = new Array();
  38272. this._options = options;
  38273. if (!this._isMainTrack) {
  38274. this._scene.soundTracks.push(this);
  38275. this.id = this._scene.soundTracks.length - 1;
  38276. }
  38277. }
  38278. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  38279. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38280. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  38281. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  38282. if (this._options) {
  38283. if (this._options.volume) {
  38284. this._outputAudioNode.gain.value = this._options.volume;
  38285. }
  38286. if (this._options.mainTrack) {
  38287. this._isMainTrack = this._options.mainTrack;
  38288. }
  38289. }
  38290. this._isInitialized = true;
  38291. }
  38292. };
  38293. SoundTrack.prototype.dispose = function () {
  38294. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38295. if (this._connectedAnalyser) {
  38296. this._connectedAnalyser.stopDebugCanvas();
  38297. }
  38298. while (this.soundCollection.length) {
  38299. this.soundCollection[0].dispose();
  38300. }
  38301. if (this._outputAudioNode) {
  38302. this._outputAudioNode.disconnect();
  38303. }
  38304. this._outputAudioNode = null;
  38305. }
  38306. };
  38307. SoundTrack.prototype.AddSound = function (sound) {
  38308. if (!this._isInitialized) {
  38309. this._initializeSoundTrackAudioGraph();
  38310. }
  38311. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38312. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  38313. }
  38314. if (sound.soundTrackId) {
  38315. if (sound.soundTrackId === -1) {
  38316. this._scene.mainSoundTrack.RemoveSound(sound);
  38317. }
  38318. else {
  38319. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  38320. }
  38321. }
  38322. this.soundCollection.push(sound);
  38323. sound.soundTrackId = this.id;
  38324. };
  38325. SoundTrack.prototype.RemoveSound = function (sound) {
  38326. var index = this.soundCollection.indexOf(sound);
  38327. if (index !== -1) {
  38328. this.soundCollection.splice(index, 1);
  38329. }
  38330. };
  38331. SoundTrack.prototype.setVolume = function (newVolume) {
  38332. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38333. this._outputAudioNode.gain.value = newVolume;
  38334. }
  38335. };
  38336. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  38337. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38338. for (var i = 0; i < this.soundCollection.length; i++) {
  38339. this.soundCollection[i].switchPanningModelToHRTF();
  38340. }
  38341. }
  38342. };
  38343. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  38344. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38345. for (var i = 0; i < this.soundCollection.length; i++) {
  38346. this.soundCollection[i].switchPanningModelToEqualPower();
  38347. }
  38348. }
  38349. };
  38350. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  38351. if (this._connectedAnalyser) {
  38352. this._connectedAnalyser.stopDebugCanvas();
  38353. }
  38354. this._connectedAnalyser = analyser;
  38355. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38356. this._outputAudioNode.disconnect();
  38357. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  38358. }
  38359. };
  38360. return SoundTrack;
  38361. }());
  38362. BABYLON.SoundTrack = SoundTrack;
  38363. })(BABYLON || (BABYLON = {}));
  38364. //# sourceMappingURL=babylon.soundtrack.js.map
  38365. var BABYLON;
  38366. (function (BABYLON) {
  38367. /**
  38368. * Special Glow Blur post process only blurring the alpha channel
  38369. * It enforces keeping the most luminous color in the color channel.
  38370. */
  38371. var GlowBlurPostProcess = (function (_super) {
  38372. __extends(GlowBlurPostProcess, _super);
  38373. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  38374. var _this = this;
  38375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38376. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  38377. this.direction = direction;
  38378. this.blurWidth = blurWidth;
  38379. this.onApplyObservable.add(function (effect) {
  38380. effect.setFloat2("screenSize", _this.width, _this.height);
  38381. effect.setVector2("direction", _this.direction);
  38382. effect.setFloat("blurWidth", _this.blurWidth);
  38383. });
  38384. }
  38385. return GlowBlurPostProcess;
  38386. }(BABYLON.PostProcess));
  38387. /**
  38388. * The highlight layer Helps adding a glow effect around a mesh.
  38389. *
  38390. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  38391. * glowy meshes to your scene.
  38392. *
  38393. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  38394. */
  38395. var HighlightLayer = (function () {
  38396. /**
  38397. * Instantiates a new highlight Layer and references it to the scene..
  38398. * @param name The name of the layer
  38399. * @param scene The scene to use the layer in
  38400. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  38401. */
  38402. function HighlightLayer(name, scene, options) {
  38403. this._vertexBuffers = {};
  38404. this._mainTextureDesiredSize = { width: 0, height: 0 };
  38405. this._meshes = {};
  38406. this._maxSize = 0;
  38407. this._shouldRender = false;
  38408. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  38409. this._excludedMeshes = {};
  38410. /**
  38411. * Specifies whether or not the inner glow is ACTIVE in the layer.
  38412. */
  38413. this.innerGlow = true;
  38414. /**
  38415. * Specifies whether or not the outer glow is ACTIVE in the layer.
  38416. */
  38417. this.outerGlow = true;
  38418. /**
  38419. * Specifies wether the highlight layer is enabled or not.
  38420. */
  38421. this.isEnabled = true;
  38422. /**
  38423. * An event triggered when the highlight layer has been disposed.
  38424. * @type {BABYLON.Observable}
  38425. */
  38426. this.onDisposeObservable = new BABYLON.Observable();
  38427. /**
  38428. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  38429. * @type {BABYLON.Observable}
  38430. */
  38431. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  38432. /**
  38433. * An event triggered when the highlight layer is being blurred.
  38434. * @type {BABYLON.Observable}
  38435. */
  38436. this.onBeforeBlurObservable = new BABYLON.Observable();
  38437. /**
  38438. * An event triggered when the highlight layer has been blurred.
  38439. * @type {BABYLON.Observable}
  38440. */
  38441. this.onAfterBlurObservable = new BABYLON.Observable();
  38442. /**
  38443. * An event triggered when the glowing blurred texture is being merged in the scene.
  38444. * @type {BABYLON.Observable}
  38445. */
  38446. this.onBeforeComposeObservable = new BABYLON.Observable();
  38447. /**
  38448. * An event triggered when the glowing blurred texture has been merged in the scene.
  38449. * @type {BABYLON.Observable}
  38450. */
  38451. this.onAfterComposeObservable = new BABYLON.Observable();
  38452. /**
  38453. * An event triggered when the highlight layer changes its size.
  38454. * @type {BABYLON.Observable}
  38455. */
  38456. this.onSizeChangedObservable = new BABYLON.Observable();
  38457. this._scene = scene;
  38458. var engine = scene.getEngine();
  38459. this._engine = engine;
  38460. this._maxSize = this._engine.getCaps().maxTextureSize;
  38461. this._scene.highlightLayers.push(this);
  38462. // Warn on stencil.
  38463. if (!this._engine.isStencilEnable) {
  38464. 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 }");
  38465. }
  38466. // Adapt options
  38467. this._options = options || {
  38468. mainTextureRatio: 0.25,
  38469. blurTextureSizeRatio: 0.5,
  38470. blurHorizontalSize: 1,
  38471. blurVerticalSize: 1,
  38472. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  38473. };
  38474. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  38475. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  38476. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  38477. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  38478. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  38479. // VBO
  38480. var vertices = [];
  38481. vertices.push(1, 1);
  38482. vertices.push(-1, 1);
  38483. vertices.push(-1, -1);
  38484. vertices.push(1, -1);
  38485. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38486. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38487. // Indices
  38488. var indices = [];
  38489. indices.push(0);
  38490. indices.push(1);
  38491. indices.push(2);
  38492. indices.push(0);
  38493. indices.push(2);
  38494. indices.push(3);
  38495. this._indexBuffer = engine.createIndexBuffer(indices);
  38496. // Effect
  38497. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  38498. // Render target
  38499. this.setMainTextureSize();
  38500. // Create Textures and post processes
  38501. this.createTextureAndPostProcesses();
  38502. }
  38503. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  38504. /**
  38505. * Gets the horizontal size of the blur.
  38506. */
  38507. get: function () {
  38508. return this._horizontalBlurPostprocess.blurWidth;
  38509. },
  38510. /**
  38511. * Specifies the horizontal size of the blur.
  38512. */
  38513. set: function (value) {
  38514. this._horizontalBlurPostprocess.blurWidth = value;
  38515. },
  38516. enumerable: true,
  38517. configurable: true
  38518. });
  38519. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  38520. /**
  38521. * Gets the vertical size of the blur.
  38522. */
  38523. get: function () {
  38524. return this._verticalBlurPostprocess.blurWidth;
  38525. },
  38526. /**
  38527. * Specifies the vertical size of the blur.
  38528. */
  38529. set: function (value) {
  38530. this._verticalBlurPostprocess.blurWidth = value;
  38531. },
  38532. enumerable: true,
  38533. configurable: true
  38534. });
  38535. Object.defineProperty(HighlightLayer.prototype, "camera", {
  38536. /**
  38537. * Gets the camera attached to the layer.
  38538. */
  38539. get: function () {
  38540. return this._options.camera;
  38541. },
  38542. enumerable: true,
  38543. configurable: true
  38544. });
  38545. /**
  38546. * Creates the render target textures and post processes used in the highlight layer.
  38547. */
  38548. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  38549. var _this = this;
  38550. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  38551. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  38552. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  38553. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  38554. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  38555. width: this._mainTextureDesiredSize.width,
  38556. height: this._mainTextureDesiredSize.height
  38557. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38558. this._mainTexture.activeCamera = this._options.camera;
  38559. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38560. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38561. this._mainTexture.anisotropicFilteringLevel = 1;
  38562. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38563. this._mainTexture.renderParticles = false;
  38564. this._mainTexture.renderList = null;
  38565. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  38566. width: blurTextureWidth,
  38567. height: blurTextureHeight
  38568. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38569. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38570. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38571. this._blurTexture.anisotropicFilteringLevel = 16;
  38572. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38573. this._blurTexture.renderParticles = false;
  38574. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38575. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  38576. effect.setTexture("textureSampler", _this._mainTexture);
  38577. });
  38578. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  38579. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38580. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38581. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38582. });
  38583. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38584. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38585. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38586. });
  38587. }
  38588. else {
  38589. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38590. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38591. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38592. });
  38593. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38594. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38595. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38596. });
  38597. }
  38598. this._mainTexture.onAfterUnbindObservable.add(function () {
  38599. _this.onBeforeBlurObservable.notifyObservers(_this);
  38600. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  38601. _this.onAfterBlurObservable.notifyObservers(_this);
  38602. });
  38603. // Custom render function
  38604. var renderSubMesh = function (subMesh) {
  38605. var mesh = subMesh.getRenderingMesh();
  38606. var scene = _this._scene;
  38607. var engine = scene.getEngine();
  38608. // Culling
  38609. engine.setState(subMesh.getMaterial().backFaceCulling);
  38610. // Managing instances
  38611. var batch = mesh._getInstancesRenderList(subMesh._id);
  38612. if (batch.mustReturn) {
  38613. return;
  38614. }
  38615. // Excluded Mesh
  38616. if (_this._excludedMeshes[mesh.id]) {
  38617. return;
  38618. }
  38619. ;
  38620. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38621. var highlightLayerMesh = _this._meshes[mesh.id];
  38622. var material = subMesh.getMaterial();
  38623. var emissiveTexture = null;
  38624. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  38625. emissiveTexture = material.emissiveTexture;
  38626. }
  38627. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  38628. engine.enableEffect(_this._glowMapGenerationEffect);
  38629. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  38630. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  38631. if (highlightLayerMesh) {
  38632. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  38633. }
  38634. else {
  38635. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  38636. }
  38637. // Alpha test
  38638. if (material && material.needAlphaTesting()) {
  38639. var alphaTexture = material.getAlphaTestTexture();
  38640. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  38641. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38642. }
  38643. // Glow emissive only
  38644. if (emissiveTexture) {
  38645. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  38646. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  38647. }
  38648. // Bones
  38649. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38650. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38651. }
  38652. // Draw
  38653. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  38654. }
  38655. else {
  38656. // Need to reset refresh rate of the shadowMap
  38657. _this._mainTexture.resetRefreshCounter();
  38658. }
  38659. };
  38660. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38661. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  38662. var index;
  38663. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38664. renderSubMesh(opaqueSubMeshes.data[index]);
  38665. }
  38666. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38667. renderSubMesh(alphaTestSubMeshes.data[index]);
  38668. }
  38669. for (index = 0; index < transparentSubMeshes.length; index++) {
  38670. renderSubMesh(transparentSubMeshes.data[index]);
  38671. }
  38672. };
  38673. this._mainTexture.onClearObservable.add(function (engine) {
  38674. engine.clear(HighlightLayer.neutralColor, true, true, true);
  38675. });
  38676. };
  38677. /**
  38678. * Checks for the readiness of the element composing the layer.
  38679. * @param subMesh the mesh to check for
  38680. * @param useInstances specify wether or not to use instances to render the mesh
  38681. * @param emissiveTexture the associated emissive texture used to generate the glow
  38682. * @return true if ready otherwise, false
  38683. */
  38684. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  38685. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  38686. return false;
  38687. }
  38688. var defines = [];
  38689. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38690. var mesh = subMesh.getMesh();
  38691. var material = subMesh.getMaterial();
  38692. var uv1 = false;
  38693. var uv2 = false;
  38694. // Alpha test
  38695. if (material && material.needAlphaTesting()) {
  38696. var alphaTexture = material.getAlphaTestTexture();
  38697. if (alphaTexture) {
  38698. defines.push("#define ALPHATEST");
  38699. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38700. alphaTexture.coordinatesIndex === 1) {
  38701. defines.push("#define DIFFUSEUV2");
  38702. uv2 = true;
  38703. }
  38704. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38705. defines.push("#define DIFFUSEUV1");
  38706. uv1 = true;
  38707. }
  38708. }
  38709. }
  38710. // Emissive
  38711. if (emissiveTexture) {
  38712. defines.push("#define EMISSIVE");
  38713. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38714. emissiveTexture.coordinatesIndex === 1) {
  38715. defines.push("#define EMISSIVEUV2");
  38716. uv2 = true;
  38717. }
  38718. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38719. defines.push("#define EMISSIVEUV1");
  38720. uv1 = true;
  38721. }
  38722. }
  38723. if (uv1) {
  38724. attribs.push(BABYLON.VertexBuffer.UVKind);
  38725. defines.push("#define UV1");
  38726. }
  38727. if (uv2) {
  38728. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38729. defines.push("#define UV2");
  38730. }
  38731. // Bones
  38732. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38733. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38734. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38735. if (mesh.numBoneInfluencers > 4) {
  38736. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38737. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38738. }
  38739. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38740. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38741. }
  38742. else {
  38743. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38744. }
  38745. // Instances
  38746. if (useInstances) {
  38747. defines.push("#define INSTANCES");
  38748. attribs.push("world0");
  38749. attribs.push("world1");
  38750. attribs.push("world2");
  38751. attribs.push("world3");
  38752. }
  38753. // Get correct effect
  38754. var join = defines.join("\n");
  38755. if (this._cachedDefines !== join) {
  38756. this._cachedDefines = join;
  38757. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  38758. }
  38759. return this._glowMapGenerationEffect.isReady();
  38760. };
  38761. /**
  38762. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  38763. */
  38764. HighlightLayer.prototype.render = function () {
  38765. var currentEffect = this._glowMapMergeEffect;
  38766. // Check
  38767. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  38768. return;
  38769. var engine = this._scene.getEngine();
  38770. this.onBeforeComposeObservable.notifyObservers(this);
  38771. // Render
  38772. engine.enableEffect(currentEffect);
  38773. engine.setState(false);
  38774. // Cache
  38775. var previousStencilBuffer = engine.getStencilBuffer();
  38776. var previousStencilFunction = engine.getStencilFunction();
  38777. var previousStencilMask = engine.getStencilMask();
  38778. var previousAlphaMode = engine.getAlphaMode();
  38779. // Texture
  38780. currentEffect.setTexture("textureSampler", this._blurTexture);
  38781. // VBOs
  38782. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38783. // Draw order
  38784. engine.setAlphaMode(this._options.alphaBlendingMode);
  38785. engine.setStencilMask(0x00);
  38786. engine.setStencilBuffer(true);
  38787. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  38788. if (this.outerGlow) {
  38789. currentEffect.setFloat("offset", 0);
  38790. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  38791. engine.draw(true, 0, 6);
  38792. }
  38793. if (this.innerGlow) {
  38794. currentEffect.setFloat("offset", 1);
  38795. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  38796. engine.draw(true, 0, 6);
  38797. }
  38798. // Restore Cache
  38799. engine.setStencilFunction(previousStencilFunction);
  38800. engine.setStencilMask(previousStencilMask);
  38801. engine.setAlphaMode(previousAlphaMode);
  38802. engine.setStencilBuffer(previousStencilBuffer);
  38803. this.onAfterComposeObservable.notifyObservers(this);
  38804. // Handle size changes.
  38805. var size = this._mainTexture.getSize();
  38806. this.setMainTextureSize();
  38807. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  38808. // Recreate RTT and post processes on size change.
  38809. this.onSizeChangedObservable.notifyObservers(this);
  38810. this.disposeTextureAndPostProcesses();
  38811. this.createTextureAndPostProcesses();
  38812. }
  38813. };
  38814. /**
  38815. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  38816. * @param mesh The mesh to exclude from the highlight layer
  38817. */
  38818. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  38819. var meshExcluded = this._excludedMeshes[mesh.id];
  38820. if (!meshExcluded) {
  38821. this._excludedMeshes[mesh.id] = {
  38822. mesh: mesh,
  38823. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  38824. mesh.getEngine().setStencilBuffer(false);
  38825. }),
  38826. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  38827. mesh.getEngine().setStencilBuffer(true);
  38828. }),
  38829. };
  38830. }
  38831. };
  38832. /**
  38833. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  38834. * @param mesh The mesh to highlight
  38835. */
  38836. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  38837. var meshExcluded = this._excludedMeshes[mesh.id];
  38838. if (meshExcluded) {
  38839. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  38840. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  38841. }
  38842. this._excludedMeshes[mesh.id] = undefined;
  38843. };
  38844. /**
  38845. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  38846. * @param mesh The mesh to highlight
  38847. * @param color The color of the highlight
  38848. * @param glowEmissiveOnly Extract the glow from the emissive texture
  38849. */
  38850. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  38851. var _this = this;
  38852. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  38853. var meshHighlight = this._meshes[mesh.id];
  38854. if (meshHighlight) {
  38855. meshHighlight.color = color;
  38856. }
  38857. else {
  38858. this._meshes[mesh.id] = {
  38859. mesh: mesh,
  38860. color: color,
  38861. // Lambda required for capture due to Observable this context
  38862. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  38863. if (_this._excludedMeshes[mesh.id]) {
  38864. _this.defaultStencilReference(mesh);
  38865. }
  38866. else {
  38867. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  38868. }
  38869. }),
  38870. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  38871. glowEmissiveOnly: glowEmissiveOnly
  38872. };
  38873. }
  38874. this._shouldRender = true;
  38875. };
  38876. /**
  38877. * Remove a mesh from the highlight layer in order to make it stop glowing.
  38878. * @param mesh The mesh to highlight
  38879. */
  38880. HighlightLayer.prototype.removeMesh = function (mesh) {
  38881. var meshHighlight = this._meshes[mesh.id];
  38882. if (meshHighlight) {
  38883. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  38884. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  38885. }
  38886. this._meshes[mesh.id] = undefined;
  38887. this._shouldRender = false;
  38888. for (var meshHighlightToCheck in this._meshes) {
  38889. if (meshHighlightToCheck) {
  38890. this._shouldRender = true;
  38891. break;
  38892. }
  38893. }
  38894. };
  38895. /**
  38896. * Returns true if the layer contains information to display, otherwise false.
  38897. */
  38898. HighlightLayer.prototype.shouldRender = function () {
  38899. return this.isEnabled && this._shouldRender;
  38900. };
  38901. /**
  38902. * Sets the main texture desired size which is the closest power of two
  38903. * of the engine canvas size.
  38904. */
  38905. HighlightLayer.prototype.setMainTextureSize = function () {
  38906. if (this._options.mainTextureFixedSize) {
  38907. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  38908. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  38909. }
  38910. else {
  38911. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  38912. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  38913. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  38914. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  38915. }
  38916. };
  38917. /**
  38918. * Force the stencil to the normal expected value for none glowing parts
  38919. */
  38920. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  38921. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  38922. };
  38923. /**
  38924. * Dispose only the render target textures and post process.
  38925. */
  38926. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  38927. this._blurTexture.dispose();
  38928. this._mainTexture.dispose();
  38929. this._downSamplePostprocess.dispose();
  38930. this._horizontalBlurPostprocess.dispose();
  38931. this._verticalBlurPostprocess.dispose();
  38932. };
  38933. /**
  38934. * Dispose the highlight layer and free resources.
  38935. */
  38936. HighlightLayer.prototype.dispose = function () {
  38937. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38938. if (vertexBuffer) {
  38939. vertexBuffer.dispose();
  38940. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38941. }
  38942. if (this._indexBuffer) {
  38943. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38944. this._indexBuffer = null;
  38945. }
  38946. // Clean textures and post processes
  38947. this.disposeTextureAndPostProcesses();
  38948. // Clean mesh references
  38949. for (var id in this._meshes) {
  38950. var meshHighlight = this._meshes[id];
  38951. if (meshHighlight && meshHighlight.mesh) {
  38952. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  38953. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  38954. }
  38955. }
  38956. this._meshes = null;
  38957. for (var id in this._excludedMeshes) {
  38958. var meshHighlight = this._excludedMeshes[id];
  38959. if (meshHighlight) {
  38960. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  38961. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  38962. }
  38963. }
  38964. this._excludedMeshes = null;
  38965. // Remove from scene
  38966. var index = this._scene.highlightLayers.indexOf(this, 0);
  38967. if (index > -1) {
  38968. this._scene.highlightLayers.splice(index, 1);
  38969. }
  38970. // Callback
  38971. this.onDisposeObservable.notifyObservers(this);
  38972. this.onDisposeObservable.clear();
  38973. this.onBeforeRenderMainTextureObservable.clear();
  38974. this.onBeforeBlurObservable.clear();
  38975. this.onBeforeComposeObservable.clear();
  38976. this.onAfterComposeObservable.clear();
  38977. this.onSizeChangedObservable.clear();
  38978. };
  38979. /**
  38980. * The neutral color used during the preparation of the glow effect.
  38981. * This is black by default as the blend operation is a blend operation.
  38982. */
  38983. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  38984. /**
  38985. * Stencil value used for glowing meshes.
  38986. */
  38987. HighlightLayer.glowingMeshStencilReference = 0x02;
  38988. /**
  38989. * Stencil value used for the other meshes in the scene.
  38990. */
  38991. HighlightLayer.normalMeshStencilReference = 0x01;
  38992. return HighlightLayer;
  38993. }());
  38994. BABYLON.HighlightLayer = HighlightLayer;
  38995. })(BABYLON || (BABYLON = {}));
  38996. //# sourceMappingURL=babylon.highlightlayer.js.map
  38997. var BABYLON;
  38998. (function (BABYLON) {
  38999. var SIMDVector3 = (function () {
  39000. function SIMDVector3() {
  39001. }
  39002. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  39003. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  39004. };
  39005. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  39006. var m = transformation.m;
  39007. var m0 = SIMD.Float32x4.load(m, 0);
  39008. var m1 = SIMD.Float32x4.load(m, 4);
  39009. var m2 = SIMD.Float32x4.load(m, 8);
  39010. var m3 = SIMD.Float32x4.load(m, 12);
  39011. 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));
  39012. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  39013. result.x = SIMD.Float32x4.extractLane(r, 0);
  39014. result.y = SIMD.Float32x4.extractLane(r, 1);
  39015. result.z = SIMD.Float32x4.extractLane(r, 2);
  39016. };
  39017. return SIMDVector3;
  39018. }());
  39019. var SIMDMatrix = (function () {
  39020. function SIMDMatrix() {
  39021. }
  39022. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  39023. var tm = this.m;
  39024. var om = other.m;
  39025. var m0 = SIMD.Float32x4.load(om, 0);
  39026. var m1 = SIMD.Float32x4.load(om, 4);
  39027. var m2 = SIMD.Float32x4.load(om, 8);
  39028. var m3 = SIMD.Float32x4.load(om, 12);
  39029. for (var i = 0; i < 16; i += 4) {
  39030. 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)))));
  39031. }
  39032. return this;
  39033. };
  39034. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  39035. var src = this.m;
  39036. var dest = other.m;
  39037. // Load the 4 rows
  39038. var src0 = SIMD.Float32x4.load(src, 0);
  39039. var src1 = SIMD.Float32x4.load(src, 4);
  39040. var src2 = SIMD.Float32x4.load(src, 8);
  39041. var src3 = SIMD.Float32x4.load(src, 12);
  39042. // Transpose the source matrix. Sort of. Not a true transpose operation
  39043. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  39044. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  39045. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  39046. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  39047. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  39048. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  39049. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  39050. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  39051. // This is a true transposition, but it will lead to an incorrect result
  39052. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  39053. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  39054. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39055. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39056. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  39057. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  39058. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39059. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39060. // ----
  39061. tmp1 = SIMD.Float32x4.mul(row2, row3);
  39062. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39063. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  39064. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  39065. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39066. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  39067. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  39068. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  39069. // ----
  39070. tmp1 = SIMD.Float32x4.mul(row1, row2);
  39071. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39072. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  39073. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  39074. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39075. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  39076. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  39077. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  39078. // ----
  39079. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  39080. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39081. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  39082. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  39083. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  39084. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39085. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  39086. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  39087. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  39088. // ----
  39089. tmp1 = SIMD.Float32x4.mul(row0, row1);
  39090. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39091. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39092. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  39093. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39094. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39095. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  39096. // ----
  39097. tmp1 = SIMD.Float32x4.mul(row0, row3);
  39098. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39099. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  39100. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  39101. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39102. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  39103. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  39104. // ----
  39105. tmp1 = SIMD.Float32x4.mul(row0, row2);
  39106. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39107. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  39108. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  39109. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39110. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  39111. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  39112. // Compute determinant
  39113. var det = SIMD.Float32x4.mul(row0, minor0);
  39114. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  39115. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  39116. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  39117. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  39118. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  39119. // These shuffles aren't necessary if the faulty transposition is done
  39120. // up at the top of this function.
  39121. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  39122. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  39123. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  39124. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  39125. // Compute final values by multiplying with 1/det
  39126. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  39127. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  39128. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  39129. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  39130. return this;
  39131. };
  39132. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  39133. var out = result.m;
  39134. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  39135. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  39136. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  39137. // cc.kmVec3Subtract(f, pCenter, pEye);
  39138. var f = SIMD.Float32x4.sub(center, eye);
  39139. // cc.kmVec3Normalize(f, f);
  39140. var tmp = SIMD.Float32x4.mul(f, f);
  39141. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39142. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39143. // cc.kmVec3Assign(up, pUp);
  39144. // cc.kmVec3Normalize(up, up);
  39145. tmp = SIMD.Float32x4.mul(up, up);
  39146. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39147. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39148. // cc.kmVec3Cross(s, f, up);
  39149. 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)));
  39150. // cc.kmVec3Normalize(s, s);
  39151. tmp = SIMD.Float32x4.mul(s, s);
  39152. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39153. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39154. // cc.kmVec3Cross(u, s, f);
  39155. 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)));
  39156. // cc.kmVec3Normalize(s, s);
  39157. tmp = SIMD.Float32x4.mul(s, s);
  39158. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39159. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39160. var zero = SIMD.Float32x4.splat(0.0);
  39161. s = SIMD.Float32x4.neg(s);
  39162. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  39163. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  39164. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  39165. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  39166. 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);
  39167. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  39168. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  39169. 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)))));
  39170. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  39171. 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)))));
  39172. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  39173. 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)))));
  39174. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  39175. 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)))));
  39176. };
  39177. return SIMDMatrix;
  39178. }());
  39179. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  39180. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  39181. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  39182. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  39183. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  39184. var SIMDHelper = (function () {
  39185. function SIMDHelper() {
  39186. }
  39187. Object.defineProperty(SIMDHelper, "IsEnabled", {
  39188. get: function () {
  39189. return SIMDHelper._isEnabled;
  39190. },
  39191. enumerable: true,
  39192. configurable: true
  39193. });
  39194. SIMDHelper.DisableSIMD = function () {
  39195. // Replace functions
  39196. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  39197. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  39198. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  39199. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  39200. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  39201. SIMDHelper._isEnabled = false;
  39202. };
  39203. SIMDHelper.EnableSIMD = function () {
  39204. if (self.SIMD === undefined) {
  39205. return;
  39206. }
  39207. // check if polyfills needed
  39208. if (!self.Math.fround) {
  39209. self.Math.fround = (function (array) { return function (x) {
  39210. return array[0] = x, array[0];
  39211. }; })(new Float32Array(1));
  39212. }
  39213. if (!self.Math.imul) {
  39214. self.Math.imul = function (a, b) {
  39215. var ah = (a >>> 16) & 0xffff;
  39216. var al = a & 0xffff;
  39217. var bh = (b >>> 16) & 0xffff;
  39218. var bl = b & 0xffff;
  39219. // the shift by 0 fixes the sign on the high part
  39220. // the final |0 converts the unsigned value into a signed value
  39221. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  39222. };
  39223. }
  39224. // Replace functions
  39225. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  39226. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  39227. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  39228. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  39229. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  39230. SIMDHelper._isEnabled = true;
  39231. };
  39232. SIMDHelper._isEnabled = false;
  39233. return SIMDHelper;
  39234. }());
  39235. BABYLON.SIMDHelper = SIMDHelper;
  39236. })(BABYLON || (BABYLON = {}));
  39237. //# sourceMappingURL=babylon.math.SIMD.js.map
  39238. var BABYLON;
  39239. (function (BABYLON) {
  39240. /**
  39241. * This class describe a rectangle that were added to the map.
  39242. * You have access to its coordinates either in pixel or normalized (UV)
  39243. */
  39244. var PackedRect = (function () {
  39245. function PackedRect(root, parent, pos, size) {
  39246. this._pos = pos;
  39247. this._size = size;
  39248. this._root = root;
  39249. this._parent = parent;
  39250. this._contentSize = null;
  39251. this._bottomNode = null;
  39252. this._leftNode = null;
  39253. this._initialSize = null;
  39254. this._rightNode = null;
  39255. }
  39256. Object.defineProperty(PackedRect.prototype, "pos", {
  39257. /**
  39258. * @returns the position of this node into the map
  39259. */
  39260. get: function () {
  39261. return this._pos;
  39262. },
  39263. enumerable: true,
  39264. configurable: true
  39265. });
  39266. Object.defineProperty(PackedRect.prototype, "contentSize", {
  39267. /**
  39268. * @returns the size of the rectangle this node handles
  39269. */
  39270. get: function () {
  39271. return this._contentSize;
  39272. },
  39273. enumerable: true,
  39274. configurable: true
  39275. });
  39276. Object.defineProperty(PackedRect.prototype, "UVs", {
  39277. /**
  39278. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  39279. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  39280. */
  39281. get: function () {
  39282. return this.getUVsForCustomSize(this._root._size);
  39283. },
  39284. enumerable: true,
  39285. configurable: true
  39286. });
  39287. /**
  39288. * 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.
  39289. * This method will return the UVs for this part by given the custom size of what you really use
  39290. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  39291. */
  39292. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  39293. var mainWidth = this._root._size.width;
  39294. var mainHeight = this._root._size.height;
  39295. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  39296. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  39297. var uvs = new Array();
  39298. uvs.push(topLeft);
  39299. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  39300. uvs.push(rightBottom);
  39301. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  39302. return uvs;
  39303. };
  39304. /**
  39305. * Free this rectangle from the map.
  39306. * Call this method when you no longer need the rectangle to be in the map.
  39307. */
  39308. PackedRect.prototype.freeContent = function () {
  39309. if (!this.contentSize) {
  39310. return;
  39311. }
  39312. this._contentSize = null;
  39313. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  39314. this.attemptDefrag();
  39315. };
  39316. Object.defineProperty(PackedRect.prototype, "isUsed", {
  39317. get: function () {
  39318. return this._contentSize != null || this._leftNode != null;
  39319. },
  39320. enumerable: true,
  39321. configurable: true
  39322. });
  39323. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  39324. var node = this.findNode(contentSize);
  39325. // Not enough space...
  39326. if (!node) {
  39327. return null;
  39328. }
  39329. node.splitNode(contentSize);
  39330. return node;
  39331. };
  39332. PackedRect.prototype.findNode = function (size) {
  39333. var resNode = null;
  39334. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  39335. if (this.isUsed) {
  39336. if (this._leftNode) {
  39337. resNode = this._leftNode.findNode(size);
  39338. }
  39339. if (!resNode && this._rightNode) {
  39340. resNode = this._rightNode.findNode(size);
  39341. }
  39342. if (!resNode && this._bottomNode) {
  39343. resNode = this._bottomNode.findNode(size);
  39344. }
  39345. }
  39346. else if (this._initialSize) {
  39347. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  39348. resNode = this;
  39349. }
  39350. else {
  39351. return null;
  39352. }
  39353. }
  39354. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  39355. resNode = this;
  39356. }
  39357. return resNode;
  39358. };
  39359. PackedRect.prototype.splitNode = function (contentSize) {
  39360. // 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)
  39361. if (!this._contentSize && this._initialSize) {
  39362. this._contentSize = contentSize.clone();
  39363. 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));
  39364. return this._leftNode.splitNode(contentSize);
  39365. }
  39366. else {
  39367. this._contentSize = contentSize.clone();
  39368. this._initialSize = contentSize.clone();
  39369. if (contentSize.width !== this._size.width) {
  39370. 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));
  39371. }
  39372. if (contentSize.height !== this._size.height) {
  39373. 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));
  39374. }
  39375. return this;
  39376. }
  39377. };
  39378. PackedRect.prototype.attemptDefrag = function () {
  39379. if (!this.isUsed && this.isRecursiveFree) {
  39380. this.clearNode();
  39381. if (this._parent) {
  39382. this._parent.attemptDefrag();
  39383. }
  39384. }
  39385. };
  39386. PackedRect.prototype.clearNode = function () {
  39387. this._initialSize = null;
  39388. this._rightNode = null;
  39389. this._bottomNode = null;
  39390. };
  39391. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  39392. get: function () {
  39393. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  39394. },
  39395. enumerable: true,
  39396. configurable: true
  39397. });
  39398. PackedRect.prototype.evalFreeSize = function (size) {
  39399. var levelSize = 0;
  39400. if (!this.isUsed) {
  39401. if (this._initialSize) {
  39402. levelSize = this._initialSize.surface;
  39403. }
  39404. else {
  39405. levelSize = this._size.surface;
  39406. }
  39407. }
  39408. if (this._rightNode) {
  39409. levelSize += this._rightNode.evalFreeSize(0);
  39410. }
  39411. if (this._bottomNode) {
  39412. levelSize += this._bottomNode.evalFreeSize(0);
  39413. }
  39414. return levelSize + size;
  39415. };
  39416. return PackedRect;
  39417. }());
  39418. BABYLON.PackedRect = PackedRect;
  39419. /**
  39420. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  39421. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  39422. * 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.
  39423. */
  39424. var RectPackingMap = (function (_super) {
  39425. __extends(RectPackingMap, _super);
  39426. /**
  39427. * Create an instance of the object with a dimension using the given size
  39428. * @param size The dimension of the rectangle that will contain all the sub ones.
  39429. */
  39430. function RectPackingMap(size) {
  39431. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  39432. this._root = this;
  39433. }
  39434. /**
  39435. * Add a rectangle, finding the best location to store it into the map
  39436. * @param size the dimension of the rectangle to store
  39437. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  39438. */
  39439. RectPackingMap.prototype.addRect = function (size) {
  39440. var node = this.findAndSplitNode(size);
  39441. return node;
  39442. };
  39443. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  39444. /**
  39445. * Return the current space free normalized between [0;1]
  39446. * @returns {}
  39447. */
  39448. get: function () {
  39449. var freeSize = 0;
  39450. freeSize = this.evalFreeSize(freeSize);
  39451. return freeSize / (this._size.width * this._size.height);
  39452. },
  39453. enumerable: true,
  39454. configurable: true
  39455. });
  39456. return RectPackingMap;
  39457. }(PackedRect));
  39458. BABYLON.RectPackingMap = RectPackingMap;
  39459. })(BABYLON || (BABYLON = {}));
  39460. //# sourceMappingURL=babylon.rectPackingMap.js.map
  39461. var BABYLON;
  39462. (function (BABYLON) {
  39463. var DynamicFloatArrayElementInfo = (function () {
  39464. function DynamicFloatArrayElementInfo() {
  39465. }
  39466. return DynamicFloatArrayElementInfo;
  39467. }());
  39468. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  39469. /**
  39470. * 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.
  39471. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  39472. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  39473. * 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.
  39474. * 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.
  39475. * 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".
  39476. */
  39477. var DynamicFloatArray = (function () {
  39478. /**
  39479. * Construct an instance of the dynamic float array
  39480. * @param stride size of one element in float (i.e. not bytes!)
  39481. * @param initialElementCount the number of available entries at construction
  39482. */
  39483. function DynamicFloatArray(stride, initialElementCount) {
  39484. this.compareValueOffset = null;
  39485. this.sortingAscending = true;
  39486. this._stride = stride;
  39487. this.buffer = new Float32Array(stride * initialElementCount);
  39488. this._lastUsed = 0;
  39489. this._firstFree = 0;
  39490. this._allEntries = new Array(initialElementCount);
  39491. this._freeEntries = new Array(initialElementCount);
  39492. for (var i = 0; i < initialElementCount; i++) {
  39493. var element = new DynamicFloatArrayElementInfo();
  39494. element.offset = i * stride;
  39495. this._allEntries[i] = element;
  39496. this._freeEntries[initialElementCount - i - 1] = element;
  39497. }
  39498. }
  39499. /**
  39500. * Allocate an element in the array.
  39501. * @return the element info instance that contains the offset into the main buffer of the element's location.
  39502. * Beware, this offset may change when you call pack()
  39503. */
  39504. DynamicFloatArray.prototype.allocElement = function () {
  39505. if (this._freeEntries.length === 0) {
  39506. this._growBuffer();
  39507. }
  39508. var el = this._freeEntries.pop();
  39509. this._lastUsed = Math.max(el.offset, this._lastUsed);
  39510. if (el.offset === this._firstFree) {
  39511. if (this._freeEntries.length > 0) {
  39512. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  39513. }
  39514. else {
  39515. this._firstFree += this._stride;
  39516. }
  39517. }
  39518. return el;
  39519. };
  39520. /**
  39521. * Free the element corresponding to the given element info
  39522. * @param elInfo the element that describe the allocated element
  39523. */
  39524. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  39525. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  39526. this._freeEntries.push(elInfo);
  39527. };
  39528. /**
  39529. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  39530. * 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().
  39531. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  39532. */
  39533. DynamicFloatArray.prototype.pack = function () {
  39534. // no free slot? no need to pack
  39535. if (this._freeEntries.length === 0) {
  39536. return this.buffer;
  39537. }
  39538. // If the buffer is already packed the last used will always be lower than the first free
  39539. // 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.
  39540. if (this._lastUsed < this._firstFree) {
  39541. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  39542. return elementsBuffer_1;
  39543. }
  39544. var s = this._stride;
  39545. // 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
  39546. var lastFree = new DynamicFloatArrayElementInfo();
  39547. lastFree.offset = this.totalElementCount * s;
  39548. this._freeEntries.push(lastFree);
  39549. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  39550. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39551. var firstFreeSlotOffset = sortedFree[0].offset;
  39552. var freeZoneSize = 1;
  39553. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  39554. var prevOffset = sortedFree[0].offset;
  39555. for (var i = 1; i < sortedFree.length; i++) {
  39556. // 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
  39557. if (firstFreeSlotOffset >= occupiedZoneSize) {
  39558. break;
  39559. }
  39560. var curFree = sortedFree[i];
  39561. var curOffset = curFree.offset;
  39562. // Compute the distance between this offset and the previous
  39563. var distance = curOffset - prevOffset;
  39564. // If the distance is the stride size, they are adjacent, it good, move to the next
  39565. if (distance === s) {
  39566. // Free zone is one element bigger
  39567. ++freeZoneSize;
  39568. // as we're about to iterate to the next, the cur becomes the previous...
  39569. prevOffset = curOffset;
  39570. continue;
  39571. }
  39572. // Distance is bigger, which means there's x element between the previous free and this one
  39573. var usedRange = (distance / s) - 1;
  39574. // Two cases the free zone is smaller than the data to move or bigger
  39575. // Copy what can fit in the free zone
  39576. var curMoveOffset = curOffset - s;
  39577. var copyCount = Math.min(freeZoneSize, usedRange);
  39578. for (var j = 0; j < copyCount; j++) {
  39579. var freeI = firstFreeSlotOffset / s;
  39580. var curI = curMoveOffset / s;
  39581. var moveEl = sortedAll[curI];
  39582. this._moveElement(moveEl, firstFreeSlotOffset);
  39583. var replacedEl = sortedAll[freeI];
  39584. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  39585. replacedEl.offset = curMoveOffset;
  39586. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  39587. sortedAll[freeI] = moveEl;
  39588. sortedAll[curI] = replacedEl;
  39589. curMoveOffset -= s;
  39590. firstFreeSlotOffset += s;
  39591. }
  39592. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  39593. if (freeZoneSize <= usedRange) {
  39594. firstFreeSlotOffset = curMoveOffset + s;
  39595. freeZoneSize = 1 + copyCount;
  39596. }
  39597. else {
  39598. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  39599. }
  39600. // as we're about to iterate to the next, the cur becomes the previous...
  39601. prevOffset = curOffset;
  39602. }
  39603. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  39604. this._lastUsed = firstFreeSlotOffset - s;
  39605. this._firstFree = firstFreeSlotOffset;
  39606. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  39607. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  39608. this._allEntries = sortedAll;
  39609. return elementsBuffer;
  39610. };
  39611. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  39612. for (var i = 0; i < this._stride; i++) {
  39613. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  39614. }
  39615. element.offset = destOffset;
  39616. };
  39617. DynamicFloatArray.prototype._growBuffer = function () {
  39618. // Allocate the new buffer with 50% more entries, copy the content of the current one
  39619. var newElCount = Math.floor(this.totalElementCount * 1.5);
  39620. var newBuffer = new Float32Array(newElCount * this._stride);
  39621. newBuffer.set(this.buffer);
  39622. var curCount = this.totalElementCount;
  39623. var addedCount = newElCount - this.totalElementCount;
  39624. for (var i = 0; i < addedCount; i++) {
  39625. var element = new DynamicFloatArrayElementInfo();
  39626. element.offset = (curCount + i) * this.stride;
  39627. this._allEntries.push(element);
  39628. this._freeEntries[addedCount - i - 1] = element;
  39629. }
  39630. this._firstFree = curCount * this.stride;
  39631. this.buffer = newBuffer;
  39632. };
  39633. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  39634. /**
  39635. * Get the total count of entries that can fit in the current buffer
  39636. * @returns the elements count
  39637. */
  39638. get: function () {
  39639. return this._allEntries.length;
  39640. },
  39641. enumerable: true,
  39642. configurable: true
  39643. });
  39644. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  39645. /**
  39646. * Get the count of free entries that can still be allocated without resizing the buffer
  39647. * @returns the free elements count
  39648. */
  39649. get: function () {
  39650. return this._freeEntries.length;
  39651. },
  39652. enumerable: true,
  39653. configurable: true
  39654. });
  39655. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  39656. /**
  39657. * Get the count of allocated elements
  39658. * @returns the allocated elements count
  39659. */
  39660. get: function () {
  39661. return this._allEntries.length - this._freeEntries.length;
  39662. },
  39663. enumerable: true,
  39664. configurable: true
  39665. });
  39666. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  39667. /**
  39668. * Return the size of one element in float
  39669. * @returns the size in float
  39670. */
  39671. get: function () {
  39672. return this._stride;
  39673. },
  39674. enumerable: true,
  39675. configurable: true
  39676. });
  39677. DynamicFloatArray.prototype.sort = function () {
  39678. var _this = this;
  39679. if (!this.compareValueOffset) {
  39680. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  39681. }
  39682. var count = this.usedElementCount;
  39683. // Do we have to (re)create the sort table?
  39684. if (!this._sortTable || this._sortTable.length < count) {
  39685. // 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...
  39686. var newCount = Math.min(this.totalElementCount, count * 2);
  39687. this._sortTable = new Array(newCount);
  39688. }
  39689. if (!this._sortedTable || this._sortedTable.length !== count) {
  39690. this._sortedTable = new Array(count);
  39691. }
  39692. // Because, you know...
  39693. this.pack();
  39694. //let stride = this.stride;
  39695. //for (let i = 0; i < count; i++) {
  39696. // let si = this._sortTable[i];
  39697. // if (!si) {
  39698. // si = new SortInfo();
  39699. // this._sortTable[i] = si;
  39700. // }
  39701. // si.entry = this._allEntries[i];
  39702. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  39703. // si.swapedOffset = null;
  39704. // this._sortedTable[i] = si;
  39705. //}
  39706. var curOffset = 0;
  39707. var stride = this.stride;
  39708. for (var i = 0; i < count; i++, curOffset += stride) {
  39709. var si = this._sortTable[i];
  39710. if (!si) {
  39711. si = new SortInfo();
  39712. this._sortTable[i] = si;
  39713. }
  39714. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  39715. si.offset = curOffset;
  39716. si.swapedOffset = null;
  39717. this._sortedTable[i] = si;
  39718. }
  39719. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  39720. if (this.sortingAscending) {
  39721. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  39722. }
  39723. else {
  39724. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  39725. }
  39726. var swapElements = function (src, dst) {
  39727. for (var i = 0; i < stride; i++) {
  39728. var tps = _this.buffer[dst + i];
  39729. _this.buffer[dst + i] = _this.buffer[src + i];
  39730. _this.buffer[src + i] = tps;
  39731. }
  39732. };
  39733. // 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:
  39734. // 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),
  39735. // and I still want something with a good algorithm complexity.
  39736. // 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,
  39737. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  39738. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  39739. // 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
  39740. // until we find a SortInfo object without a swapedOffset which means we got the right location
  39741. // 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
  39742. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  39743. for (var i = 0; i < count; i++) {
  39744. // Get the element to move
  39745. var sourceSI = this._sortedTable[i];
  39746. var destSI = this._sortTable[i];
  39747. var sourceOff = sourceSI.offset;
  39748. // If the source changed location, find the new one
  39749. if (sourceSI.swapedOffset) {
  39750. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  39751. var curSI = sourceSI;
  39752. while (curSI.swapedOffset) {
  39753. curSI = this._sortTable[curSI.swapedOffset / stride];
  39754. }
  39755. // Finally get the right location
  39756. sourceOff = curSI.offset;
  39757. }
  39758. // Tag the element being replaced with its new location
  39759. destSI.swapedOffset = sourceOff;
  39760. // Swap elements (only if needed)
  39761. if (sourceOff !== destSI.offset) {
  39762. swapElements(sourceOff, destSI.offset);
  39763. }
  39764. // Update the offset in the corresponding DFAE
  39765. //sourceSI.entry.offset = destSI.entry.offset;
  39766. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  39767. }
  39768. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39769. return true;
  39770. };
  39771. return DynamicFloatArray;
  39772. }());
  39773. BABYLON.DynamicFloatArray = DynamicFloatArray;
  39774. var SortInfo = (function () {
  39775. function SortInfo() {
  39776. this.compareData = this.offset = this.swapedOffset = null;
  39777. }
  39778. return SortInfo;
  39779. }());
  39780. })(BABYLON || (BABYLON = {}));
  39781. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  39782. var BABYLON;
  39783. (function (BABYLON) {
  39784. /**
  39785. * This class given information about a given character.
  39786. */
  39787. var CharInfo = (function () {
  39788. function CharInfo() {
  39789. }
  39790. return CharInfo;
  39791. }());
  39792. BABYLON.CharInfo = CharInfo;
  39793. var FontTexture = (function (_super) {
  39794. __extends(FontTexture, _super);
  39795. /**
  39796. * Create a new instance of the FontTexture class
  39797. * @param name the name of the texture
  39798. * @param font the font to use, use the W3C CSS notation
  39799. * @param scene the scene that owns the texture
  39800. * @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
  39801. * @param samplingMode the texture sampling mode
  39802. * @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.
  39803. */
  39804. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  39805. if (maxCharCount === void 0) { maxCharCount = 200; }
  39806. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39807. if (superSample === void 0) { superSample = false; }
  39808. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39809. _super.call(this, null, scene, true, false, samplingMode);
  39810. this._charInfos = {};
  39811. this._curCharCount = 0;
  39812. this._lastUpdateCharCount = -1;
  39813. this._usedCounter = 1;
  39814. this.name = name;
  39815. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39816. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39817. this._sdfScale = 8;
  39818. this._signedDistanceField = signedDistanceField;
  39819. this._superSample = false;
  39820. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  39821. if (superSample || signedDistanceField) {
  39822. var sfont = this.getSuperSampleFont(font);
  39823. if (sfont) {
  39824. this._superSample = true;
  39825. font = sfont;
  39826. }
  39827. }
  39828. // First canvas creation to determine the size of the texture to create
  39829. this._canvas = document.createElement("canvas");
  39830. this._context = this._canvas.getContext("2d");
  39831. this._context.font = font;
  39832. this._context.fillStyle = "white";
  39833. this._context.textBaseline = "top";
  39834. this._cachedFontId = null;
  39835. var res = this.getFontHeight(font);
  39836. this._lineHeightSuper = res.height + 4;
  39837. this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;
  39838. this._offset = res.offset - 1;
  39839. this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  39840. this._yMargin = this._xMargin;
  39841. var maxCharWidth = this._context.measureText("W").width;
  39842. this._spaceWidthSuper = this._context.measureText(" ").width;
  39843. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  39844. // This is an approximate size, but should always be able to fit at least the maxCharCount
  39845. var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;
  39846. var edge = Math.sqrt(totalEstSurface);
  39847. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  39848. // Create the texture that will store the font characters
  39849. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  39850. var textureSize = this.getSize();
  39851. this.hasAlpha = this._signedDistanceField === false;
  39852. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  39853. this._canvas = document.createElement("canvas");
  39854. this._canvas.width = textureSize.width;
  39855. this._canvas.height = textureSize.height;
  39856. this._context = this._canvas.getContext("2d");
  39857. this._context.textBaseline = "top";
  39858. this._context.font = font;
  39859. this._context.fillStyle = "white";
  39860. this._context.imageSmoothingEnabled = false;
  39861. this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  39862. // 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
  39863. // 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)
  39864. // So you can see this context as an intermediate one, because it is.
  39865. if (this._signedDistanceField) {
  39866. var sdfC = document.createElement("canvas");
  39867. var s = this._sdfScale;
  39868. sdfC.width = maxCharWidth * s;
  39869. sdfC.height = this._lineHeightSuper * s;
  39870. var sdfCtx = sdfC.getContext("2d");
  39871. sdfCtx.scale(s, s);
  39872. sdfCtx.textBaseline = "top";
  39873. sdfCtx.font = font;
  39874. sdfCtx.fillStyle = "white";
  39875. sdfCtx.imageSmoothingEnabled = false;
  39876. this._sdfCanvas = sdfC;
  39877. this._sdfContext = sdfCtx;
  39878. }
  39879. this._currentFreePosition = BABYLON.Vector2.Zero();
  39880. // Add the basic ASCII based characters
  39881. for (var i = 0x20; i < 0x7F; i++) {
  39882. var c = String.fromCharCode(i);
  39883. this.getChar(c);
  39884. }
  39885. this.update();
  39886. }
  39887. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  39888. get: function () {
  39889. return this._superSample;
  39890. },
  39891. enumerable: true,
  39892. configurable: true
  39893. });
  39894. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  39895. get: function () {
  39896. return this._signedDistanceField;
  39897. },
  39898. enumerable: true,
  39899. configurable: true
  39900. });
  39901. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  39902. get: function () {
  39903. return this._spaceWidth;
  39904. },
  39905. enumerable: true,
  39906. configurable: true
  39907. });
  39908. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  39909. get: function () {
  39910. return this._lineHeight;
  39911. },
  39912. enumerable: true,
  39913. configurable: true
  39914. });
  39915. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  39916. if (supersample === void 0) { supersample = false; }
  39917. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39918. var s = scene;
  39919. if (!s.__fontTextureCache__) {
  39920. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  39921. }
  39922. var dic = s.__fontTextureCache__;
  39923. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  39924. var ft = dic.get(lfn);
  39925. if (ft) {
  39926. ++ft._usedCounter;
  39927. return ft;
  39928. }
  39929. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  39930. ft._cachedFontId = lfn;
  39931. dic.add(lfn, ft);
  39932. return ft;
  39933. };
  39934. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  39935. if (supersample === void 0) { supersample = false; }
  39936. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39937. var s = scene;
  39938. var dic = s.__fontTextureCache__;
  39939. if (!dic) {
  39940. return;
  39941. }
  39942. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  39943. var font = dic.get(lfn);
  39944. if (--font._usedCounter === 0) {
  39945. dic.remove(lfn);
  39946. font.dispose();
  39947. }
  39948. };
  39949. /**
  39950. * Make sure the given char is present in the font map.
  39951. * @param char the character to get or add
  39952. * @return the CharInfo instance corresponding to the given character
  39953. */
  39954. FontTexture.prototype.getChar = function (char) {
  39955. if (char.length !== 1) {
  39956. return null;
  39957. }
  39958. var info = this._charInfos[char];
  39959. if (info) {
  39960. return info;
  39961. }
  39962. info = new CharInfo();
  39963. var measure = this._context.measureText(char);
  39964. var textureSize = this.getSize();
  39965. // we reached the end of the current line?
  39966. var width = Math.round(measure.width);
  39967. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  39968. this._currentFreePosition.x = 0;
  39969. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  39970. // No more room?
  39971. if (this._currentFreePosition.y > textureSize.height) {
  39972. return this.getChar("!");
  39973. }
  39974. }
  39975. // 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)
  39976. if (this._signedDistanceField) {
  39977. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  39978. this._sdfContext.fillText(char, 0, -this._offset);
  39979. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  39980. var res = this._computeSDFChar(data);
  39981. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  39982. }
  39983. else {
  39984. // Draw the character in the HTML canvas
  39985. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  39986. }
  39987. // Fill the CharInfo object
  39988. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  39989. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  39990. if (this._signedDistanceField) {
  39991. var off = 1 / textureSize.width;
  39992. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  39993. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  39994. }
  39995. info.charWidth = this._superSample ? (width / 2) : width;
  39996. // Add the info structure
  39997. this._charInfos[char] = info;
  39998. this._curCharCount++;
  39999. // Set the next position
  40000. this._currentFreePosition.x += width + this._xMargin;
  40001. return info;
  40002. };
  40003. FontTexture.prototype._computeSDFChar = function (source) {
  40004. var scl = this._sdfScale;
  40005. var sw = source.width;
  40006. var sh = source.height;
  40007. var dw = sw / scl;
  40008. var dh = sh / scl;
  40009. var roffx = 0;
  40010. var roffy = 0;
  40011. // We shouldn't look beyond half of the biggest between width and height
  40012. var radius = scl;
  40013. var br = radius - 1;
  40014. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  40015. var sx = dx * scl;
  40016. var sy = dy * scl;
  40017. // Looking out of the area? return true to make the test going on
  40018. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  40019. return true;
  40020. }
  40021. // Get the pixel we want
  40022. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  40023. var res = (val > 0) === lookVis;
  40024. if (!res) {
  40025. roffx = offX;
  40026. roffy = offY;
  40027. }
  40028. return res;
  40029. };
  40030. var lookupArea = function (dx, dy, lookVis) {
  40031. // 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
  40032. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  40033. lookupSrc(dx, dy, 0, -br, lookVis) &&
  40034. lookupSrc(dx, dy, -br, 0, lookVis) &&
  40035. lookupSrc(dx, dy, br, 0, lookVis)) {
  40036. return 0;
  40037. }
  40038. for (var i = 1; i <= radius; i++) {
  40039. // Quick test N, S, W, E
  40040. 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)) {
  40041. return i * i; // Squared Distance is simple to compute in this case
  40042. }
  40043. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  40044. for (var j = 1; j <= i; j++) {
  40045. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  40046. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  40047. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  40048. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  40049. // We found the nearest texel having and opposite state, store the squared length
  40050. var res_1 = (i * i) + (j * j);
  40051. var count = 1;
  40052. // 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
  40053. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  40054. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  40055. ++count;
  40056. }
  40057. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  40058. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  40059. ++count;
  40060. }
  40061. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  40062. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  40063. ++count;
  40064. }
  40065. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  40066. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  40067. ++count;
  40068. }
  40069. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  40070. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  40071. ++count;
  40072. }
  40073. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  40074. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  40075. ++count;
  40076. }
  40077. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  40078. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  40079. ++count;
  40080. }
  40081. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  40082. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  40083. ++count;
  40084. }
  40085. // Compute the average based on the accumulated distance
  40086. return res_1 / count;
  40087. }
  40088. }
  40089. }
  40090. return 0;
  40091. };
  40092. var tmp = new Array(dw * dh);
  40093. for (var y = 0; y < dh; y++) {
  40094. for (var x = 0; x < dw; x++) {
  40095. var curState = lookupSrc(x, y, 0, 0, true);
  40096. var d = lookupArea(x, y, curState);
  40097. if (d === 0) {
  40098. d = radius * radius * 2;
  40099. }
  40100. tmp[(y * dw) + x] = curState ? d : -d;
  40101. }
  40102. }
  40103. var res = this._context.createImageData(dw, dh);
  40104. var size = dw * dh;
  40105. for (var j = 0; j < size; j++) {
  40106. var d = tmp[j];
  40107. var sign = (d < 0) ? -1 : 1;
  40108. d = Math.sqrt(Math.abs(d)) * sign;
  40109. d *= 127.5 / radius;
  40110. d += 127.5;
  40111. if (d < 0) {
  40112. d = 0;
  40113. }
  40114. else if (d > 255) {
  40115. d = 255;
  40116. }
  40117. d += 0.5;
  40118. res.data[j * 4 + 0] = d;
  40119. res.data[j * 4 + 1] = d;
  40120. res.data[j * 4 + 2] = d;
  40121. res.data[j * 4 + 3] = 255;
  40122. }
  40123. return res;
  40124. };
  40125. FontTexture.prototype.measureText = function (text, tabulationSize) {
  40126. if (tabulationSize === void 0) { tabulationSize = 4; }
  40127. var maxWidth = 0;
  40128. var curWidth = 0;
  40129. var lineCount = 1;
  40130. var charxpos = 0;
  40131. // Parse each char of the string
  40132. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  40133. var char = text_1[_i];
  40134. // Next line feed?
  40135. if (char === "\n") {
  40136. maxWidth = Math.max(maxWidth, curWidth);
  40137. charxpos = 0;
  40138. curWidth = 0;
  40139. ++lineCount;
  40140. continue;
  40141. }
  40142. // Tabulation ?
  40143. if (char === "\t") {
  40144. var nextPos = charxpos + tabulationSize;
  40145. nextPos = nextPos - (nextPos % tabulationSize);
  40146. curWidth += (nextPos - charxpos) * this.spaceWidth;
  40147. charxpos = nextPos;
  40148. continue;
  40149. }
  40150. if (char < " ") {
  40151. continue;
  40152. }
  40153. curWidth += this.getChar(char).charWidth;
  40154. ++charxpos;
  40155. }
  40156. maxWidth = Math.max(maxWidth, curWidth);
  40157. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  40158. };
  40159. FontTexture.prototype.getSuperSampleFont = function (font) {
  40160. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  40161. 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*$/;
  40162. var res = font.toLocaleLowerCase().match(regex);
  40163. if (res == null) {
  40164. return null;
  40165. }
  40166. var size = parseInt(res[4]);
  40167. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  40168. var newFont = "";
  40169. for (var j = 1; j < res.length; j++) {
  40170. if (res[j] != null) {
  40171. newFont += res[j] + " ";
  40172. }
  40173. }
  40174. return newFont;
  40175. };
  40176. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  40177. FontTexture.prototype.getFontHeight = function (font) {
  40178. var fontDraw = document.createElement("canvas");
  40179. var ctx = fontDraw.getContext('2d');
  40180. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  40181. ctx.textBaseline = 'top';
  40182. ctx.fillStyle = 'white';
  40183. ctx.font = font;
  40184. ctx.fillText('jH|', 0, 0);
  40185. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  40186. var start = -1;
  40187. var end = -1;
  40188. for (var row = 0; row < fontDraw.height; row++) {
  40189. for (var column = 0; column < fontDraw.width; column++) {
  40190. var index = (row * fontDraw.width + column) * 4;
  40191. if (pixels[index] === 0) {
  40192. if (column === fontDraw.width - 1 && start !== -1) {
  40193. end = row;
  40194. row = fontDraw.height;
  40195. break;
  40196. }
  40197. continue;
  40198. }
  40199. else {
  40200. if (start === -1) {
  40201. start = row;
  40202. }
  40203. break;
  40204. }
  40205. }
  40206. }
  40207. return { height: (end - start) + 1, offset: start - 1 };
  40208. };
  40209. Object.defineProperty(FontTexture.prototype, "canRescale", {
  40210. get: function () {
  40211. return false;
  40212. },
  40213. enumerable: true,
  40214. configurable: true
  40215. });
  40216. FontTexture.prototype.getContext = function () {
  40217. return this._context;
  40218. };
  40219. /**
  40220. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  40221. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  40222. */
  40223. FontTexture.prototype.update = function () {
  40224. // Update only if there's new char added since the previous update
  40225. if (this._lastUpdateCharCount < this._curCharCount) {
  40226. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  40227. this._lastUpdateCharCount = this._curCharCount;
  40228. }
  40229. };
  40230. // cloning should be prohibited, there's no point to duplicate this texture at all
  40231. FontTexture.prototype.clone = function () {
  40232. return null;
  40233. };
  40234. /**
  40235. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  40236. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  40237. */
  40238. FontTexture.prototype.incCachedFontTextureCounter = function () {
  40239. ++this._usedCounter;
  40240. };
  40241. /**
  40242. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  40243. */
  40244. FontTexture.prototype.decCachedFontTextureCounter = function () {
  40245. var s = this.getScene();
  40246. var dic = s.__fontTextureCache__;
  40247. if (!dic) {
  40248. return;
  40249. }
  40250. if (--this._usedCounter === 0) {
  40251. dic.remove(this._cachedFontId);
  40252. this.dispose();
  40253. }
  40254. };
  40255. return FontTexture;
  40256. }(BABYLON.Texture));
  40257. BABYLON.FontTexture = FontTexture;
  40258. })(BABYLON || (BABYLON = {}));
  40259. //# sourceMappingURL=babylon.fontTexture.js.map
  40260. var BABYLON;
  40261. (function (BABYLON) {
  40262. var MapTexture = (function (_super) {
  40263. __extends(MapTexture, _super);
  40264. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40266. if (useMipMap === void 0) { useMipMap = false; }
  40267. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  40268. this.name = name;
  40269. this._size = size;
  40270. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40271. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40272. // Create the rectPackMap that will allocate portion of the texture
  40273. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40274. // Create the texture that will store the content
  40275. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40276. }
  40277. /**
  40278. * Allocate a rectangle of a given size in the texture map
  40279. * @param size the size of the rectangle to allocation
  40280. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40281. */
  40282. MapTexture.prototype.allocateRect = function (size) {
  40283. return this._rectPackingMap.addRect(size);
  40284. };
  40285. /**
  40286. * Free a given rectangle from the texture map
  40287. * @param rectInfo the instance corresponding to the rect to free.
  40288. */
  40289. MapTexture.prototype.freeRect = function (rectInfo) {
  40290. if (rectInfo) {
  40291. rectInfo.freeContent();
  40292. }
  40293. };
  40294. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40295. /**
  40296. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40297. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40298. * @returns {}
  40299. */
  40300. get: function () {
  40301. return this._rectPackingMap.freeSpace;
  40302. },
  40303. enumerable: true,
  40304. configurable: true
  40305. });
  40306. /**
  40307. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40308. * 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.
  40309. * Don't forget to call unbindTexture when you're done rendering
  40310. * @param rect the zone to render to
  40311. * @param clear true to clear the portion's color/depth data
  40312. */
  40313. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40314. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40315. };
  40316. /**
  40317. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40318. * 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.
  40319. * Don't forget to call unbindTexture when you're done rendering
  40320. * @param pos the position into the texture
  40321. * @param size the portion to fit the clip space to
  40322. * @param clear true to clear the portion's color/depth data
  40323. */
  40324. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40325. var engine = this.getScene().getEngine();
  40326. engine.bindFramebuffer(this._texture);
  40327. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40328. if (clear) {
  40329. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40330. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40331. }
  40332. };
  40333. /**
  40334. * Unbind the texture map from the rendering engine.
  40335. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40336. * @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.
  40337. */
  40338. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40339. // Dump ?
  40340. if (dumpForDebug) {
  40341. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40342. }
  40343. var engine = this.getScene().getEngine();
  40344. if (this._replacedViewport) {
  40345. engine.setViewport(this._replacedViewport);
  40346. this._replacedViewport = null;
  40347. }
  40348. engine.unBindFramebuffer(this._texture);
  40349. };
  40350. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40351. get: function () {
  40352. return false;
  40353. },
  40354. enumerable: true,
  40355. configurable: true
  40356. });
  40357. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40358. // Anyway, there's not much point to use this method for this kind of texture I guess
  40359. MapTexture.prototype.clone = function () {
  40360. return null;
  40361. };
  40362. return MapTexture;
  40363. }(BABYLON.Texture));
  40364. BABYLON.MapTexture = MapTexture;
  40365. })(BABYLON || (BABYLON = {}));
  40366. //# sourceMappingURL=babylon.mapTexture.js.map
  40367. var BABYLON;
  40368. (function (BABYLON) {
  40369. var ShaderMaterial = (function (_super) {
  40370. __extends(ShaderMaterial, _super);
  40371. function ShaderMaterial(name, scene, shaderPath, options) {
  40372. _super.call(this, name, scene);
  40373. this._textures = {};
  40374. this._textureArrays = {};
  40375. this._floats = {};
  40376. this._floatsArrays = {};
  40377. this._colors3 = {};
  40378. this._colors4 = {};
  40379. this._vectors2 = {};
  40380. this._vectors3 = {};
  40381. this._vectors4 = {};
  40382. this._matrices = {};
  40383. this._matrices3x3 = {};
  40384. this._matrices2x2 = {};
  40385. this._vectors3Arrays = {};
  40386. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40387. this._shaderPath = shaderPath;
  40388. options.needAlphaBlending = options.needAlphaBlending || false;
  40389. options.needAlphaTesting = options.needAlphaTesting || false;
  40390. options.attributes = options.attributes || ["position", "normal", "uv"];
  40391. options.uniforms = options.uniforms || ["worldViewProjection"];
  40392. options.samplers = options.samplers || [];
  40393. options.defines = options.defines || [];
  40394. this._options = options;
  40395. }
  40396. ShaderMaterial.prototype.needAlphaBlending = function () {
  40397. return this._options.needAlphaBlending;
  40398. };
  40399. ShaderMaterial.prototype.needAlphaTesting = function () {
  40400. return this._options.needAlphaTesting;
  40401. };
  40402. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40403. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40404. this._options.uniforms.push(uniformName);
  40405. }
  40406. };
  40407. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40408. if (this._options.samplers.indexOf(name) === -1) {
  40409. this._options.samplers.push(name);
  40410. }
  40411. this._textures[name] = texture;
  40412. return this;
  40413. };
  40414. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40415. if (this._options.samplers.indexOf(name) === -1) {
  40416. this._options.samplers.push(name);
  40417. }
  40418. this._checkUniform(name);
  40419. this._textureArrays[name] = textures;
  40420. return this;
  40421. };
  40422. ShaderMaterial.prototype.setFloat = function (name, value) {
  40423. this._checkUniform(name);
  40424. this._floats[name] = value;
  40425. return this;
  40426. };
  40427. ShaderMaterial.prototype.setFloats = function (name, value) {
  40428. this._checkUniform(name);
  40429. this._floatsArrays[name] = value;
  40430. return this;
  40431. };
  40432. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40433. this._checkUniform(name);
  40434. this._colors3[name] = value;
  40435. return this;
  40436. };
  40437. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40438. this._checkUniform(name);
  40439. this._colors4[name] = value;
  40440. return this;
  40441. };
  40442. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40443. this._checkUniform(name);
  40444. this._vectors2[name] = value;
  40445. return this;
  40446. };
  40447. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40448. this._checkUniform(name);
  40449. this._vectors3[name] = value;
  40450. return this;
  40451. };
  40452. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40453. this._checkUniform(name);
  40454. this._vectors4[name] = value;
  40455. return this;
  40456. };
  40457. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40458. this._checkUniform(name);
  40459. this._matrices[name] = value;
  40460. return this;
  40461. };
  40462. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40463. this._checkUniform(name);
  40464. this._matrices3x3[name] = value;
  40465. return this;
  40466. };
  40467. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40468. this._checkUniform(name);
  40469. this._matrices2x2[name] = value;
  40470. return this;
  40471. };
  40472. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40473. this._checkUniform(name);
  40474. this._vectors3Arrays[name] = value;
  40475. return this;
  40476. };
  40477. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40478. if (!mesh) {
  40479. return true;
  40480. }
  40481. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40482. return false;
  40483. }
  40484. return false;
  40485. };
  40486. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40487. var scene = this.getScene();
  40488. var engine = scene.getEngine();
  40489. if (!this.checkReadyOnEveryCall) {
  40490. if (this._renderId === scene.getRenderId()) {
  40491. if (this._checkCache(scene, mesh, useInstances)) {
  40492. return true;
  40493. }
  40494. }
  40495. }
  40496. // Instances
  40497. var defines = [];
  40498. var fallbacks = new BABYLON.EffectFallbacks();
  40499. if (useInstances) {
  40500. defines.push("#define INSTANCES");
  40501. }
  40502. for (var index = 0; index < this._options.defines.length; index++) {
  40503. defines.push(this._options.defines[index]);
  40504. }
  40505. // Bones
  40506. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40507. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40508. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40509. fallbacks.addCPUSkinningFallback(0, mesh);
  40510. }
  40511. // Alpha test
  40512. if (engine.getAlphaTesting()) {
  40513. defines.push("#define ALPHATEST");
  40514. }
  40515. var previousEffect = this._effect;
  40516. var join = defines.join("\n");
  40517. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  40518. if (!this._effect.isReady()) {
  40519. return false;
  40520. }
  40521. if (previousEffect !== this._effect) {
  40522. scene.resetCachedMaterial();
  40523. }
  40524. this._renderId = scene.getRenderId();
  40525. return true;
  40526. };
  40527. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40528. var scene = this.getScene();
  40529. if (this._options.uniforms.indexOf("world") !== -1) {
  40530. this._effect.setMatrix("world", world);
  40531. }
  40532. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40533. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40534. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40535. }
  40536. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40537. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40538. }
  40539. };
  40540. ShaderMaterial.prototype.bind = function (world, mesh) {
  40541. // Std values
  40542. this.bindOnlyWorldMatrix(world);
  40543. if (this.getScene().getCachedMaterial() !== this) {
  40544. if (this._options.uniforms.indexOf("view") !== -1) {
  40545. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40546. }
  40547. if (this._options.uniforms.indexOf("projection") !== -1) {
  40548. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40549. }
  40550. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40551. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40552. }
  40553. // Bones
  40554. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40555. var name;
  40556. // Texture
  40557. for (name in this._textures) {
  40558. this._effect.setTexture(name, this._textures[name]);
  40559. }
  40560. // Texture arrays
  40561. for (name in this._textureArrays) {
  40562. this._effect.setTextureArray(name, this._textureArrays[name]);
  40563. }
  40564. // Float
  40565. for (name in this._floats) {
  40566. this._effect.setFloat(name, this._floats[name]);
  40567. }
  40568. // Float s
  40569. for (name in this._floatsArrays) {
  40570. this._effect.setArray(name, this._floatsArrays[name]);
  40571. }
  40572. // Color3
  40573. for (name in this._colors3) {
  40574. this._effect.setColor3(name, this._colors3[name]);
  40575. }
  40576. // Color4
  40577. for (name in this._colors4) {
  40578. var color = this._colors4[name];
  40579. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40580. }
  40581. // Vector2
  40582. for (name in this._vectors2) {
  40583. this._effect.setVector2(name, this._vectors2[name]);
  40584. }
  40585. // Vector3
  40586. for (name in this._vectors3) {
  40587. this._effect.setVector3(name, this._vectors3[name]);
  40588. }
  40589. // Vector4
  40590. for (name in this._vectors4) {
  40591. this._effect.setVector4(name, this._vectors4[name]);
  40592. }
  40593. // Matrix
  40594. for (name in this._matrices) {
  40595. this._effect.setMatrix(name, this._matrices[name]);
  40596. }
  40597. // Matrix 3x3
  40598. for (name in this._matrices3x3) {
  40599. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40600. }
  40601. // Matrix 2x2
  40602. for (name in this._matrices2x2) {
  40603. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40604. }
  40605. // Vector3Array
  40606. for (name in this._vectors3Arrays) {
  40607. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40608. }
  40609. }
  40610. _super.prototype.bind.call(this, world, mesh);
  40611. };
  40612. ShaderMaterial.prototype.clone = function (name) {
  40613. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40614. return newShaderMaterial;
  40615. };
  40616. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40617. if (forceDisposeTextures) {
  40618. var name;
  40619. for (name in this._textures) {
  40620. this._textures[name].dispose();
  40621. }
  40622. for (name in this._textureArrays) {
  40623. var array = this._textureArrays[name];
  40624. for (var index = 0; index < array.length; index++) {
  40625. array[index].dispose();
  40626. }
  40627. }
  40628. }
  40629. this._textures = {};
  40630. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40631. };
  40632. ShaderMaterial.prototype.serialize = function () {
  40633. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40634. serializationObject.customType = "BABYLON.ShaderMaterial";
  40635. serializationObject.options = this._options;
  40636. serializationObject.shaderPath = this._shaderPath;
  40637. var name;
  40638. // Texture
  40639. serializationObject.textures = {};
  40640. for (name in this._textures) {
  40641. serializationObject.textures[name] = this._textures[name].serialize();
  40642. }
  40643. // Texture arrays
  40644. serializationObject.textureArrays = {};
  40645. for (name in this._textureArrays) {
  40646. serializationObject.textureArrays[name] = [];
  40647. var array = this._textureArrays[name];
  40648. for (var index = 0; index < array.length; index++) {
  40649. serializationObject.textureArrays[name].push(array[index].serialize());
  40650. }
  40651. }
  40652. // Float
  40653. serializationObject.floats = {};
  40654. for (name in this._floats) {
  40655. serializationObject.floats[name] = this._floats[name];
  40656. }
  40657. // Float s
  40658. serializationObject.floatArrays = {};
  40659. for (name in this._floatsArrays) {
  40660. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40661. }
  40662. // Color3
  40663. serializationObject.colors3 = {};
  40664. for (name in this._colors3) {
  40665. serializationObject.colors3[name] = this._colors3[name].asArray();
  40666. }
  40667. // Color4
  40668. serializationObject.colors4 = {};
  40669. for (name in this._colors4) {
  40670. serializationObject.colors4[name] = this._colors4[name].asArray();
  40671. }
  40672. // Vector2
  40673. serializationObject.vectors2 = {};
  40674. for (name in this._vectors2) {
  40675. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40676. }
  40677. // Vector3
  40678. serializationObject.vectors3 = {};
  40679. for (name in this._vectors3) {
  40680. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40681. }
  40682. // Vector4
  40683. serializationObject.vectors4 = {};
  40684. for (name in this._vectors4) {
  40685. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40686. }
  40687. // Matrix
  40688. serializationObject.matrices = {};
  40689. for (name in this._matrices) {
  40690. serializationObject.matrices[name] = this._matrices[name].asArray();
  40691. }
  40692. // Matrix 3x3
  40693. serializationObject.matrices3x3 = {};
  40694. for (name in this._matrices3x3) {
  40695. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40696. }
  40697. // Matrix 2x2
  40698. serializationObject.matrices2x2 = {};
  40699. for (name in this._matrices2x2) {
  40700. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40701. }
  40702. // Vector3Array
  40703. serializationObject.vectors3Arrays = {};
  40704. for (name in this._vectors3Arrays) {
  40705. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40706. }
  40707. return serializationObject;
  40708. };
  40709. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40710. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40711. var name;
  40712. // Texture
  40713. for (name in source.textures) {
  40714. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40715. }
  40716. // Texture arrays
  40717. for (name in source.textureArrays) {
  40718. var array = source.textureArrays[name];
  40719. var textureArray = new Array();
  40720. for (var index = 0; index < array.length; index++) {
  40721. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40722. }
  40723. material.setTextureArray(name, textureArray);
  40724. }
  40725. // Float
  40726. for (name in source.floats) {
  40727. material.setFloat(name, source.floats[name]);
  40728. }
  40729. // Float s
  40730. for (name in source.floatsArrays) {
  40731. material.setFloats(name, source.floatsArrays[name]);
  40732. }
  40733. // Color3
  40734. for (name in source.colors3) {
  40735. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40736. }
  40737. // Color4
  40738. for (name in source.colors4) {
  40739. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40740. }
  40741. // Vector2
  40742. for (name in source.vectors2) {
  40743. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40744. }
  40745. // Vector3
  40746. for (name in source.vectors3) {
  40747. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40748. }
  40749. // Vector4
  40750. for (name in source.vectors4) {
  40751. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40752. }
  40753. // Matrix
  40754. for (name in source.matrices) {
  40755. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40756. }
  40757. // Matrix 3x3
  40758. for (name in source.matrices3x3) {
  40759. material.setMatrix3x3(name, source.matrices3x3[name]);
  40760. }
  40761. // Matrix 2x2
  40762. for (name in source.matrices2x2) {
  40763. material.setMatrix2x2(name, source.matrices2x2[name]);
  40764. }
  40765. // Vector3Array
  40766. for (name in source.vectors3Arrays) {
  40767. material.setArray3(name, source.vectors3Arrays[name]);
  40768. }
  40769. return material;
  40770. };
  40771. return ShaderMaterial;
  40772. }(BABYLON.Material));
  40773. BABYLON.ShaderMaterial = ShaderMaterial;
  40774. })(BABYLON || (BABYLON = {}));
  40775. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40776. var BABYLON;
  40777. (function (BABYLON) {
  40778. var Internals;
  40779. (function (Internals) {
  40780. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  40781. // All values and structures referenced from:
  40782. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  40783. var DDS_MAGIC = 0x20534444;
  40784. 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;
  40785. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  40786. 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;
  40787. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  40788. function FourCCToInt32(value) {
  40789. return value.charCodeAt(0) +
  40790. (value.charCodeAt(1) << 8) +
  40791. (value.charCodeAt(2) << 16) +
  40792. (value.charCodeAt(3) << 24);
  40793. }
  40794. function Int32ToFourCC(value) {
  40795. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  40796. }
  40797. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  40798. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  40799. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  40800. var headerLengthInt = 31; // The header length in 32 bit ints
  40801. // Offsets into the header array
  40802. var off_magic = 0;
  40803. var off_size = 1;
  40804. var off_flags = 2;
  40805. var off_height = 3;
  40806. var off_width = 4;
  40807. var off_mipmapCount = 7;
  40808. var off_pfFlags = 20;
  40809. var off_pfFourCC = 21;
  40810. var off_RGBbpp = 22;
  40811. var off_RMask = 23;
  40812. var off_GMask = 24;
  40813. var off_BMask = 25;
  40814. var off_AMask = 26;
  40815. var off_caps1 = 27;
  40816. var off_caps2 = 28;
  40817. ;
  40818. var DDSTools = (function () {
  40819. function DDSTools() {
  40820. }
  40821. DDSTools.GetDDSInfo = function (arrayBuffer) {
  40822. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  40823. var mipmapCount = 1;
  40824. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  40825. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40826. }
  40827. return {
  40828. width: header[off_width],
  40829. height: header[off_height],
  40830. mipmapCount: mipmapCount,
  40831. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  40832. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  40833. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  40834. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  40835. };
  40836. };
  40837. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40838. var byteArray = new Uint8Array(dataLength);
  40839. var srcData = new Uint8Array(arrayBuffer);
  40840. var index = 0;
  40841. for (var y = height - 1; y >= 0; y--) {
  40842. for (var x = 0; x < width; x++) {
  40843. var srcPos = dataOffset + (x + y * width) * 4;
  40844. byteArray[index + 2] = srcData[srcPos];
  40845. byteArray[index + 1] = srcData[srcPos + 1];
  40846. byteArray[index] = srcData[srcPos + 2];
  40847. byteArray[index + 3] = srcData[srcPos + 3];
  40848. index += 4;
  40849. }
  40850. }
  40851. return byteArray;
  40852. };
  40853. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40854. var byteArray = new Uint8Array(dataLength);
  40855. var srcData = new Uint8Array(arrayBuffer);
  40856. var index = 0;
  40857. for (var y = height - 1; y >= 0; y--) {
  40858. for (var x = 0; x < width; x++) {
  40859. var srcPos = dataOffset + (x + y * width) * 3;
  40860. byteArray[index + 2] = srcData[srcPos];
  40861. byteArray[index + 1] = srcData[srcPos + 1];
  40862. byteArray[index] = srcData[srcPos + 2];
  40863. index += 3;
  40864. }
  40865. }
  40866. return byteArray;
  40867. };
  40868. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40869. var byteArray = new Uint8Array(dataLength);
  40870. var srcData = new Uint8Array(arrayBuffer);
  40871. var index = 0;
  40872. for (var y = height - 1; y >= 0; y--) {
  40873. for (var x = 0; x < width; x++) {
  40874. var srcPos = dataOffset + (x + y * width);
  40875. byteArray[index] = srcData[srcPos];
  40876. index++;
  40877. }
  40878. }
  40879. return byteArray;
  40880. };
  40881. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  40882. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  40883. if (header[off_magic] != DDS_MAGIC) {
  40884. BABYLON.Tools.Error("Invalid magic number in DDS header");
  40885. return;
  40886. }
  40887. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  40888. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  40889. return;
  40890. }
  40891. if (info.isFourCC) {
  40892. fourCC = header[off_pfFourCC];
  40893. switch (fourCC) {
  40894. case FOURCC_DXT1:
  40895. blockBytes = 8;
  40896. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40897. break;
  40898. case FOURCC_DXT3:
  40899. blockBytes = 16;
  40900. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40901. break;
  40902. case FOURCC_DXT5:
  40903. blockBytes = 16;
  40904. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40905. break;
  40906. default:
  40907. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  40908. return;
  40909. }
  40910. }
  40911. mipmapCount = 1;
  40912. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  40913. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40914. }
  40915. var bpp = header[off_RGBbpp];
  40916. for (var face = 0; face < faces; face++) {
  40917. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  40918. width = header[off_width];
  40919. height = header[off_height];
  40920. dataOffset = header[off_size] + 4;
  40921. for (i = 0; i < mipmapCount; ++i) {
  40922. if (info.isRGB) {
  40923. if (bpp === 24) {
  40924. dataLength = width * height * 3;
  40925. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40926. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  40927. }
  40928. else {
  40929. dataLength = width * height * 4;
  40930. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40931. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  40932. }
  40933. }
  40934. else if (info.isLuminance) {
  40935. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  40936. var unpaddedRowSize = width;
  40937. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  40938. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  40939. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40940. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  40941. }
  40942. else {
  40943. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  40944. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  40945. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  40946. }
  40947. dataOffset += dataLength;
  40948. width *= 0.5;
  40949. height *= 0.5;
  40950. width = Math.max(1.0, width);
  40951. height = Math.max(1.0, height);
  40952. }
  40953. }
  40954. };
  40955. return DDSTools;
  40956. }());
  40957. Internals.DDSTools = DDSTools;
  40958. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40959. })(BABYLON || (BABYLON = {}));
  40960. //# sourceMappingURL=babylon.tools.dds.js.map
  40961. var BABYLON;
  40962. (function (BABYLON) {
  40963. var CannonJSPlugin = (function () {
  40964. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  40965. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  40966. if (iterations === void 0) { iterations = 10; }
  40967. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  40968. this.name = "CannonJSPlugin";
  40969. this._physicsMaterials = [];
  40970. this._fixedTimeStep = 1 / 60;
  40971. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  40972. this._currentCollisionGroup = 2;
  40973. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  40974. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  40975. this._tmpPosition = BABYLON.Vector3.Zero();
  40976. this._tmpQuaternion = new BABYLON.Quaternion();
  40977. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  40978. this._tmpDeltaRotation = new BABYLON.Quaternion();
  40979. this._tmpUnityRotation = new BABYLON.Quaternion();
  40980. if (!this.isSupported()) {
  40981. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  40982. return;
  40983. }
  40984. this.world = new CANNON.World();
  40985. this.world.broadphase = new CANNON.NaiveBroadphase();
  40986. this.world.solver.iterations = iterations;
  40987. }
  40988. CannonJSPlugin.prototype.setGravity = function (gravity) {
  40989. this.world.gravity.copy(gravity);
  40990. };
  40991. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  40992. this._fixedTimeStep = timeStep;
  40993. };
  40994. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  40995. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  40996. };
  40997. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  40998. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  40999. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41000. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41001. };
  41002. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41003. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41004. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41005. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41006. };
  41007. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41008. //parent-child relationship. Does this impostor has a parent impostor?
  41009. if (impostor.parent) {
  41010. if (impostor.physicsBody) {
  41011. this.removePhysicsBody(impostor);
  41012. //TODO is that needed?
  41013. impostor.forceUpdate();
  41014. }
  41015. return;
  41016. }
  41017. //should a new body be created for this impostor?
  41018. if (impostor.isBodyInitRequired()) {
  41019. var shape = this._createShape(impostor);
  41020. //unregister events, if body is being changed
  41021. var oldBody = impostor.physicsBody;
  41022. if (oldBody) {
  41023. this.removePhysicsBody(impostor);
  41024. }
  41025. //create the body and material
  41026. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41027. var bodyCreationObject = {
  41028. mass: impostor.getParam("mass"),
  41029. material: material
  41030. };
  41031. // A simple extend, in case native options were used.
  41032. var nativeOptions = impostor.getParam("nativeOptions");
  41033. for (var key in nativeOptions) {
  41034. if (nativeOptions.hasOwnProperty(key)) {
  41035. bodyCreationObject[key] = nativeOptions[key];
  41036. }
  41037. }
  41038. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41039. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41040. this.world.addEventListener("preStep", impostor.beforeStep);
  41041. this.world.addEventListener("postStep", impostor.afterStep);
  41042. impostor.physicsBody.addShape(shape);
  41043. this.world.add(impostor.physicsBody);
  41044. //try to keep the body moving in the right direction by taking old properties.
  41045. //Should be tested!
  41046. if (oldBody) {
  41047. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41048. impostor.physicsBody[param].copy(oldBody[param]);
  41049. });
  41050. }
  41051. this._processChildMeshes(impostor);
  41052. }
  41053. //now update the body's transformation
  41054. this._updatePhysicsBodyTransformation(impostor);
  41055. };
  41056. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41057. var _this = this;
  41058. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41059. if (meshChildren.length) {
  41060. var processMesh = function (localPosition, mesh) {
  41061. var childImpostor = mesh.getPhysicsImpostor();
  41062. if (childImpostor) {
  41063. var parent = childImpostor.parent;
  41064. if (parent !== mainImpostor) {
  41065. var localPosition = mesh.position;
  41066. if (childImpostor.physicsBody) {
  41067. _this.removePhysicsBody(childImpostor);
  41068. childImpostor.physicsBody = null;
  41069. }
  41070. childImpostor.parent = mainImpostor;
  41071. childImpostor.resetUpdateFlags();
  41072. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41073. //Add the mass of the children.
  41074. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41075. }
  41076. }
  41077. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41078. };
  41079. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41080. }
  41081. };
  41082. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41083. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41084. this.world.removeEventListener("preStep", impostor.beforeStep);
  41085. this.world.removeEventListener("postStep", impostor.afterStep);
  41086. this.world.remove(impostor.physicsBody);
  41087. };
  41088. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41089. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41090. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41091. if (!mainBody || !connectedBody) {
  41092. return;
  41093. }
  41094. var constraint;
  41095. var jointData = impostorJoint.joint.jointData;
  41096. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41097. var constraintData = {
  41098. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41099. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41100. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41101. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41102. maxForce: jointData.nativeParams.maxForce,
  41103. collideConnected: !!jointData.collision
  41104. };
  41105. //Not needed, Cannon has a collideConnected flag
  41106. /*if (!jointData.collision) {
  41107. //add 1st body to a collision group of its own, if it is not in 1
  41108. if (mainBody.collisionFilterGroup === 1) {
  41109. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  41110. this._currentCollisionGroup <<= 1;
  41111. }
  41112. if (connectedBody.collisionFilterGroup === 1) {
  41113. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  41114. this._currentCollisionGroup <<= 1;
  41115. }
  41116. //add their mask to the collisionFilterMask of each other:
  41117. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  41118. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  41119. }*/
  41120. switch (impostorJoint.joint.type) {
  41121. case BABYLON.PhysicsJoint.HingeJoint:
  41122. case BABYLON.PhysicsJoint.Hinge2Joint:
  41123. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41124. break;
  41125. case BABYLON.PhysicsJoint.DistanceJoint:
  41126. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41127. break;
  41128. case BABYLON.PhysicsJoint.SpringJoint:
  41129. var springData = jointData;
  41130. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41131. restLength: springData.length,
  41132. stiffness: springData.stiffness,
  41133. damping: springData.damping,
  41134. localAnchorA: constraintData.pivotA,
  41135. localAnchorB: constraintData.pivotB
  41136. });
  41137. break;
  41138. case BABYLON.PhysicsJoint.LockJoint:
  41139. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41140. break;
  41141. case BABYLON.PhysicsJoint.PointToPointJoint:
  41142. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41143. default:
  41144. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41145. break;
  41146. }
  41147. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41148. constraint.collideConnected = !!jointData.collision;
  41149. impostorJoint.joint.physicsJoint = constraint;
  41150. //don't add spring as constraint, as it is not one.
  41151. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41152. this.world.addConstraint(constraint);
  41153. }
  41154. else {
  41155. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41156. constraint.applyForce();
  41157. });
  41158. }
  41159. };
  41160. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41161. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41162. };
  41163. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41164. var index;
  41165. var mat;
  41166. for (index = 0; index < this._physicsMaterials.length; index++) {
  41167. mat = this._physicsMaterials[index];
  41168. if (mat.friction === friction && mat.restitution === restitution) {
  41169. return mat;
  41170. }
  41171. }
  41172. var currentMat = new CANNON.Material(name);
  41173. currentMat.friction = friction;
  41174. currentMat.restitution = restitution;
  41175. this._physicsMaterials.push(currentMat);
  41176. return currentMat;
  41177. };
  41178. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41179. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41180. };
  41181. CannonJSPlugin.prototype._createShape = function (impostor) {
  41182. var object = impostor.object;
  41183. var returnValue;
  41184. var extendSize = impostor.getObjectExtendSize();
  41185. switch (impostor.type) {
  41186. case BABYLON.PhysicsEngine.SphereImpostor:
  41187. var radiusX = extendSize.x;
  41188. var radiusY = extendSize.y;
  41189. var radiusZ = extendSize.z;
  41190. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41191. break;
  41192. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41193. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41194. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41195. break;
  41196. case BABYLON.PhysicsImpostor.BoxImpostor:
  41197. var box = extendSize.scale(0.5);
  41198. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41199. break;
  41200. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41201. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41202. returnValue = new CANNON.Plane();
  41203. break;
  41204. case BABYLON.PhysicsImpostor.MeshImpostor:
  41205. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41206. var rawFaces = object.getIndices ? object.getIndices() : [];
  41207. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41208. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41209. break;
  41210. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41211. returnValue = this._createHeightmap(object);
  41212. break;
  41213. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41214. returnValue = new CANNON.Particle();
  41215. break;
  41216. }
  41217. return returnValue;
  41218. };
  41219. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41220. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41221. var matrix = [];
  41222. //For now pointDepth will not be used and will be automatically calculated.
  41223. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41224. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41225. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41226. var elementSize = dim * 2 / arraySize;
  41227. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41228. for (var i = 0; i < pos.length; i = i + 3) {
  41229. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41230. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41231. var y = pos[i + 1] + minY;
  41232. if (!matrix[x]) {
  41233. matrix[x] = [];
  41234. }
  41235. if (!matrix[x][z]) {
  41236. matrix[x][z] = y;
  41237. }
  41238. matrix[x][z] = Math.max(y, matrix[x][z]);
  41239. }
  41240. for (var x = 0; x <= arraySize; ++x) {
  41241. if (!matrix[x]) {
  41242. var loc = 1;
  41243. while (!matrix[(x + loc) % arraySize]) {
  41244. loc++;
  41245. }
  41246. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41247. }
  41248. for (var z = 0; z <= arraySize; ++z) {
  41249. if (!matrix[x][z]) {
  41250. var loc = 1;
  41251. var newValue;
  41252. while (newValue === undefined) {
  41253. newValue = matrix[x][(z + loc++) % arraySize];
  41254. }
  41255. matrix[x][z] = newValue;
  41256. }
  41257. }
  41258. }
  41259. var shape = new CANNON.Heightfield(matrix, {
  41260. elementSize: elementSize
  41261. });
  41262. //For future reference, needed for body transformation
  41263. shape.minY = minY;
  41264. return shape;
  41265. };
  41266. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41267. var object = impostor.object;
  41268. //make sure it is updated...
  41269. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41270. // The delta between the mesh position and the mesh bounding box center
  41271. var center = impostor.getObjectCenter();
  41272. var extendSize = impostor.getObjectExtendSize();
  41273. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41274. this._tmpPosition.copyFrom(center);
  41275. var quaternion = object.rotationQuaternion;
  41276. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41277. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  41278. //-90 DEG in X, precalculated
  41279. quaternion = quaternion.multiply(this._minus90X);
  41280. //Invert! (Precalculated, 90 deg in X)
  41281. //No need to clone. this will never change.
  41282. impostor.setDeltaRotation(this._plus90X);
  41283. }
  41284. //If it is a heightfield, if should be centered.
  41285. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  41286. var mesh = object;
  41287. //calculate the correct body position:
  41288. var rotationQuaternion = mesh.rotationQuaternion;
  41289. mesh.rotationQuaternion = this._tmpUnityRotation;
  41290. mesh.computeWorldMatrix(true);
  41291. //get original center with no rotation
  41292. var c = center.clone();
  41293. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  41294. //rotation is back
  41295. mesh.rotationQuaternion = rotationQuaternion;
  41296. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  41297. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  41298. mesh.setPivotMatrix(p);
  41299. mesh.computeWorldMatrix(true);
  41300. //calculate the translation
  41301. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  41302. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  41303. //add it inverted to the delta
  41304. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  41305. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  41306. mesh.setPivotMatrix(oldPivot);
  41307. mesh.computeWorldMatrix(true);
  41308. }
  41309. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  41310. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  41311. this._tmpPosition.copyFrom(object.position);
  41312. }
  41313. impostor.setDeltaPosition(this._tmpDeltaPosition);
  41314. //Now update the impostor object
  41315. impostor.physicsBody.position.copy(this._tmpPosition);
  41316. impostor.physicsBody.quaternion.copy(quaternion);
  41317. };
  41318. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41319. impostor.object.position.copyFrom(impostor.physicsBody.position);
  41320. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  41321. };
  41322. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41323. impostor.physicsBody.position.copy(newPosition);
  41324. impostor.physicsBody.quaternion.copy(newRotation);
  41325. };
  41326. CannonJSPlugin.prototype.isSupported = function () {
  41327. return window.CANNON !== undefined;
  41328. };
  41329. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41330. impostor.physicsBody.velocity.copy(velocity);
  41331. };
  41332. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41333. impostor.physicsBody.angularVelocity.copy(velocity);
  41334. };
  41335. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41336. var v = impostor.physicsBody.velocity;
  41337. if (!v)
  41338. return null;
  41339. return new BABYLON.Vector3(v.x, v.y, v.z);
  41340. };
  41341. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41342. var v = impostor.physicsBody.angularVelocity;
  41343. if (!v)
  41344. return null;
  41345. return new BABYLON.Vector3(v.x, v.y, v.z);
  41346. };
  41347. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41348. impostor.physicsBody.mass = mass;
  41349. impostor.physicsBody.updateMassProperties();
  41350. };
  41351. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  41352. impostor.physicsBody.sleep();
  41353. };
  41354. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  41355. impostor.physicsBody.wakeUp();
  41356. };
  41357. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41358. joint.physicsJoint.distance = maxDistance;
  41359. };
  41360. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  41361. if (!motorIndex) {
  41362. joint.physicsJoint.enableMotor();
  41363. }
  41364. };
  41365. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  41366. if (!motorIndex) {
  41367. joint.physicsJoint.disableMotor();
  41368. }
  41369. };
  41370. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41371. if (!motorIndex) {
  41372. joint.physicsJoint.enableMotor();
  41373. joint.physicsJoint.setMotorSpeed(speed);
  41374. if (maxForce) {
  41375. this.setLimit(joint, maxForce);
  41376. }
  41377. }
  41378. };
  41379. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  41380. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  41381. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  41382. };
  41383. CannonJSPlugin.prototype.dispose = function () {
  41384. //nothing to do, actually.
  41385. };
  41386. return CannonJSPlugin;
  41387. }());
  41388. BABYLON.CannonJSPlugin = CannonJSPlugin;
  41389. })(BABYLON || (BABYLON = {}));
  41390. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  41391. var BABYLON;
  41392. (function (BABYLON) {
  41393. var OimoJSPlugin = (function () {
  41394. function OimoJSPlugin(iterations) {
  41395. this.name = "OimoJSPlugin";
  41396. this._tmpImpostorsArray = [];
  41397. this._tmpPositionVector = BABYLON.Vector3.Zero();
  41398. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  41399. this.world.worldscale(1);
  41400. this.world.clear();
  41401. //making sure no stats are calculated
  41402. this.world.isNoStat = true;
  41403. }
  41404. OimoJSPlugin.prototype.setGravity = function (gravity) {
  41405. this.world.gravity.copy(gravity);
  41406. };
  41407. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  41408. this.world.timeStep = timeStep;
  41409. };
  41410. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  41411. var _this = this;
  41412. impostors.forEach(function (impostor) {
  41413. impostor.beforeStep();
  41414. });
  41415. this.world.step();
  41416. impostors.forEach(function (impostor) {
  41417. impostor.afterStep();
  41418. //update the ordered impostors array
  41419. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  41420. });
  41421. //check for collisions
  41422. var contact = this.world.contacts;
  41423. while (contact !== null) {
  41424. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  41425. contact = contact.next;
  41426. continue;
  41427. }
  41428. //is this body colliding with any other? get the impostor
  41429. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  41430. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  41431. if (!mainImpostor || !collidingImpostor) {
  41432. contact = contact.next;
  41433. continue;
  41434. }
  41435. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41436. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  41437. contact = contact.next;
  41438. }
  41439. };
  41440. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41441. var mass = impostor.physicsBody.massInfo.mass;
  41442. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  41443. };
  41444. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41445. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  41446. this.applyImpulse(impostor, force, contactPoint);
  41447. };
  41448. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41449. var _this = this;
  41450. //parent-child relationship. Does this impostor has a parent impostor?
  41451. if (impostor.parent) {
  41452. if (impostor.physicsBody) {
  41453. this.removePhysicsBody(impostor);
  41454. //TODO is that needed?
  41455. impostor.forceUpdate();
  41456. }
  41457. return;
  41458. }
  41459. if (impostor.isBodyInitRequired()) {
  41460. var bodyConfig = {
  41461. name: impostor.uniqueId,
  41462. //Oimo must have mass, also for static objects.
  41463. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  41464. size: [],
  41465. type: [],
  41466. pos: [],
  41467. rot: [],
  41468. move: impostor.getParam("mass") !== 0,
  41469. //Supporting older versions of Oimo
  41470. world: this.world
  41471. };
  41472. var impostors = [impostor];
  41473. var addToArray = function (parent) {
  41474. if (!parent.getChildMeshes)
  41475. return;
  41476. parent.getChildMeshes().forEach(function (m) {
  41477. if (m.physicsImpostor) {
  41478. impostors.push(m.physicsImpostor);
  41479. m.physicsImpostor._init();
  41480. }
  41481. });
  41482. };
  41483. addToArray(impostor.object);
  41484. var checkWithEpsilon_1 = function (value) {
  41485. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  41486. };
  41487. impostors.forEach(function (i) {
  41488. //get the correct bounding box
  41489. var oldQuaternion = i.object.rotationQuaternion;
  41490. var rot = new OIMO.Euler().setFromQuaternion({
  41491. x: impostor.object.rotationQuaternion.x,
  41492. y: impostor.object.rotationQuaternion.y,
  41493. z: impostor.object.rotationQuaternion.z,
  41494. s: impostor.object.rotationQuaternion.w
  41495. });
  41496. var extendSize = i.getObjectExtendSize();
  41497. if (i === impostor) {
  41498. var center = impostor.getObjectCenter();
  41499. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  41500. //Can also use Array.prototype.push.apply
  41501. bodyConfig.pos.push(center.x);
  41502. bodyConfig.pos.push(center.y);
  41503. bodyConfig.pos.push(center.z);
  41504. //tmp solution
  41505. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  41506. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  41507. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  41508. }
  41509. else {
  41510. bodyConfig.pos.push(i.object.position.x);
  41511. bodyConfig.pos.push(i.object.position.y);
  41512. bodyConfig.pos.push(i.object.position.z);
  41513. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  41514. bodyConfig.rot.push(0);
  41515. bodyConfig.rot.push(0);
  41516. bodyConfig.rot.push(0);
  41517. }
  41518. // register mesh
  41519. switch (i.type) {
  41520. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41521. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  41522. case BABYLON.PhysicsImpostor.SphereImpostor:
  41523. var radiusX = extendSize.x;
  41524. var radiusY = extendSize.y;
  41525. var radiusZ = extendSize.z;
  41526. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  41527. bodyConfig.type.push('sphere');
  41528. //due to the way oimo works with compounds, add 3 times
  41529. bodyConfig.size.push(size);
  41530. bodyConfig.size.push(size);
  41531. bodyConfig.size.push(size);
  41532. break;
  41533. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41534. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  41535. var sizeY = checkWithEpsilon_1(extendSize.y);
  41536. bodyConfig.type.push('cylinder');
  41537. bodyConfig.size.push(sizeX);
  41538. bodyConfig.size.push(sizeY);
  41539. //due to the way oimo works with compounds, add one more value.
  41540. bodyConfig.size.push(sizeY);
  41541. break;
  41542. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41543. case BABYLON.PhysicsImpostor.BoxImpostor:
  41544. default:
  41545. var sizeX = checkWithEpsilon_1(extendSize.x);
  41546. var sizeY = checkWithEpsilon_1(extendSize.y);
  41547. var sizeZ = checkWithEpsilon_1(extendSize.z);
  41548. bodyConfig.type.push('box');
  41549. bodyConfig.size.push(sizeX);
  41550. bodyConfig.size.push(sizeY);
  41551. bodyConfig.size.push(sizeZ);
  41552. break;
  41553. }
  41554. //actually not needed, but hey...
  41555. i.object.rotationQuaternion = oldQuaternion;
  41556. });
  41557. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  41558. }
  41559. else {
  41560. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  41561. }
  41562. impostor.setDeltaPosition(this._tmpPositionVector);
  41563. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  41564. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  41565. };
  41566. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41567. //impostor.physicsBody.dispose();
  41568. //Same as : (older oimo versions)
  41569. this.world.removeRigidBody(impostor.physicsBody);
  41570. };
  41571. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41572. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41573. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41574. if (!mainBody || !connectedBody) {
  41575. return;
  41576. }
  41577. var jointData = impostorJoint.joint.jointData;
  41578. var options = jointData.nativeParams || {};
  41579. var type;
  41580. var nativeJointData = {
  41581. body1: mainBody,
  41582. body2: connectedBody,
  41583. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  41584. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  41585. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  41586. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  41587. min: options.min,
  41588. max: options.max,
  41589. collision: options.collision || jointData.collision,
  41590. spring: options.spring,
  41591. //supporting older version of Oimo
  41592. world: this.world
  41593. };
  41594. switch (impostorJoint.joint.type) {
  41595. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41596. type = "jointBall";
  41597. break;
  41598. case BABYLON.PhysicsJoint.SpringJoint:
  41599. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  41600. var springData = jointData;
  41601. nativeJointData.min = springData.length || nativeJointData.min;
  41602. //Max should also be set, just make sure it is at least min
  41603. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  41604. case BABYLON.PhysicsJoint.DistanceJoint:
  41605. type = "jointDistance";
  41606. nativeJointData.max = jointData.maxDistance;
  41607. break;
  41608. case BABYLON.PhysicsJoint.PrismaticJoint:
  41609. type = "jointPrisme";
  41610. break;
  41611. case BABYLON.PhysicsJoint.SliderJoint:
  41612. type = "jointSlide";
  41613. break;
  41614. case BABYLON.PhysicsJoint.WheelJoint:
  41615. type = "jointWheel";
  41616. break;
  41617. case BABYLON.PhysicsJoint.HingeJoint:
  41618. default:
  41619. type = "jointHinge";
  41620. break;
  41621. }
  41622. nativeJointData.type = type;
  41623. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  41624. };
  41625. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41626. //Bug in Oimo prevents us from disposing a joint in the playground
  41627. //joint.joint.physicsJoint.dispose();
  41628. //So we will bruteforce it!
  41629. try {
  41630. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  41631. }
  41632. catch (e) {
  41633. BABYLON.Tools.Warn(e);
  41634. }
  41635. };
  41636. OimoJSPlugin.prototype.isSupported = function () {
  41637. return OIMO !== undefined;
  41638. };
  41639. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41640. if (!impostor.physicsBody.sleeping) {
  41641. //TODO check that
  41642. if (impostor.physicsBody.shapes.next) {
  41643. var parentShape = this._getLastShape(impostor.physicsBody);
  41644. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  41645. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  41646. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  41647. }
  41648. else {
  41649. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  41650. }
  41651. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  41652. impostor.object.rotationQuaternion.normalize();
  41653. }
  41654. };
  41655. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41656. var body = impostor.physicsBody;
  41657. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  41658. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  41659. body.syncShapes();
  41660. body.awake();
  41661. };
  41662. OimoJSPlugin.prototype._getLastShape = function (body) {
  41663. var lastShape = body.shapes;
  41664. while (lastShape.next) {
  41665. lastShape = lastShape.next;
  41666. }
  41667. return lastShape;
  41668. };
  41669. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41670. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  41671. };
  41672. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41673. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  41674. };
  41675. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41676. var v = impostor.physicsBody.linearVelocity;
  41677. if (!v)
  41678. return null;
  41679. return new BABYLON.Vector3(v.x, v.y, v.z);
  41680. };
  41681. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41682. var v = impostor.physicsBody.angularVelocity;
  41683. if (!v)
  41684. return null;
  41685. return new BABYLON.Vector3(v.x, v.y, v.z);
  41686. };
  41687. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41688. var staticBody = mass === 0;
  41689. //this will actually set the body's density and not its mass.
  41690. //But this is how oimo treats the mass variable.
  41691. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  41692. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  41693. };
  41694. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  41695. impostor.physicsBody.sleep();
  41696. };
  41697. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  41698. impostor.physicsBody.awake();
  41699. };
  41700. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41701. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  41702. if (minDistance !== void 0) {
  41703. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  41704. }
  41705. };
  41706. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41707. //TODO separate rotational and transational motors.
  41708. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41709. if (motor) {
  41710. motor.setMotor(speed, maxForce);
  41711. }
  41712. };
  41713. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  41714. //TODO separate rotational and transational motors.
  41715. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41716. if (motor) {
  41717. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  41718. }
  41719. };
  41720. OimoJSPlugin.prototype.dispose = function () {
  41721. this.world.clear();
  41722. };
  41723. return OimoJSPlugin;
  41724. }());
  41725. BABYLON.OimoJSPlugin = OimoJSPlugin;
  41726. })(BABYLON || (BABYLON = {}));
  41727. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  41728. var BABYLON;
  41729. (function (BABYLON) {
  41730. var DisplayPassPostProcess = (function (_super) {
  41731. __extends(DisplayPassPostProcess, _super);
  41732. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  41733. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  41734. }
  41735. return DisplayPassPostProcess;
  41736. }(BABYLON.PostProcess));
  41737. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  41738. })(BABYLON || (BABYLON = {}));
  41739. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  41740. var BABYLON;
  41741. (function (BABYLON) {
  41742. var SimplificationSettings = (function () {
  41743. function SimplificationSettings(quality, distance, optimizeMesh) {
  41744. this.quality = quality;
  41745. this.distance = distance;
  41746. this.optimizeMesh = optimizeMesh;
  41747. }
  41748. return SimplificationSettings;
  41749. }());
  41750. BABYLON.SimplificationSettings = SimplificationSettings;
  41751. var SimplificationQueue = (function () {
  41752. function SimplificationQueue() {
  41753. this.running = false;
  41754. this._simplificationArray = [];
  41755. }
  41756. SimplificationQueue.prototype.addTask = function (task) {
  41757. this._simplificationArray.push(task);
  41758. };
  41759. SimplificationQueue.prototype.executeNext = function () {
  41760. var task = this._simplificationArray.pop();
  41761. if (task) {
  41762. this.running = true;
  41763. this.runSimplification(task);
  41764. }
  41765. else {
  41766. this.running = false;
  41767. }
  41768. };
  41769. SimplificationQueue.prototype.runSimplification = function (task) {
  41770. var _this = this;
  41771. if (task.parallelProcessing) {
  41772. //parallel simplifier
  41773. task.settings.forEach(function (setting) {
  41774. var simplifier = _this.getSimplifier(task);
  41775. simplifier.simplify(setting, function (newMesh) {
  41776. task.mesh.addLODLevel(setting.distance, newMesh);
  41777. newMesh.isVisible = true;
  41778. //check if it is the last
  41779. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41780. //all done, run the success callback.
  41781. task.successCallback();
  41782. }
  41783. _this.executeNext();
  41784. });
  41785. });
  41786. }
  41787. else {
  41788. //single simplifier.
  41789. var simplifier = this.getSimplifier(task);
  41790. var runDecimation = function (setting, callback) {
  41791. simplifier.simplify(setting, function (newMesh) {
  41792. task.mesh.addLODLevel(setting.distance, newMesh);
  41793. newMesh.isVisible = true;
  41794. //run the next quality level
  41795. callback();
  41796. });
  41797. };
  41798. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  41799. runDecimation(task.settings[loop.index], function () {
  41800. loop.executeNext();
  41801. });
  41802. }, function () {
  41803. //execution ended, run the success callback.
  41804. if (task.successCallback) {
  41805. task.successCallback();
  41806. }
  41807. _this.executeNext();
  41808. });
  41809. }
  41810. };
  41811. SimplificationQueue.prototype.getSimplifier = function (task) {
  41812. switch (task.simplificationType) {
  41813. case SimplificationType.QUADRATIC:
  41814. default:
  41815. return new QuadraticErrorSimplification(task.mesh);
  41816. }
  41817. };
  41818. return SimplificationQueue;
  41819. }());
  41820. BABYLON.SimplificationQueue = SimplificationQueue;
  41821. /**
  41822. * The implemented types of simplification.
  41823. * At the moment only Quadratic Error Decimation is implemented.
  41824. */
  41825. (function (SimplificationType) {
  41826. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  41827. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  41828. var SimplificationType = BABYLON.SimplificationType;
  41829. var DecimationTriangle = (function () {
  41830. function DecimationTriangle(vertices) {
  41831. this.vertices = vertices;
  41832. this.error = new Array(4);
  41833. this.deleted = false;
  41834. this.isDirty = false;
  41835. this.deletePending = false;
  41836. this.borderFactor = 0;
  41837. }
  41838. return DecimationTriangle;
  41839. }());
  41840. BABYLON.DecimationTriangle = DecimationTriangle;
  41841. var DecimationVertex = (function () {
  41842. function DecimationVertex(position, id) {
  41843. this.position = position;
  41844. this.id = id;
  41845. this.isBorder = true;
  41846. this.q = new QuadraticMatrix();
  41847. this.triangleCount = 0;
  41848. this.triangleStart = 0;
  41849. this.originalOffsets = [];
  41850. }
  41851. DecimationVertex.prototype.updatePosition = function (newPosition) {
  41852. this.position.copyFrom(newPosition);
  41853. };
  41854. return DecimationVertex;
  41855. }());
  41856. BABYLON.DecimationVertex = DecimationVertex;
  41857. var QuadraticMatrix = (function () {
  41858. function QuadraticMatrix(data) {
  41859. this.data = new Array(10);
  41860. for (var i = 0; i < 10; ++i) {
  41861. if (data && data[i]) {
  41862. this.data[i] = data[i];
  41863. }
  41864. else {
  41865. this.data[i] = 0;
  41866. }
  41867. }
  41868. }
  41869. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  41870. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  41871. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  41872. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  41873. return det;
  41874. };
  41875. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  41876. for (var i = 0; i < 10; ++i) {
  41877. this.data[i] += matrix.data[i];
  41878. }
  41879. };
  41880. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  41881. for (var i = 0; i < 10; ++i) {
  41882. this.data[i] += data[i];
  41883. }
  41884. };
  41885. QuadraticMatrix.prototype.add = function (matrix) {
  41886. var m = new QuadraticMatrix();
  41887. for (var i = 0; i < 10; ++i) {
  41888. m.data[i] = this.data[i] + matrix.data[i];
  41889. }
  41890. return m;
  41891. };
  41892. QuadraticMatrix.FromData = function (a, b, c, d) {
  41893. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  41894. };
  41895. //returning an array to avoid garbage collection
  41896. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  41897. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  41898. };
  41899. return QuadraticMatrix;
  41900. }());
  41901. BABYLON.QuadraticMatrix = QuadraticMatrix;
  41902. var Reference = (function () {
  41903. function Reference(vertexId, triangleId) {
  41904. this.vertexId = vertexId;
  41905. this.triangleId = triangleId;
  41906. }
  41907. return Reference;
  41908. }());
  41909. BABYLON.Reference = Reference;
  41910. /**
  41911. * An implementation of the Quadratic Error simplification algorithm.
  41912. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  41913. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  41914. * @author RaananW
  41915. */
  41916. var QuadraticErrorSimplification = (function () {
  41917. function QuadraticErrorSimplification(_mesh) {
  41918. this._mesh = _mesh;
  41919. this.initialized = false;
  41920. this.syncIterations = 5000;
  41921. this.aggressiveness = 7;
  41922. this.decimationIterations = 100;
  41923. this.boundingBoxEpsilon = BABYLON.Epsilon;
  41924. }
  41925. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  41926. var _this = this;
  41927. this.initDecimatedMesh();
  41928. //iterating through the submeshes array, one after the other.
  41929. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  41930. _this.initWithMesh(loop.index, function () {
  41931. _this.runDecimation(settings, loop.index, function () {
  41932. loop.executeNext();
  41933. });
  41934. }, settings.optimizeMesh);
  41935. }, function () {
  41936. setTimeout(function () {
  41937. successCallback(_this._reconstructedMesh);
  41938. }, 0);
  41939. });
  41940. };
  41941. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  41942. var _this = this;
  41943. var gCount = 0;
  41944. triangle.vertices.forEach(function (vertex) {
  41945. var count = 0;
  41946. var vPos = vertex.position;
  41947. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  41948. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  41949. ++count;
  41950. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  41951. ++count;
  41952. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  41953. ++count;
  41954. if (count > 1) {
  41955. ++gCount;
  41956. }
  41957. ;
  41958. });
  41959. if (gCount > 1) {
  41960. console.log(triangle, gCount);
  41961. }
  41962. return gCount > 1;
  41963. };
  41964. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  41965. var _this = this;
  41966. var targetCount = ~~(this.triangles.length * settings.quality);
  41967. var deletedTriangles = 0;
  41968. var triangleCount = this.triangles.length;
  41969. var iterationFunction = function (iteration, callback) {
  41970. setTimeout(function () {
  41971. if (iteration % 5 === 0) {
  41972. _this.updateMesh(iteration === 0);
  41973. }
  41974. for (var i = 0; i < _this.triangles.length; ++i) {
  41975. _this.triangles[i].isDirty = false;
  41976. }
  41977. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  41978. var trianglesIterator = function (i) {
  41979. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  41980. var t = _this.triangles[tIdx];
  41981. if (!t)
  41982. return;
  41983. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  41984. return;
  41985. }
  41986. for (var j = 0; j < 3; ++j) {
  41987. if (t.error[j] < threshold) {
  41988. var deleted0 = [];
  41989. var deleted1 = [];
  41990. var v0 = t.vertices[j];
  41991. var v1 = t.vertices[(j + 1) % 3];
  41992. if (v0.isBorder || v1.isBorder)
  41993. continue;
  41994. var p = BABYLON.Vector3.Zero();
  41995. var n = BABYLON.Vector3.Zero();
  41996. var uv = BABYLON.Vector2.Zero();
  41997. var color = new BABYLON.Color4(0, 0, 0, 1);
  41998. _this.calculateError(v0, v1, p, n, uv, color);
  41999. var delTr = [];
  42000. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42001. continue;
  42002. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42003. continue;
  42004. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42005. continue;
  42006. var uniqueArray = [];
  42007. delTr.forEach(function (deletedT) {
  42008. if (uniqueArray.indexOf(deletedT) === -1) {
  42009. deletedT.deletePending = true;
  42010. uniqueArray.push(deletedT);
  42011. }
  42012. });
  42013. if (uniqueArray.length % 2 !== 0) {
  42014. continue;
  42015. }
  42016. v0.q = v1.q.add(v0.q);
  42017. v0.updatePosition(p);
  42018. var tStart = _this.references.length;
  42019. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42020. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42021. var tCount = _this.references.length - tStart;
  42022. if (tCount <= v0.triangleCount) {
  42023. if (tCount) {
  42024. for (var c = 0; c < tCount; c++) {
  42025. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42026. }
  42027. }
  42028. }
  42029. else {
  42030. v0.triangleStart = tStart;
  42031. }
  42032. v0.triangleCount = tCount;
  42033. break;
  42034. }
  42035. }
  42036. };
  42037. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42038. }, 0);
  42039. };
  42040. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42041. if (triangleCount - deletedTriangles <= targetCount)
  42042. loop.breakLoop();
  42043. else {
  42044. iterationFunction(loop.index, function () {
  42045. loop.executeNext();
  42046. });
  42047. }
  42048. }, function () {
  42049. setTimeout(function () {
  42050. //reconstruct this part of the mesh
  42051. _this.reconstructMesh(submeshIndex);
  42052. successCallback();
  42053. }, 0);
  42054. });
  42055. };
  42056. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42057. var _this = this;
  42058. this.vertices = [];
  42059. this.triangles = [];
  42060. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42061. var indices = this._mesh.getIndices();
  42062. var submesh = this._mesh.subMeshes[submeshIndex];
  42063. var findInVertices = function (positionToSearch) {
  42064. if (optimizeMesh) {
  42065. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42066. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42067. return _this.vertices[ii];
  42068. }
  42069. }
  42070. }
  42071. return null;
  42072. };
  42073. var vertexReferences = [];
  42074. var vertexInit = function (i) {
  42075. var offset = i + submesh.verticesStart;
  42076. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42077. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42078. vertex.originalOffsets.push(offset);
  42079. if (vertex.id === _this.vertices.length) {
  42080. _this.vertices.push(vertex);
  42081. }
  42082. vertexReferences.push(vertex.id);
  42083. };
  42084. //var totalVertices = mesh.getTotalVertices();
  42085. var totalVertices = submesh.verticesCount;
  42086. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42087. var indicesInit = function (i) {
  42088. var offset = (submesh.indexStart / 3) + i;
  42089. var pos = (offset * 3);
  42090. var i0 = indices[pos + 0];
  42091. var i1 = indices[pos + 1];
  42092. var i2 = indices[pos + 2];
  42093. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42094. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42095. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42096. var triangle = new DecimationTriangle([v0, v1, v2]);
  42097. triangle.originalOffset = pos;
  42098. _this.triangles.push(triangle);
  42099. };
  42100. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42101. _this.init(callback);
  42102. });
  42103. });
  42104. };
  42105. QuadraticErrorSimplification.prototype.init = function (callback) {
  42106. var _this = this;
  42107. var triangleInit1 = function (i) {
  42108. var t = _this.triangles[i];
  42109. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42110. for (var j = 0; j < 3; j++) {
  42111. 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))));
  42112. }
  42113. };
  42114. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42115. var triangleInit2 = function (i) {
  42116. var t = _this.triangles[i];
  42117. for (var j = 0; j < 3; ++j) {
  42118. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42119. }
  42120. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42121. };
  42122. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42123. _this.initialized = true;
  42124. callback();
  42125. });
  42126. });
  42127. };
  42128. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42129. var newTriangles = [];
  42130. var i;
  42131. for (i = 0; i < this.vertices.length; ++i) {
  42132. this.vertices[i].triangleCount = 0;
  42133. }
  42134. var t;
  42135. var j;
  42136. for (i = 0; i < this.triangles.length; ++i) {
  42137. if (!this.triangles[i].deleted) {
  42138. t = this.triangles[i];
  42139. for (j = 0; j < 3; ++j) {
  42140. t.vertices[j].triangleCount = 1;
  42141. }
  42142. newTriangles.push(t);
  42143. }
  42144. }
  42145. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42146. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42147. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42148. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42149. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42150. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42151. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42152. var vertexCount = 0;
  42153. for (i = 0; i < this.vertices.length; ++i) {
  42154. var vertex = this.vertices[i];
  42155. vertex.id = vertexCount;
  42156. if (vertex.triangleCount) {
  42157. vertex.originalOffsets.forEach(function (originalOffset) {
  42158. newPositionData.push(vertex.position.x);
  42159. newPositionData.push(vertex.position.y);
  42160. newPositionData.push(vertex.position.z);
  42161. newNormalData.push(normalData[originalOffset * 3]);
  42162. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42163. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42164. if (uvs && uvs.length) {
  42165. newUVsData.push(uvs[(originalOffset * 2)]);
  42166. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42167. }
  42168. else if (colorsData && colorsData.length) {
  42169. newColorsData.push(colorsData[(originalOffset * 4)]);
  42170. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42171. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42172. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42173. }
  42174. ++vertexCount;
  42175. });
  42176. }
  42177. }
  42178. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42179. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42180. var submeshesArray = this._reconstructedMesh.subMeshes;
  42181. this._reconstructedMesh.subMeshes = [];
  42182. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42183. var originalIndices = this._mesh.getIndices();
  42184. for (i = 0; i < newTriangles.length; ++i) {
  42185. t = newTriangles[i]; //now get the new referencing point for each vertex
  42186. [0, 1, 2].forEach(function (idx) {
  42187. var id = originalIndices[t.originalOffset + idx];
  42188. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42189. if (offset < 0)
  42190. offset = 0;
  42191. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42192. });
  42193. }
  42194. //overwriting the old vertex buffers and indices.
  42195. this._reconstructedMesh.setIndices(newIndicesArray);
  42196. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42197. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42198. if (newUVsData.length > 0)
  42199. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42200. if (newColorsData.length > 0)
  42201. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42202. //create submesh
  42203. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42204. if (submeshIndex > 0) {
  42205. this._reconstructedMesh.subMeshes = [];
  42206. submeshesArray.forEach(function (submesh) {
  42207. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42208. });
  42209. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42210. }
  42211. };
  42212. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42213. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42214. this._reconstructedMesh.material = this._mesh.material;
  42215. this._reconstructedMesh.parent = this._mesh.parent;
  42216. this._reconstructedMesh.isVisible = false;
  42217. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42218. };
  42219. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42220. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42221. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42222. if (t.deleted)
  42223. continue;
  42224. var s = this.references[vertex1.triangleStart + i].vertexId;
  42225. var v1 = t.vertices[(s + 1) % 3];
  42226. var v2 = t.vertices[(s + 2) % 3];
  42227. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42228. deletedArray[i] = true;
  42229. delTr.push(t);
  42230. continue;
  42231. }
  42232. var d1 = v1.position.subtract(point);
  42233. d1 = d1.normalize();
  42234. var d2 = v2.position.subtract(point);
  42235. d2 = d2.normalize();
  42236. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42237. return true;
  42238. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42239. deletedArray[i] = false;
  42240. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42241. return true;
  42242. }
  42243. return false;
  42244. };
  42245. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42246. var newDeleted = deletedTriangles;
  42247. for (var i = 0; i < vertex.triangleCount; ++i) {
  42248. var ref = this.references[vertex.triangleStart + i];
  42249. var t = this.triangles[ref.triangleId];
  42250. if (t.deleted)
  42251. continue;
  42252. if (deletedArray[i] && t.deletePending) {
  42253. t.deleted = true;
  42254. newDeleted++;
  42255. continue;
  42256. }
  42257. t.vertices[ref.vertexId] = origVertex;
  42258. t.isDirty = true;
  42259. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42260. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42261. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42262. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42263. this.references.push(ref);
  42264. }
  42265. return newDeleted;
  42266. };
  42267. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42268. for (var i = 0; i < this.vertices.length; ++i) {
  42269. var vCount = [];
  42270. var vId = [];
  42271. var v = this.vertices[i];
  42272. var j;
  42273. for (j = 0; j < v.triangleCount; ++j) {
  42274. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42275. for (var ii = 0; ii < 3; ii++) {
  42276. var ofs = 0;
  42277. var vv = triangle.vertices[ii];
  42278. while (ofs < vCount.length) {
  42279. if (vId[ofs] === vv.id)
  42280. break;
  42281. ++ofs;
  42282. }
  42283. if (ofs === vCount.length) {
  42284. vCount.push(1);
  42285. vId.push(vv.id);
  42286. }
  42287. else {
  42288. vCount[ofs]++;
  42289. }
  42290. }
  42291. }
  42292. for (j = 0; j < vCount.length; ++j) {
  42293. if (vCount[j] === 1) {
  42294. this.vertices[vId[j]].isBorder = true;
  42295. }
  42296. else {
  42297. this.vertices[vId[j]].isBorder = false;
  42298. }
  42299. }
  42300. }
  42301. };
  42302. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  42303. if (identifyBorders === void 0) { identifyBorders = false; }
  42304. var i;
  42305. if (!identifyBorders) {
  42306. var newTrianglesVector = [];
  42307. for (i = 0; i < this.triangles.length; ++i) {
  42308. if (!this.triangles[i].deleted) {
  42309. newTrianglesVector.push(this.triangles[i]);
  42310. }
  42311. }
  42312. this.triangles = newTrianglesVector;
  42313. }
  42314. for (i = 0; i < this.vertices.length; ++i) {
  42315. this.vertices[i].triangleCount = 0;
  42316. this.vertices[i].triangleStart = 0;
  42317. }
  42318. var t;
  42319. var j;
  42320. var v;
  42321. for (i = 0; i < this.triangles.length; ++i) {
  42322. t = this.triangles[i];
  42323. for (j = 0; j < 3; ++j) {
  42324. v = t.vertices[j];
  42325. v.triangleCount++;
  42326. }
  42327. }
  42328. var tStart = 0;
  42329. for (i = 0; i < this.vertices.length; ++i) {
  42330. this.vertices[i].triangleStart = tStart;
  42331. tStart += this.vertices[i].triangleCount;
  42332. this.vertices[i].triangleCount = 0;
  42333. }
  42334. var newReferences = new Array(this.triangles.length * 3);
  42335. for (i = 0; i < this.triangles.length; ++i) {
  42336. t = this.triangles[i];
  42337. for (j = 0; j < 3; ++j) {
  42338. v = t.vertices[j];
  42339. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  42340. v.triangleCount++;
  42341. }
  42342. }
  42343. this.references = newReferences;
  42344. if (identifyBorders) {
  42345. this.identifyBorder();
  42346. }
  42347. };
  42348. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  42349. var x = point.x;
  42350. var y = point.y;
  42351. var z = point.z;
  42352. 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
  42353. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  42354. };
  42355. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  42356. var q = vertex1.q.add(vertex2.q);
  42357. var border = vertex1.isBorder && vertex2.isBorder;
  42358. var error = 0;
  42359. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  42360. if (qDet !== 0 && !border) {
  42361. if (!pointResult) {
  42362. pointResult = BABYLON.Vector3.Zero();
  42363. }
  42364. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  42365. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  42366. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  42367. error = this.vertexError(q, pointResult);
  42368. }
  42369. else {
  42370. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  42371. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  42372. var error1 = this.vertexError(q, vertex1.position);
  42373. var error2 = this.vertexError(q, vertex2.position);
  42374. var error3 = this.vertexError(q, p3);
  42375. error = Math.min(error1, error2, error3);
  42376. if (error === error1) {
  42377. if (pointResult) {
  42378. pointResult.copyFrom(vertex1.position);
  42379. }
  42380. }
  42381. else if (error === error2) {
  42382. if (pointResult) {
  42383. pointResult.copyFrom(vertex2.position);
  42384. }
  42385. }
  42386. else {
  42387. if (pointResult) {
  42388. pointResult.copyFrom(p3);
  42389. }
  42390. }
  42391. }
  42392. return error;
  42393. };
  42394. return QuadraticErrorSimplification;
  42395. }());
  42396. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  42397. })(BABYLON || (BABYLON = {}));
  42398. //# sourceMappingURL=babylon.meshSimplification.js.map
  42399. var BABYLON;
  42400. (function (BABYLON) {
  42401. var serializedGeometries = [];
  42402. var serializeGeometry = function (geometry, serializationGeometries) {
  42403. if (serializedGeometries[geometry.id]) {
  42404. return;
  42405. }
  42406. if (geometry.doNotSerialize) {
  42407. return;
  42408. }
  42409. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  42410. serializationGeometries.boxes.push(geometry.serialize());
  42411. }
  42412. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  42413. serializationGeometries.spheres.push(geometry.serialize());
  42414. }
  42415. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  42416. serializationGeometries.cylinders.push(geometry.serialize());
  42417. }
  42418. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  42419. serializationGeometries.toruses.push(geometry.serialize());
  42420. }
  42421. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  42422. serializationGeometries.grounds.push(geometry.serialize());
  42423. }
  42424. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  42425. serializationGeometries.planes.push(geometry.serialize());
  42426. }
  42427. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  42428. serializationGeometries.torusKnots.push(geometry.serialize());
  42429. }
  42430. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  42431. throw new Error("Unknown primitive type");
  42432. }
  42433. else {
  42434. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  42435. }
  42436. serializedGeometries[geometry.id] = true;
  42437. };
  42438. var serializeMesh = function (mesh, serializationScene) {
  42439. var serializationObject = {};
  42440. serializationObject.name = mesh.name;
  42441. serializationObject.id = mesh.id;
  42442. if (BABYLON.Tags.HasTags(mesh)) {
  42443. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  42444. }
  42445. serializationObject.position = mesh.position.asArray();
  42446. if (mesh.rotationQuaternion) {
  42447. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  42448. }
  42449. else if (mesh.rotation) {
  42450. serializationObject.rotation = mesh.rotation.asArray();
  42451. }
  42452. serializationObject.scaling = mesh.scaling.asArray();
  42453. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  42454. serializationObject.isEnabled = mesh.isEnabled();
  42455. serializationObject.isVisible = mesh.isVisible;
  42456. serializationObject.infiniteDistance = mesh.infiniteDistance;
  42457. serializationObject.pickable = mesh.isPickable;
  42458. serializationObject.receiveShadows = mesh.receiveShadows;
  42459. serializationObject.billboardMode = mesh.billboardMode;
  42460. serializationObject.visibility = mesh.visibility;
  42461. serializationObject.checkCollisions = mesh.checkCollisions;
  42462. serializationObject.isBlocker = mesh.isBlocker;
  42463. // Parent
  42464. if (mesh.parent) {
  42465. serializationObject.parentId = mesh.parent.id;
  42466. }
  42467. // Geometry
  42468. var geometry = mesh._geometry;
  42469. if (geometry) {
  42470. var geometryId = geometry.id;
  42471. serializationObject.geometryId = geometryId;
  42472. if (!mesh.getScene().getGeometryByID(geometryId)) {
  42473. // 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
  42474. serializeGeometry(geometry, serializationScene.geometries);
  42475. }
  42476. // SubMeshes
  42477. serializationObject.subMeshes = [];
  42478. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42479. var subMesh = mesh.subMeshes[subIndex];
  42480. serializationObject.subMeshes.push({
  42481. materialIndex: subMesh.materialIndex,
  42482. verticesStart: subMesh.verticesStart,
  42483. verticesCount: subMesh.verticesCount,
  42484. indexStart: subMesh.indexStart,
  42485. indexCount: subMesh.indexCount
  42486. });
  42487. }
  42488. }
  42489. // Material
  42490. if (mesh.material) {
  42491. serializationObject.materialId = mesh.material.id;
  42492. }
  42493. else {
  42494. mesh.material = null;
  42495. }
  42496. // Skeleton
  42497. if (mesh.skeleton) {
  42498. serializationObject.skeletonId = mesh.skeleton.id;
  42499. }
  42500. // Physics
  42501. //TODO implement correct serialization for physics impostors.
  42502. if (mesh.getPhysicsImpostor()) {
  42503. serializationObject.physicsMass = mesh.getPhysicsMass();
  42504. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  42505. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  42506. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  42507. }
  42508. // Metadata
  42509. if (mesh.metadata) {
  42510. serializationObject.metadata = mesh.metadata;
  42511. }
  42512. // Instances
  42513. serializationObject.instances = [];
  42514. for (var index = 0; index < mesh.instances.length; index++) {
  42515. var instance = mesh.instances[index];
  42516. var serializationInstance = {
  42517. name: instance.name,
  42518. position: instance.position.asArray(),
  42519. scaling: instance.scaling.asArray()
  42520. };
  42521. if (instance.rotationQuaternion) {
  42522. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  42523. }
  42524. else if (instance.rotation) {
  42525. serializationInstance.rotation = instance.rotation.asArray();
  42526. }
  42527. serializationObject.instances.push(serializationInstance);
  42528. // Animations
  42529. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  42530. serializationInstance.ranges = instance.serializeAnimationRanges();
  42531. }
  42532. // Animations
  42533. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  42534. serializationObject.ranges = mesh.serializeAnimationRanges();
  42535. // Layer mask
  42536. serializationObject.layerMask = mesh.layerMask;
  42537. // Alpha
  42538. serializationObject.alphaIndex = mesh.alphaIndex;
  42539. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  42540. // Overlay
  42541. serializationObject.overlayAlpha = mesh.overlayAlpha;
  42542. serializationObject.overlayColor = mesh.overlayColor.asArray();
  42543. serializationObject.renderOverlay = mesh.renderOverlay;
  42544. // Fog
  42545. serializationObject.applyFog = mesh.applyFog;
  42546. // Action Manager
  42547. if (mesh.actionManager) {
  42548. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  42549. }
  42550. return serializationObject;
  42551. };
  42552. var finalizeSingleMesh = function (mesh, serializationObject) {
  42553. //only works if the mesh is already loaded
  42554. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42555. //serialize material
  42556. if (mesh.material) {
  42557. if (mesh.material instanceof BABYLON.StandardMaterial) {
  42558. serializationObject.materials = serializationObject.materials || [];
  42559. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42560. serializationObject.materials.push(mesh.material.serialize());
  42561. }
  42562. }
  42563. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  42564. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  42565. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42566. serializationObject.multiMaterials.push(mesh.material.serialize());
  42567. }
  42568. }
  42569. }
  42570. //serialize geometry
  42571. var geometry = mesh._geometry;
  42572. if (geometry) {
  42573. if (!serializationObject.geometries) {
  42574. serializationObject.geometries = {};
  42575. serializationObject.geometries.boxes = [];
  42576. serializationObject.geometries.spheres = [];
  42577. serializationObject.geometries.cylinders = [];
  42578. serializationObject.geometries.toruses = [];
  42579. serializationObject.geometries.grounds = [];
  42580. serializationObject.geometries.planes = [];
  42581. serializationObject.geometries.torusKnots = [];
  42582. serializationObject.geometries.vertexData = [];
  42583. }
  42584. serializeGeometry(geometry, serializationObject.geometries);
  42585. }
  42586. // Skeletons
  42587. if (mesh.skeleton) {
  42588. serializationObject.skeletons = serializationObject.skeletons || [];
  42589. serializationObject.skeletons.push(mesh.skeleton.serialize());
  42590. }
  42591. //serialize the actual mesh
  42592. serializationObject.meshes = serializationObject.meshes || [];
  42593. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42594. }
  42595. };
  42596. var SceneSerializer = (function () {
  42597. function SceneSerializer() {
  42598. }
  42599. SceneSerializer.ClearCache = function () {
  42600. serializedGeometries = [];
  42601. };
  42602. SceneSerializer.Serialize = function (scene) {
  42603. var serializationObject = {};
  42604. // Scene
  42605. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  42606. serializationObject.autoClear = scene.autoClear;
  42607. serializationObject.clearColor = scene.clearColor.asArray();
  42608. serializationObject.ambientColor = scene.ambientColor.asArray();
  42609. serializationObject.gravity = scene.gravity.asArray();
  42610. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  42611. serializationObject.workerCollisions = scene.workerCollisions;
  42612. // Fog
  42613. if (scene.fogMode && scene.fogMode !== 0) {
  42614. serializationObject.fogMode = scene.fogMode;
  42615. serializationObject.fogColor = scene.fogColor.asArray();
  42616. serializationObject.fogStart = scene.fogStart;
  42617. serializationObject.fogEnd = scene.fogEnd;
  42618. serializationObject.fogDensity = scene.fogDensity;
  42619. }
  42620. //Physics
  42621. if (scene.isPhysicsEnabled()) {
  42622. serializationObject.physicsEnabled = true;
  42623. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  42624. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  42625. }
  42626. // Metadata
  42627. if (scene.metadata) {
  42628. serializationObject.metadata = scene.metadata;
  42629. }
  42630. // Lights
  42631. serializationObject.lights = [];
  42632. var index;
  42633. var light;
  42634. for (index = 0; index < scene.lights.length; index++) {
  42635. light = scene.lights[index];
  42636. if (!light.doNotSerialize) {
  42637. serializationObject.lights.push(light.serialize());
  42638. }
  42639. }
  42640. // Cameras
  42641. serializationObject.cameras = [];
  42642. for (index = 0; index < scene.cameras.length; index++) {
  42643. var camera = scene.cameras[index];
  42644. if (!camera.doNotSerialize) {
  42645. serializationObject.cameras.push(camera.serialize());
  42646. }
  42647. }
  42648. if (scene.activeCamera) {
  42649. serializationObject.activeCameraID = scene.activeCamera.id;
  42650. }
  42651. // Animations
  42652. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  42653. // Materials
  42654. serializationObject.materials = [];
  42655. serializationObject.multiMaterials = [];
  42656. var material;
  42657. for (index = 0; index < scene.materials.length; index++) {
  42658. material = scene.materials[index];
  42659. if (!material.doNotSerialize) {
  42660. serializationObject.materials.push(material.serialize());
  42661. }
  42662. }
  42663. // MultiMaterials
  42664. serializationObject.multiMaterials = [];
  42665. for (index = 0; index < scene.multiMaterials.length; index++) {
  42666. var multiMaterial = scene.multiMaterials[index];
  42667. serializationObject.multiMaterials.push(multiMaterial.serialize());
  42668. }
  42669. // Skeletons
  42670. serializationObject.skeletons = [];
  42671. for (index = 0; index < scene.skeletons.length; index++) {
  42672. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  42673. }
  42674. // Geometries
  42675. serializationObject.geometries = {};
  42676. serializationObject.geometries.boxes = [];
  42677. serializationObject.geometries.spheres = [];
  42678. serializationObject.geometries.cylinders = [];
  42679. serializationObject.geometries.toruses = [];
  42680. serializationObject.geometries.grounds = [];
  42681. serializationObject.geometries.planes = [];
  42682. serializationObject.geometries.torusKnots = [];
  42683. serializationObject.geometries.vertexData = [];
  42684. serializedGeometries = [];
  42685. var geometries = scene.getGeometries();
  42686. for (index = 0; index < geometries.length; index++) {
  42687. var geometry = geometries[index];
  42688. if (geometry.isReady()) {
  42689. serializeGeometry(geometry, serializationObject.geometries);
  42690. }
  42691. }
  42692. // Meshes
  42693. serializationObject.meshes = [];
  42694. for (index = 0; index < scene.meshes.length; index++) {
  42695. var abstractMesh = scene.meshes[index];
  42696. if (abstractMesh instanceof BABYLON.Mesh) {
  42697. var mesh = abstractMesh;
  42698. if (!mesh.doNotSerialize) {
  42699. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42700. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42701. }
  42702. }
  42703. }
  42704. }
  42705. // Particles Systems
  42706. serializationObject.particleSystems = [];
  42707. for (index = 0; index < scene.particleSystems.length; index++) {
  42708. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  42709. }
  42710. // Lens flares
  42711. serializationObject.lensFlareSystems = [];
  42712. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  42713. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  42714. }
  42715. // Shadows
  42716. serializationObject.shadowGenerators = [];
  42717. for (index = 0; index < scene.lights.length; index++) {
  42718. light = scene.lights[index];
  42719. var shadowGenerator = light.getShadowGenerator();
  42720. // Only support serialization for official generator so far.
  42721. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  42722. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  42723. }
  42724. }
  42725. // Action Manager
  42726. if (scene.actionManager) {
  42727. serializationObject.actions = scene.actionManager.serialize("scene");
  42728. }
  42729. // Audio
  42730. serializationObject.sounds = [];
  42731. for (index = 0; index < scene.soundTracks.length; index++) {
  42732. var soundtrack = scene.soundTracks[index];
  42733. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  42734. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  42735. }
  42736. }
  42737. return serializationObject;
  42738. };
  42739. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  42740. if (withParents === void 0) { withParents = false; }
  42741. if (withChildren === void 0) { withChildren = false; }
  42742. var serializationObject = {};
  42743. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  42744. if (withParents || withChildren) {
  42745. //deliberate for loop! not for each, appended should be processed as well.
  42746. for (var i = 0; i < toSerialize.length; ++i) {
  42747. if (withChildren) {
  42748. toSerialize[i].getDescendants().forEach(function (node) {
  42749. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  42750. toSerialize.push(node);
  42751. }
  42752. });
  42753. }
  42754. //make sure the array doesn't contain the object already
  42755. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  42756. toSerialize.push(toSerialize[i].parent);
  42757. }
  42758. }
  42759. }
  42760. toSerialize.forEach(function (mesh) {
  42761. finalizeSingleMesh(mesh, serializationObject);
  42762. });
  42763. return serializationObject;
  42764. };
  42765. return SceneSerializer;
  42766. }());
  42767. BABYLON.SceneSerializer = SceneSerializer;
  42768. })(BABYLON || (BABYLON = {}));
  42769. //# sourceMappingURL=babylon.sceneSerializer.js.map
  42770. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  42771. // Huge respect for a such great lib.
  42772. // Earcut license:
  42773. // Copyright (c) 2016, Mapbox
  42774. //
  42775. // Permission to use, copy, modify, and/or distribute this software for any purpose
  42776. // with or without fee is hereby granted, provided that the above copyright notice
  42777. // and this permission notice appear in all copies.
  42778. //
  42779. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  42780. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  42781. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  42782. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  42783. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  42784. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  42785. // THIS SOFTWARE.
  42786. var Earcut;
  42787. (function (Earcut) {
  42788. /**
  42789. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  42790. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  42791. * @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).
  42792. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  42793. */
  42794. function earcut(data, holeIndices, dim) {
  42795. dim = dim || 2;
  42796. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  42797. if (!outerNode)
  42798. return triangles;
  42799. var minX, minY, maxX, maxY, x, y, size;
  42800. if (hasHoles)
  42801. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  42802. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  42803. if (data.length > 80 * dim) {
  42804. minX = maxX = data[0];
  42805. minY = maxY = data[1];
  42806. for (var i = dim; i < outerLen; i += dim) {
  42807. x = data[i];
  42808. y = data[i + 1];
  42809. if (x < minX)
  42810. minX = x;
  42811. if (y < minY)
  42812. minY = y;
  42813. if (x > maxX)
  42814. maxX = x;
  42815. if (y > maxY)
  42816. maxY = y;
  42817. }
  42818. // minX, minY and size are later used to transform coords into integers for z-order calculation
  42819. size = Math.max(maxX - minX, maxY - minY);
  42820. }
  42821. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  42822. return triangles;
  42823. }
  42824. Earcut.earcut = earcut;
  42825. // create a circular doubly linked list from polygon points in the specified winding order
  42826. function linkedList(data, start, end, dim, clockwise) {
  42827. var i, last;
  42828. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  42829. for (i = start; i < end; i += dim)
  42830. last = insertNode(i, data[i], data[i + 1], last);
  42831. }
  42832. else {
  42833. for (i = end - dim; i >= start; i -= dim)
  42834. last = insertNode(i, data[i], data[i + 1], last);
  42835. }
  42836. if (last && equals(last, last.next)) {
  42837. removeNode(last);
  42838. last = last.next;
  42839. }
  42840. return last;
  42841. }
  42842. // eliminate colinear or duplicate points
  42843. function filterPoints(start, end) {
  42844. if (!start)
  42845. return start;
  42846. if (!end)
  42847. end = start;
  42848. var p = start, again;
  42849. do {
  42850. again = false;
  42851. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  42852. removeNode(p);
  42853. p = end = p.prev;
  42854. if (p === p.next)
  42855. return null;
  42856. again = true;
  42857. }
  42858. else {
  42859. p = p.next;
  42860. }
  42861. } while (again || p !== end);
  42862. return end;
  42863. }
  42864. // main ear slicing loop which triangulates a polygon (given as a linked list)
  42865. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  42866. if (!ear)
  42867. return;
  42868. // interlink polygon nodes in z-order
  42869. if (!pass && size)
  42870. indexCurve(ear, minX, minY, size);
  42871. var stop = ear, prev, next;
  42872. // iterate through ears, slicing them one by one
  42873. while (ear.prev !== ear.next) {
  42874. prev = ear.prev;
  42875. next = ear.next;
  42876. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  42877. // cut off the triangle
  42878. triangles.push(prev.i / dim);
  42879. triangles.push(ear.i / dim);
  42880. triangles.push(next.i / dim);
  42881. removeNode(ear);
  42882. // skipping the next vertice leads to less sliver triangles
  42883. ear = next.next;
  42884. stop = next.next;
  42885. continue;
  42886. }
  42887. ear = next;
  42888. // if we looped through the whole remaining polygon and can't find any more ears
  42889. if (ear === stop) {
  42890. // try filtering points and slicing again
  42891. if (!pass) {
  42892. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  42893. }
  42894. else if (pass === 1) {
  42895. ear = cureLocalIntersections(ear, triangles, dim);
  42896. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  42897. }
  42898. else if (pass === 2) {
  42899. splitEarcut(ear, triangles, dim, minX, minY, size);
  42900. }
  42901. break;
  42902. }
  42903. }
  42904. }
  42905. // check whether a polygon node forms a valid ear with adjacent nodes
  42906. function isEar(ear) {
  42907. var a = ear.prev, b = ear, c = ear.next;
  42908. if (area(a, b, c) >= 0)
  42909. return false; // reflex, can't be an ear
  42910. // now make sure we don't have other points inside the potential ear
  42911. var p = ear.next.next;
  42912. while (p !== ear.prev) {
  42913. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42914. area(p.prev, p, p.next) >= 0)
  42915. return false;
  42916. p = p.next;
  42917. }
  42918. return true;
  42919. }
  42920. function isEarHashed(ear, minX, minY, size) {
  42921. var a = ear.prev, b = ear, c = ear.next;
  42922. if (area(a, b, c) >= 0)
  42923. return false; // reflex, can't be an ear
  42924. // triangle bbox; min & max are calculated like this for speed
  42925. 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);
  42926. // z-order range for the current triangle bbox;
  42927. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  42928. // first look for points inside the triangle in increasing z-order
  42929. var p = ear.nextZ;
  42930. while (p && p.z <= maxZ) {
  42931. if (p !== ear.prev &&
  42932. p !== ear.next &&
  42933. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42934. area(p.prev, p, p.next) >= 0)
  42935. return false;
  42936. p = p.nextZ;
  42937. }
  42938. // then look for points in decreasing z-order
  42939. p = ear.prevZ;
  42940. while (p && p.z >= minZ) {
  42941. if (p !== ear.prev &&
  42942. p !== ear.next &&
  42943. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42944. area(p.prev, p, p.next) >= 0)
  42945. return false;
  42946. p = p.prevZ;
  42947. }
  42948. return true;
  42949. }
  42950. // go through all polygon nodes and cure small local self-intersections
  42951. function cureLocalIntersections(start, triangles, dim) {
  42952. var p = start;
  42953. do {
  42954. var a = p.prev, b = p.next.next;
  42955. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  42956. triangles.push(a.i / dim);
  42957. triangles.push(p.i / dim);
  42958. triangles.push(b.i / dim);
  42959. // remove two nodes involved
  42960. removeNode(p);
  42961. removeNode(p.next);
  42962. p = start = b;
  42963. }
  42964. p = p.next;
  42965. } while (p !== start);
  42966. return p;
  42967. }
  42968. // try splitting polygon into two and triangulate them independently
  42969. function splitEarcut(start, triangles, dim, minX, minY, size) {
  42970. // look for a valid diagonal that divides the polygon into two
  42971. var a = start;
  42972. do {
  42973. var b = a.next.next;
  42974. while (b !== a.prev) {
  42975. if (a.i !== b.i && isValidDiagonal(a, b)) {
  42976. // split the polygon in two by the diagonal
  42977. var c = splitPolygon(a, b);
  42978. // filter colinear points around the cuts
  42979. a = filterPoints(a, a.next);
  42980. c = filterPoints(c, c.next);
  42981. // run earcut on each half
  42982. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  42983. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  42984. return;
  42985. }
  42986. b = b.next;
  42987. }
  42988. a = a.next;
  42989. } while (a !== start);
  42990. }
  42991. // link every hole into the outer loop, producing a single-ring polygon without holes
  42992. function eliminateHoles(data, holeIndices, outerNode, dim) {
  42993. var queue = [], i, len, start, end, list;
  42994. for (i = 0, len = holeIndices.length; i < len; i++) {
  42995. start = holeIndices[i] * dim;
  42996. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  42997. list = linkedList(data, start, end, dim, false);
  42998. if (list === list.next)
  42999. list.steiner = true;
  43000. queue.push(getLeftmost(list));
  43001. }
  43002. queue.sort(compareX);
  43003. // process holes from left to right
  43004. for (i = 0; i < queue.length; i++) {
  43005. eliminateHole(queue[i], outerNode);
  43006. outerNode = filterPoints(outerNode, outerNode.next);
  43007. }
  43008. return outerNode;
  43009. }
  43010. function compareX(a, b) {
  43011. return a.x - b.x;
  43012. }
  43013. // find a bridge between vertices that connects hole with an outer ring and and link it
  43014. function eliminateHole(hole, outerNode) {
  43015. outerNode = findHoleBridge(hole, outerNode);
  43016. if (outerNode) {
  43017. var b = splitPolygon(outerNode, hole);
  43018. filterPoints(b, b.next);
  43019. }
  43020. }
  43021. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43022. function findHoleBridge(hole, outerNode) {
  43023. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43024. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43025. // segment's endpoint with lesser x will be potential connection point
  43026. do {
  43027. if (hy <= p.y && hy >= p.next.y) {
  43028. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43029. if (x <= hx && x > qx) {
  43030. qx = x;
  43031. if (x === hx) {
  43032. if (hy === p.y)
  43033. return p;
  43034. if (hy === p.next.y)
  43035. return p.next;
  43036. }
  43037. m = p.x < p.next.x ? p : p.next;
  43038. }
  43039. }
  43040. p = p.next;
  43041. } while (p !== outerNode);
  43042. if (!m)
  43043. return null;
  43044. if (hx === qx)
  43045. return m.prev; // hole touches outer segment; pick lower endpoint
  43046. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43047. // if there are no points found, we have a valid connection;
  43048. // otherwise choose the point of the minimum angle with the ray as connection point
  43049. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43050. p = m.next;
  43051. while (p !== stop) {
  43052. if (hx >= p.x &&
  43053. p.x >= mx &&
  43054. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43055. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43056. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43057. m = p;
  43058. tanMin = tan;
  43059. }
  43060. }
  43061. p = p.next;
  43062. }
  43063. return m;
  43064. }
  43065. // interlink polygon nodes in z-order
  43066. function indexCurve(start, minX, minY, size) {
  43067. var p = start;
  43068. do {
  43069. if (p.z === null)
  43070. p.z = zOrder(p.x, p.y, minX, minY, size);
  43071. p.prevZ = p.prev;
  43072. p.nextZ = p.next;
  43073. p = p.next;
  43074. } while (p !== start);
  43075. p.prevZ.nextZ = null;
  43076. p.prevZ = null;
  43077. sortLinked(p);
  43078. }
  43079. // Simon Tatham's linked list merge sort algorithm
  43080. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43081. function sortLinked(list) {
  43082. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43083. do {
  43084. p = list;
  43085. list = null;
  43086. tail = null;
  43087. numMerges = 0;
  43088. while (p) {
  43089. numMerges++;
  43090. q = p;
  43091. pSize = 0;
  43092. for (i = 0; i < inSize; i++) {
  43093. pSize++;
  43094. q = q.nextZ;
  43095. if (!q)
  43096. break;
  43097. }
  43098. qSize = inSize;
  43099. while (pSize > 0 || (qSize > 0 && q)) {
  43100. if (pSize === 0) {
  43101. e = q;
  43102. q = q.nextZ;
  43103. qSize--;
  43104. }
  43105. else if (qSize === 0 || !q) {
  43106. e = p;
  43107. p = p.nextZ;
  43108. pSize--;
  43109. }
  43110. else if (p.z <= q.z) {
  43111. e = p;
  43112. p = p.nextZ;
  43113. pSize--;
  43114. }
  43115. else {
  43116. e = q;
  43117. q = q.nextZ;
  43118. qSize--;
  43119. }
  43120. if (tail)
  43121. tail.nextZ = e;
  43122. else
  43123. list = e;
  43124. e.prevZ = tail;
  43125. tail = e;
  43126. }
  43127. p = q;
  43128. }
  43129. tail.nextZ = null;
  43130. inSize *= 2;
  43131. } while (numMerges > 1);
  43132. return list;
  43133. }
  43134. // z-order of a point given coords and size of the data bounding box
  43135. function zOrder(x, y, minX, minY, size) {
  43136. // coords are transformed into non-negative 15-bit integer range
  43137. x = 32767 * (x - minX) / size;
  43138. y = 32767 * (y - minY) / size;
  43139. x = (x | (x << 8)) & 0x00FF00FF;
  43140. x = (x | (x << 4)) & 0x0F0F0F0F;
  43141. x = (x | (x << 2)) & 0x33333333;
  43142. x = (x | (x << 1)) & 0x55555555;
  43143. y = (y | (y << 8)) & 0x00FF00FF;
  43144. y = (y | (y << 4)) & 0x0F0F0F0F;
  43145. y = (y | (y << 2)) & 0x33333333;
  43146. y = (y | (y << 1)) & 0x55555555;
  43147. return x | (y << 1);
  43148. }
  43149. // find the leftmost node of a polygon ring
  43150. function getLeftmost(start) {
  43151. var p = start, leftmost = start;
  43152. do {
  43153. if (p.x < leftmost.x)
  43154. leftmost = p;
  43155. p = p.next;
  43156. } while (p !== start);
  43157. return leftmost;
  43158. }
  43159. // check if a point lies within a convex triangle
  43160. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43161. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43162. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43163. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43164. }
  43165. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43166. function isValidDiagonal(a, b) {
  43167. return a.next.i !== b.i &&
  43168. a.prev.i !== b.i &&
  43169. !intersectsPolygon(a, b) &&
  43170. locallyInside(a, b) &&
  43171. locallyInside(b, a) &&
  43172. middleInside(a, b);
  43173. }
  43174. // signed area of a triangle
  43175. function area(p, q, r) {
  43176. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43177. }
  43178. // check if two points are equal
  43179. function equals(p1, p2) {
  43180. return p1.x === p2.x && p1.y === p2.y;
  43181. }
  43182. // check if two segments intersect
  43183. function intersects(p1, q1, p2, q2) {
  43184. if ((equals(p1, q1) && equals(p2, q2)) ||
  43185. (equals(p1, q2) && equals(p2, q1)))
  43186. return true;
  43187. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43188. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43189. }
  43190. // check if a polygon diagonal intersects any polygon segments
  43191. function intersectsPolygon(a, b) {
  43192. var p = a;
  43193. do {
  43194. if (p.i !== a.i &&
  43195. p.next.i !== a.i &&
  43196. p.i !== b.i &&
  43197. p.next.i !== b.i &&
  43198. intersects(p, p.next, a, b))
  43199. return true;
  43200. p = p.next;
  43201. } while (p !== a);
  43202. return false;
  43203. }
  43204. // check if a polygon diagonal is locally inside the polygon
  43205. function locallyInside(a, b) {
  43206. return area(a.prev, a, a.next) < 0
  43207. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43208. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43209. }
  43210. // check if the middle point of a polygon diagonal is inside the polygon
  43211. function middleInside(a, b) {
  43212. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43213. do {
  43214. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43215. inside = !inside;
  43216. p = p.next;
  43217. } while (p !== a);
  43218. return inside;
  43219. }
  43220. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43221. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43222. function splitPolygon(a, b) {
  43223. 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;
  43224. a.next = b;
  43225. b.prev = a;
  43226. a2.next = an;
  43227. an.prev = a2;
  43228. b2.next = a2;
  43229. a2.prev = b2;
  43230. bp.next = b2;
  43231. b2.prev = bp;
  43232. return b2;
  43233. }
  43234. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43235. function insertNode(i, x, y, last) {
  43236. var p = new Node(i, x, y);
  43237. if (!last) {
  43238. p.prev = p;
  43239. p.next = p;
  43240. }
  43241. else {
  43242. p.next = last.next;
  43243. p.prev = last;
  43244. last.next.prev = p;
  43245. last.next = p;
  43246. }
  43247. return p;
  43248. }
  43249. function removeNode(p) {
  43250. p.next.prev = p.prev;
  43251. p.prev.next = p.next;
  43252. if (p.prevZ)
  43253. p.prevZ.nextZ = p.nextZ;
  43254. if (p.nextZ)
  43255. p.nextZ.prevZ = p.prevZ;
  43256. }
  43257. function Node(i, x, y) {
  43258. // vertice index in coordinates array
  43259. this.i = i;
  43260. // vertex coordinates
  43261. this.x = x;
  43262. this.y = y;
  43263. // previous and next vertice nodes in a polygon ring
  43264. this.prev = null;
  43265. this.next = null;
  43266. // z-order curve value
  43267. this.z = null;
  43268. // previous and next nodes in z-order
  43269. this.prevZ = null;
  43270. this.nextZ = null;
  43271. // indicates whether this is a steiner point
  43272. this.steiner = false;
  43273. }
  43274. /**
  43275. * return a percentage difference between the polygon area and its triangulation area;
  43276. * used to verify correctness of triangulation
  43277. */
  43278. function deviation(data, holeIndices, dim, triangles) {
  43279. var hasHoles = holeIndices && holeIndices.length;
  43280. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  43281. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  43282. if (hasHoles) {
  43283. for (var i = 0, len = holeIndices.length; i < len; i++) {
  43284. var start = holeIndices[i] * dim;
  43285. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43286. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  43287. }
  43288. }
  43289. var trianglesArea = 0;
  43290. for (i = 0; i < triangles.length; i += 3) {
  43291. var a = triangles[i] * dim;
  43292. var b = triangles[i + 1] * dim;
  43293. var c = triangles[i + 2] * dim;
  43294. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  43295. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  43296. }
  43297. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  43298. }
  43299. Earcut.deviation = deviation;
  43300. ;
  43301. function signedArea(data, start, end, dim) {
  43302. var sum = 0;
  43303. for (var i = start, j = end - dim; i < end; i += dim) {
  43304. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  43305. j = i;
  43306. }
  43307. return sum;
  43308. }
  43309. /**
  43310. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  43311. */
  43312. function flatten(data) {
  43313. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  43314. for (var i = 0; i < data.length; i++) {
  43315. for (var j = 0; j < data[i].length; j++) {
  43316. for (var d = 0; d < dim; d++)
  43317. result.vertices.push(data[i][j][d]);
  43318. }
  43319. if (i > 0) {
  43320. holeIndex += data[i - 1].length;
  43321. result.holes.push(holeIndex);
  43322. }
  43323. }
  43324. return result;
  43325. }
  43326. Earcut.flatten = flatten;
  43327. ;
  43328. })(Earcut || (Earcut = {}));
  43329. //# sourceMappingURL=babylon.earcut.js.map
  43330. var BABYLON;
  43331. (function (BABYLON) {
  43332. // Unique ID when we import meshes from Babylon to CSG
  43333. var currentCSGMeshId = 0;
  43334. // # class Vertex
  43335. // Represents a vertex of a polygon. Use your own vertex class instead of this
  43336. // one to provide additional features like texture coordinates and vertex
  43337. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  43338. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  43339. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  43340. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  43341. // is not used anywhere else.
  43342. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  43343. var Vertex = (function () {
  43344. function Vertex(pos, normal, uv) {
  43345. this.pos = pos;
  43346. this.normal = normal;
  43347. this.uv = uv;
  43348. }
  43349. Vertex.prototype.clone = function () {
  43350. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43351. };
  43352. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  43353. // orientation of a polygon is flipped.
  43354. Vertex.prototype.flip = function () {
  43355. this.normal = this.normal.scale(-1);
  43356. };
  43357. // Create a new vertex between this vertex and `other` by linearly
  43358. // interpolating all properties using a parameter of `t`. Subclasses should
  43359. // override this to interpolate additional properties.
  43360. Vertex.prototype.interpolate = function (other, t) {
  43361. 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));
  43362. };
  43363. return Vertex;
  43364. }());
  43365. // # class Plane
  43366. // Represents a plane in 3D space.
  43367. var Plane = (function () {
  43368. function Plane(normal, w) {
  43369. this.normal = normal;
  43370. this.w = w;
  43371. }
  43372. Plane.FromPoints = function (a, b, c) {
  43373. var v0 = c.subtract(a);
  43374. var v1 = b.subtract(a);
  43375. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  43376. return null;
  43377. }
  43378. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  43379. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  43380. };
  43381. Plane.prototype.clone = function () {
  43382. return new Plane(this.normal.clone(), this.w);
  43383. };
  43384. Plane.prototype.flip = function () {
  43385. this.normal.scaleInPlace(-1);
  43386. this.w = -this.w;
  43387. };
  43388. // Split `polygon` by this plane if needed, then put the polygon or polygon
  43389. // fragments in the appropriate lists. Coplanar polygons go into either
  43390. // `coplanarFront` or `coplanarBack` depending on their orientation with
  43391. // respect to this plane. Polygons in front or in back of this plane go into
  43392. // either `front` or `back`.
  43393. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  43394. var COPLANAR = 0;
  43395. var FRONT = 1;
  43396. var BACK = 2;
  43397. var SPANNING = 3;
  43398. // Classify each point as well as the entire polygon into one of the above
  43399. // four classes.
  43400. var polygonType = 0;
  43401. var types = [];
  43402. var i;
  43403. var t;
  43404. for (i = 0; i < polygon.vertices.length; i++) {
  43405. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  43406. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  43407. polygonType |= type;
  43408. types.push(type);
  43409. }
  43410. // Put the polygon in the correct list, splitting it when necessary.
  43411. switch (polygonType) {
  43412. case COPLANAR:
  43413. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  43414. break;
  43415. case FRONT:
  43416. front.push(polygon);
  43417. break;
  43418. case BACK:
  43419. back.push(polygon);
  43420. break;
  43421. case SPANNING:
  43422. var f = [], b = [];
  43423. for (i = 0; i < polygon.vertices.length; i++) {
  43424. var j = (i + 1) % polygon.vertices.length;
  43425. var ti = types[i], tj = types[j];
  43426. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  43427. if (ti !== BACK)
  43428. f.push(vi);
  43429. if (ti !== FRONT)
  43430. b.push(ti !== BACK ? vi.clone() : vi);
  43431. if ((ti | tj) === SPANNING) {
  43432. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  43433. var v = vi.interpolate(vj, t);
  43434. f.push(v);
  43435. b.push(v.clone());
  43436. }
  43437. }
  43438. var poly;
  43439. if (f.length >= 3) {
  43440. poly = new Polygon(f, polygon.shared);
  43441. if (poly.plane)
  43442. front.push(poly);
  43443. }
  43444. if (b.length >= 3) {
  43445. poly = new Polygon(b, polygon.shared);
  43446. if (poly.plane)
  43447. back.push(poly);
  43448. }
  43449. break;
  43450. }
  43451. };
  43452. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  43453. // point is on the plane.
  43454. Plane.EPSILON = 1e-5;
  43455. return Plane;
  43456. }());
  43457. // # class Polygon
  43458. // Represents a convex polygon. The vertices used to initialize a polygon must
  43459. // be coplanar and form a convex loop.
  43460. //
  43461. // Each convex polygon has a `shared` property, which is shared between all
  43462. // polygons that are clones of each other or were split from the same polygon.
  43463. // This can be used to define per-polygon properties (such as surface color).
  43464. var Polygon = (function () {
  43465. function Polygon(vertices, shared) {
  43466. this.vertices = vertices;
  43467. this.shared = shared;
  43468. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  43469. }
  43470. Polygon.prototype.clone = function () {
  43471. var vertices = this.vertices.map(function (v) { return v.clone(); });
  43472. return new Polygon(vertices, this.shared);
  43473. };
  43474. Polygon.prototype.flip = function () {
  43475. this.vertices.reverse().map(function (v) { v.flip(); });
  43476. this.plane.flip();
  43477. };
  43478. return Polygon;
  43479. }());
  43480. // # class Node
  43481. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  43482. // by picking a polygon to split along. That polygon (and all other coplanar
  43483. // polygons) are added directly to that node and the other polygons are added to
  43484. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  43485. // no distinction between internal and leaf nodes.
  43486. var Node = (function () {
  43487. function Node(polygons) {
  43488. this.plane = null;
  43489. this.front = null;
  43490. this.back = null;
  43491. this.polygons = [];
  43492. if (polygons) {
  43493. this.build(polygons);
  43494. }
  43495. }
  43496. Node.prototype.clone = function () {
  43497. var node = new Node();
  43498. node.plane = this.plane && this.plane.clone();
  43499. node.front = this.front && this.front.clone();
  43500. node.back = this.back && this.back.clone();
  43501. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  43502. return node;
  43503. };
  43504. // Convert solid space to empty space and empty space to solid space.
  43505. Node.prototype.invert = function () {
  43506. for (var i = 0; i < this.polygons.length; i++) {
  43507. this.polygons[i].flip();
  43508. }
  43509. if (this.plane) {
  43510. this.plane.flip();
  43511. }
  43512. if (this.front) {
  43513. this.front.invert();
  43514. }
  43515. if (this.back) {
  43516. this.back.invert();
  43517. }
  43518. var temp = this.front;
  43519. this.front = this.back;
  43520. this.back = temp;
  43521. };
  43522. // Recursively remove all polygons in `polygons` that are inside this BSP
  43523. // tree.
  43524. Node.prototype.clipPolygons = function (polygons) {
  43525. if (!this.plane)
  43526. return polygons.slice();
  43527. var front = [], back = [];
  43528. for (var i = 0; i < polygons.length; i++) {
  43529. this.plane.splitPolygon(polygons[i], front, back, front, back);
  43530. }
  43531. if (this.front) {
  43532. front = this.front.clipPolygons(front);
  43533. }
  43534. if (this.back) {
  43535. back = this.back.clipPolygons(back);
  43536. }
  43537. else {
  43538. back = [];
  43539. }
  43540. return front.concat(back);
  43541. };
  43542. // Remove all polygons in this BSP tree that are inside the other BSP tree
  43543. // `bsp`.
  43544. Node.prototype.clipTo = function (bsp) {
  43545. this.polygons = bsp.clipPolygons(this.polygons);
  43546. if (this.front)
  43547. this.front.clipTo(bsp);
  43548. if (this.back)
  43549. this.back.clipTo(bsp);
  43550. };
  43551. // Return a list of all polygons in this BSP tree.
  43552. Node.prototype.allPolygons = function () {
  43553. var polygons = this.polygons.slice();
  43554. if (this.front)
  43555. polygons = polygons.concat(this.front.allPolygons());
  43556. if (this.back)
  43557. polygons = polygons.concat(this.back.allPolygons());
  43558. return polygons;
  43559. };
  43560. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  43561. // new polygons are filtered down to the bottom of the tree and become new
  43562. // nodes there. Each set of polygons is partitioned using the first polygon
  43563. // (no heuristic is used to pick a good split).
  43564. Node.prototype.build = function (polygons) {
  43565. if (!polygons.length)
  43566. return;
  43567. if (!this.plane)
  43568. this.plane = polygons[0].plane.clone();
  43569. var front = [], back = [];
  43570. for (var i = 0; i < polygons.length; i++) {
  43571. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  43572. }
  43573. if (front.length) {
  43574. if (!this.front)
  43575. this.front = new Node();
  43576. this.front.build(front);
  43577. }
  43578. if (back.length) {
  43579. if (!this.back)
  43580. this.back = new Node();
  43581. this.back.build(back);
  43582. }
  43583. };
  43584. return Node;
  43585. }());
  43586. var CSG = (function () {
  43587. function CSG() {
  43588. this.polygons = new Array();
  43589. }
  43590. // Convert BABYLON.Mesh to BABYLON.CSG
  43591. CSG.FromMesh = function (mesh) {
  43592. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  43593. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  43594. if (mesh instanceof BABYLON.Mesh) {
  43595. mesh.computeWorldMatrix(true);
  43596. matrix = mesh.getWorldMatrix();
  43597. meshPosition = mesh.position.clone();
  43598. meshRotation = mesh.rotation.clone();
  43599. if (mesh.rotationQuaternion) {
  43600. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  43601. }
  43602. meshScaling = mesh.scaling.clone();
  43603. }
  43604. else {
  43605. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  43606. }
  43607. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43608. var subMeshes = mesh.subMeshes;
  43609. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  43610. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  43611. vertices = [];
  43612. for (var j = 0; j < 3; j++) {
  43613. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  43614. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  43615. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  43616. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  43617. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  43618. vertex = new Vertex(position, normal, uv);
  43619. vertices.push(vertex);
  43620. }
  43621. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  43622. // To handle the case of degenerated triangle
  43623. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  43624. if (polygon.plane)
  43625. polygons.push(polygon);
  43626. }
  43627. }
  43628. var csg = CSG.FromPolygons(polygons);
  43629. csg.matrix = matrix;
  43630. csg.position = meshPosition;
  43631. csg.rotation = meshRotation;
  43632. csg.scaling = meshScaling;
  43633. csg.rotationQuaternion = meshRotationQuaternion;
  43634. currentCSGMeshId++;
  43635. return csg;
  43636. };
  43637. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  43638. CSG.FromPolygons = function (polygons) {
  43639. var csg = new CSG();
  43640. csg.polygons = polygons;
  43641. return csg;
  43642. };
  43643. CSG.prototype.clone = function () {
  43644. var csg = new CSG();
  43645. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  43646. csg.copyTransformAttributes(this);
  43647. return csg;
  43648. };
  43649. CSG.prototype.toPolygons = function () {
  43650. return this.polygons;
  43651. };
  43652. CSG.prototype.union = function (csg) {
  43653. var a = new Node(this.clone().polygons);
  43654. var b = new Node(csg.clone().polygons);
  43655. a.clipTo(b);
  43656. b.clipTo(a);
  43657. b.invert();
  43658. b.clipTo(a);
  43659. b.invert();
  43660. a.build(b.allPolygons());
  43661. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43662. };
  43663. CSG.prototype.unionInPlace = function (csg) {
  43664. var a = new Node(this.polygons);
  43665. var b = new Node(csg.polygons);
  43666. a.clipTo(b);
  43667. b.clipTo(a);
  43668. b.invert();
  43669. b.clipTo(a);
  43670. b.invert();
  43671. a.build(b.allPolygons());
  43672. this.polygons = a.allPolygons();
  43673. };
  43674. CSG.prototype.subtract = function (csg) {
  43675. var a = new Node(this.clone().polygons);
  43676. var b = new Node(csg.clone().polygons);
  43677. a.invert();
  43678. a.clipTo(b);
  43679. b.clipTo(a);
  43680. b.invert();
  43681. b.clipTo(a);
  43682. b.invert();
  43683. a.build(b.allPolygons());
  43684. a.invert();
  43685. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43686. };
  43687. CSG.prototype.subtractInPlace = function (csg) {
  43688. var a = new Node(this.polygons);
  43689. var b = new Node(csg.polygons);
  43690. a.invert();
  43691. a.clipTo(b);
  43692. b.clipTo(a);
  43693. b.invert();
  43694. b.clipTo(a);
  43695. b.invert();
  43696. a.build(b.allPolygons());
  43697. a.invert();
  43698. this.polygons = a.allPolygons();
  43699. };
  43700. CSG.prototype.intersect = function (csg) {
  43701. var a = new Node(this.clone().polygons);
  43702. var b = new Node(csg.clone().polygons);
  43703. a.invert();
  43704. b.clipTo(a);
  43705. b.invert();
  43706. a.clipTo(b);
  43707. b.clipTo(a);
  43708. a.build(b.allPolygons());
  43709. a.invert();
  43710. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43711. };
  43712. CSG.prototype.intersectInPlace = function (csg) {
  43713. var a = new Node(this.polygons);
  43714. var b = new Node(csg.polygons);
  43715. a.invert();
  43716. b.clipTo(a);
  43717. b.invert();
  43718. a.clipTo(b);
  43719. b.clipTo(a);
  43720. a.build(b.allPolygons());
  43721. a.invert();
  43722. this.polygons = a.allPolygons();
  43723. };
  43724. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  43725. // not modified.
  43726. CSG.prototype.inverse = function () {
  43727. var csg = this.clone();
  43728. csg.inverseInPlace();
  43729. return csg;
  43730. };
  43731. CSG.prototype.inverseInPlace = function () {
  43732. this.polygons.map(function (p) { p.flip(); });
  43733. };
  43734. // This is used to keep meshes transformations so they can be restored
  43735. // when we build back a Babylon Mesh
  43736. // NB : All CSG operations are performed in world coordinates
  43737. CSG.prototype.copyTransformAttributes = function (csg) {
  43738. this.matrix = csg.matrix;
  43739. this.position = csg.position;
  43740. this.rotation = csg.rotation;
  43741. this.scaling = csg.scaling;
  43742. this.rotationQuaternion = csg.rotationQuaternion;
  43743. return this;
  43744. };
  43745. // Build Raw mesh from CSG
  43746. // Coordinates here are in world space
  43747. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  43748. var matrix = this.matrix.clone();
  43749. matrix.invert();
  43750. 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;
  43751. if (keepSubMeshes) {
  43752. // Sort Polygons, since subMeshes are indices range
  43753. polygons.sort(function (a, b) {
  43754. if (a.shared.meshId === b.shared.meshId) {
  43755. return a.shared.subMeshId - b.shared.subMeshId;
  43756. }
  43757. else {
  43758. return a.shared.meshId - b.shared.meshId;
  43759. }
  43760. });
  43761. }
  43762. for (var i = 0, il = polygons.length; i < il; i++) {
  43763. polygon = polygons[i];
  43764. // Building SubMeshes
  43765. if (!subMesh_dict[polygon.shared.meshId]) {
  43766. subMesh_dict[polygon.shared.meshId] = {};
  43767. }
  43768. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  43769. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  43770. indexStart: +Infinity,
  43771. indexEnd: -Infinity,
  43772. materialIndex: polygon.shared.materialIndex
  43773. };
  43774. }
  43775. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  43776. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  43777. polygonIndices[0] = 0;
  43778. polygonIndices[1] = j - 1;
  43779. polygonIndices[2] = j;
  43780. for (var k = 0; k < 3; k++) {
  43781. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  43782. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  43783. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  43784. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  43785. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  43786. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  43787. // Check if 2 points can be merged
  43788. if (!(typeof vertex_idx !== 'undefined' &&
  43789. normals[vertex_idx * 3] === localNormal.x &&
  43790. normals[vertex_idx * 3 + 1] === localNormal.y &&
  43791. normals[vertex_idx * 3 + 2] === localNormal.z &&
  43792. uvs[vertex_idx * 2] === uv.x &&
  43793. uvs[vertex_idx * 2 + 1] === uv.y)) {
  43794. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  43795. uvs.push(uv.x, uv.y);
  43796. normals.push(normal.x, normal.y, normal.z);
  43797. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  43798. }
  43799. indices.push(vertex_idx);
  43800. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  43801. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  43802. currentIndex++;
  43803. }
  43804. }
  43805. }
  43806. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  43807. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  43808. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  43809. mesh.setIndices(indices);
  43810. if (keepSubMeshes) {
  43811. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  43812. var materialIndexOffset = 0, materialMaxIndex;
  43813. mesh.subMeshes = new Array();
  43814. for (var m in subMesh_dict) {
  43815. materialMaxIndex = -1;
  43816. for (var sm in subMesh_dict[m]) {
  43817. subMesh_obj = subMesh_dict[m][sm];
  43818. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  43819. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  43820. }
  43821. materialIndexOffset += ++materialMaxIndex;
  43822. }
  43823. }
  43824. return mesh;
  43825. };
  43826. // Build Mesh from CSG taking material and transforms into account
  43827. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  43828. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  43829. mesh.material = material;
  43830. mesh.position.copyFrom(this.position);
  43831. mesh.rotation.copyFrom(this.rotation);
  43832. if (this.rotationQuaternion) {
  43833. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  43834. }
  43835. mesh.scaling.copyFrom(this.scaling);
  43836. mesh.computeWorldMatrix(true);
  43837. return mesh;
  43838. };
  43839. return CSG;
  43840. }());
  43841. BABYLON.CSG = CSG;
  43842. })(BABYLON || (BABYLON = {}));
  43843. //# sourceMappingURL=babylon.csg.js.map
  43844. var BABYLON;
  43845. (function (BABYLON) {
  43846. var VRDistortionCorrectionPostProcess = (function (_super) {
  43847. __extends(VRDistortionCorrectionPostProcess, _super);
  43848. //ANY
  43849. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  43850. var _this = this;
  43851. _super.call(this, name, "vrDistortionCorrection", [
  43852. 'LensCenter',
  43853. 'Scale',
  43854. 'ScaleIn',
  43855. 'HmdWarpParam'
  43856. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  43857. this._isRightEye = isRightEye;
  43858. this._distortionFactors = vrMetrics.distortionK;
  43859. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  43860. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  43861. this.onSizeChangedObservable.add(function () {
  43862. _this.aspectRatio = _this.width * .5 / _this.height;
  43863. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  43864. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  43865. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  43866. });
  43867. this.onApplyObservable.add(function (effect) {
  43868. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  43869. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  43870. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  43871. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  43872. });
  43873. }
  43874. return VRDistortionCorrectionPostProcess;
  43875. }(BABYLON.PostProcess));
  43876. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  43877. })(BABYLON || (BABYLON = {}));
  43878. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  43879. // Mainly based on these 2 articles :
  43880. // 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
  43881. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  43882. var BABYLON;
  43883. (function (BABYLON) {
  43884. (function (JoystickAxis) {
  43885. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  43886. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  43887. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  43888. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  43889. var JoystickAxis = BABYLON.JoystickAxis;
  43890. var VirtualJoystick = (function () {
  43891. function VirtualJoystick(leftJoystick) {
  43892. var _this = this;
  43893. if (leftJoystick) {
  43894. this._leftJoystick = true;
  43895. }
  43896. else {
  43897. this._leftJoystick = false;
  43898. }
  43899. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  43900. VirtualJoystick._globalJoystickIndex++;
  43901. // By default left & right arrow keys are moving the X
  43902. // and up & down keys are moving the Y
  43903. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  43904. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  43905. this.reverseLeftRight = false;
  43906. this.reverseUpDown = false;
  43907. // collections of pointers
  43908. this._touches = new BABYLON.StringDictionary();
  43909. this.deltaPosition = BABYLON.Vector3.Zero();
  43910. this._joystickSensibility = 25;
  43911. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  43912. this._rotationSpeed = 25;
  43913. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  43914. this._rotateOnAxisRelativeToMesh = false;
  43915. this._onResize = function (evt) {
  43916. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  43917. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  43918. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  43919. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  43920. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  43921. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  43922. };
  43923. // injecting a canvas element on top of the canvas 3D game
  43924. if (!VirtualJoystick.vjCanvas) {
  43925. window.addEventListener("resize", this._onResize, false);
  43926. VirtualJoystick.vjCanvas = document.createElement("canvas");
  43927. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  43928. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  43929. VirtualJoystick.vjCanvas.width = window.innerWidth;
  43930. VirtualJoystick.vjCanvas.height = window.innerHeight;
  43931. VirtualJoystick.vjCanvas.style.width = "100%";
  43932. VirtualJoystick.vjCanvas.style.height = "100%";
  43933. VirtualJoystick.vjCanvas.style.position = "absolute";
  43934. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  43935. VirtualJoystick.vjCanvas.style.top = "0px";
  43936. VirtualJoystick.vjCanvas.style.left = "0px";
  43937. VirtualJoystick.vjCanvas.style.zIndex = "5";
  43938. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  43939. // Support for jQuery PEP polyfill
  43940. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  43941. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  43942. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  43943. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  43944. document.body.appendChild(VirtualJoystick.vjCanvas);
  43945. }
  43946. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  43947. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  43948. this.pressed = false;
  43949. // default joystick color
  43950. this._joystickColor = "cyan";
  43951. this._joystickPointerID = -1;
  43952. // current joystick position
  43953. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  43954. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  43955. // origin joystick position
  43956. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  43957. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  43958. this._onPointerDownHandlerRef = function (evt) {
  43959. _this._onPointerDown(evt);
  43960. };
  43961. this._onPointerMoveHandlerRef = function (evt) {
  43962. _this._onPointerMove(evt);
  43963. };
  43964. this._onPointerOutHandlerRef = function (evt) {
  43965. _this._onPointerUp(evt);
  43966. };
  43967. this._onPointerUpHandlerRef = function (evt) {
  43968. _this._onPointerUp(evt);
  43969. };
  43970. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  43971. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  43972. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  43973. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  43974. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  43975. evt.preventDefault(); // Disables system menu
  43976. }, false);
  43977. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  43978. }
  43979. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  43980. this._joystickSensibility = newJoystickSensibility;
  43981. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  43982. };
  43983. VirtualJoystick.prototype._onPointerDown = function (e) {
  43984. var positionOnScreenCondition;
  43985. e.preventDefault();
  43986. if (this._leftJoystick === true) {
  43987. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  43988. }
  43989. else {
  43990. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  43991. }
  43992. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  43993. // First contact will be dedicated to the virtual joystick
  43994. this._joystickPointerID = e.pointerId;
  43995. this._joystickPointerStartPos.x = e.clientX;
  43996. this._joystickPointerStartPos.y = e.clientY;
  43997. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  43998. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  43999. this._deltaJoystickVector.x = 0;
  44000. this._deltaJoystickVector.y = 0;
  44001. this.pressed = true;
  44002. this._touches.add(e.pointerId.toString(), e);
  44003. }
  44004. else {
  44005. // You can only trigger the action buttons with a joystick declared
  44006. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44007. this._action();
  44008. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44009. }
  44010. }
  44011. };
  44012. VirtualJoystick.prototype._onPointerMove = function (e) {
  44013. // If the current pointer is the one associated to the joystick (first touch contact)
  44014. if (this._joystickPointerID == e.pointerId) {
  44015. this._joystickPointerPos.x = e.clientX;
  44016. this._joystickPointerPos.y = e.clientY;
  44017. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44018. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44019. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44020. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44021. switch (this._axisTargetedByLeftAndRight) {
  44022. case JoystickAxis.X:
  44023. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44024. break;
  44025. case JoystickAxis.Y:
  44026. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44027. break;
  44028. case JoystickAxis.Z:
  44029. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44030. break;
  44031. }
  44032. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44033. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44034. switch (this._axisTargetedByUpAndDown) {
  44035. case JoystickAxis.X:
  44036. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44037. break;
  44038. case JoystickAxis.Y:
  44039. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44040. break;
  44041. case JoystickAxis.Z:
  44042. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44043. break;
  44044. }
  44045. }
  44046. else {
  44047. var data = this._touches.get(e.pointerId.toString());
  44048. if (data) {
  44049. data.x = e.clientX;
  44050. data.y = e.clientY;
  44051. }
  44052. }
  44053. };
  44054. VirtualJoystick.prototype._onPointerUp = function (e) {
  44055. if (this._joystickPointerID == e.pointerId) {
  44056. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  44057. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  44058. this._joystickPointerID = -1;
  44059. this.pressed = false;
  44060. }
  44061. else {
  44062. var touch = this._touches.get(e.pointerId.toString());
  44063. if (touch) {
  44064. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44065. }
  44066. }
  44067. this._deltaJoystickVector.x = 0;
  44068. this._deltaJoystickVector.y = 0;
  44069. this._touches.remove(e.pointerId.toString());
  44070. };
  44071. /**
  44072. * Change the color of the virtual joystick
  44073. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44074. */
  44075. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44076. this._joystickColor = newColor;
  44077. };
  44078. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44079. this._action = action;
  44080. };
  44081. // Define which axis you'd like to control for left & right
  44082. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44083. switch (axis) {
  44084. case JoystickAxis.X:
  44085. case JoystickAxis.Y:
  44086. case JoystickAxis.Z:
  44087. this._axisTargetedByLeftAndRight = axis;
  44088. break;
  44089. default:
  44090. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44091. break;
  44092. }
  44093. };
  44094. // Define which axis you'd like to control for up & down
  44095. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44096. switch (axis) {
  44097. case JoystickAxis.X:
  44098. case JoystickAxis.Y:
  44099. case JoystickAxis.Z:
  44100. this._axisTargetedByUpAndDown = axis;
  44101. break;
  44102. default:
  44103. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44104. break;
  44105. }
  44106. };
  44107. VirtualJoystick.prototype._clearCanvas = function () {
  44108. if (this._leftJoystick) {
  44109. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44110. }
  44111. else {
  44112. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44113. }
  44114. };
  44115. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44116. var _this = this;
  44117. if (this.pressed) {
  44118. this._touches.forEach(function (touch) {
  44119. if (touch.pointerId === _this._joystickPointerID) {
  44120. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44121. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44122. VirtualJoystick.vjCanvasContext.beginPath();
  44123. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44124. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44125. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44126. VirtualJoystick.vjCanvasContext.stroke();
  44127. VirtualJoystick.vjCanvasContext.closePath();
  44128. VirtualJoystick.vjCanvasContext.beginPath();
  44129. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44130. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44131. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44132. VirtualJoystick.vjCanvasContext.stroke();
  44133. VirtualJoystick.vjCanvasContext.closePath();
  44134. VirtualJoystick.vjCanvasContext.beginPath();
  44135. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44136. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44137. VirtualJoystick.vjCanvasContext.stroke();
  44138. VirtualJoystick.vjCanvasContext.closePath();
  44139. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44140. }
  44141. else {
  44142. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44143. VirtualJoystick.vjCanvasContext.beginPath();
  44144. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44145. VirtualJoystick.vjCanvasContext.beginPath();
  44146. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44147. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44148. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44149. VirtualJoystick.vjCanvasContext.stroke();
  44150. VirtualJoystick.vjCanvasContext.closePath();
  44151. touch.prevX = touch.x;
  44152. touch.prevY = touch.y;
  44153. }
  44154. ;
  44155. });
  44156. }
  44157. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44158. };
  44159. VirtualJoystick.prototype.releaseCanvas = function () {
  44160. if (VirtualJoystick.vjCanvas) {
  44161. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44162. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44163. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44164. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44165. window.removeEventListener("resize", this._onResize);
  44166. document.body.removeChild(VirtualJoystick.vjCanvas);
  44167. VirtualJoystick.vjCanvas = null;
  44168. }
  44169. };
  44170. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44171. VirtualJoystick._globalJoystickIndex = 0;
  44172. return VirtualJoystick;
  44173. }());
  44174. BABYLON.VirtualJoystick = VirtualJoystick;
  44175. })(BABYLON || (BABYLON = {}));
  44176. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44177. var BABYLON;
  44178. (function (BABYLON) {
  44179. // We're mainly based on the logic defined into the FreeCamera code
  44180. var VirtualJoysticksCamera = (function (_super) {
  44181. __extends(VirtualJoysticksCamera, _super);
  44182. function VirtualJoysticksCamera(name, position, scene) {
  44183. _super.call(this, name, position, scene);
  44184. this.inputs.addVirtualJoystick();
  44185. }
  44186. return VirtualJoysticksCamera;
  44187. }(BABYLON.FreeCamera));
  44188. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44189. })(BABYLON || (BABYLON = {}));
  44190. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44191. var BABYLON;
  44192. (function (BABYLON) {
  44193. var FreeCameraVirtualJoystickInput = (function () {
  44194. function FreeCameraVirtualJoystickInput() {
  44195. }
  44196. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44197. return this._leftjoystick;
  44198. };
  44199. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44200. return this._rightjoystick;
  44201. };
  44202. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44203. if (this._leftjoystick) {
  44204. var camera = this.camera;
  44205. var speed = camera._computeLocalCameraSpeed() * 50;
  44206. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44207. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44208. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44209. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44210. if (!this._leftjoystick.pressed) {
  44211. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44212. }
  44213. if (!this._rightjoystick.pressed) {
  44214. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44215. }
  44216. }
  44217. };
  44218. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44219. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44220. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44221. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44222. this._leftjoystick.setJoystickSensibility(0.15);
  44223. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44224. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44225. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44226. this._rightjoystick.reverseUpDown = true;
  44227. this._rightjoystick.setJoystickSensibility(0.05);
  44228. this._rightjoystick.setJoystickColor("yellow");
  44229. };
  44230. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44231. this._leftjoystick.releaseCanvas();
  44232. this._rightjoystick.releaseCanvas();
  44233. };
  44234. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44235. return "FreeCameraVirtualJoystickInput";
  44236. };
  44237. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44238. return "virtualJoystick";
  44239. };
  44240. return FreeCameraVirtualJoystickInput;
  44241. }());
  44242. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44243. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44244. })(BABYLON || (BABYLON = {}));
  44245. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44246. var BABYLON;
  44247. (function (BABYLON) {
  44248. var AnaglyphPostProcess = (function (_super) {
  44249. __extends(AnaglyphPostProcess, _super);
  44250. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44251. var _this = this;
  44252. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  44253. this._passedProcess = rigCameras[0]._rigPostProcess;
  44254. this.onApplyObservable.add(function (effect) {
  44255. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44256. });
  44257. }
  44258. return AnaglyphPostProcess;
  44259. }(BABYLON.PostProcess));
  44260. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44261. })(BABYLON || (BABYLON = {}));
  44262. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44263. var BABYLON;
  44264. (function (BABYLON) {
  44265. var OutlineRenderer = (function () {
  44266. function OutlineRenderer(scene) {
  44267. this._scene = scene;
  44268. }
  44269. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44270. var _this = this;
  44271. if (useOverlay === void 0) { useOverlay = false; }
  44272. var scene = this._scene;
  44273. var engine = this._scene.getEngine();
  44274. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44275. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  44276. return;
  44277. }
  44278. var mesh = subMesh.getRenderingMesh();
  44279. var material = subMesh.getMaterial();
  44280. engine.enableEffect(this._effect);
  44281. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  44282. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  44283. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44284. // Bones
  44285. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44286. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44287. }
  44288. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44289. // Alpha test
  44290. if (material && material.needAlphaTesting()) {
  44291. var alphaTexture = material.getAlphaTestTexture();
  44292. this._effect.setTexture("diffuseSampler", alphaTexture);
  44293. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44294. }
  44295. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  44296. };
  44297. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  44298. var defines = [];
  44299. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  44300. var mesh = subMesh.getMesh();
  44301. var material = subMesh.getMaterial();
  44302. // Alpha test
  44303. if (material && material.needAlphaTesting()) {
  44304. defines.push("#define ALPHATEST");
  44305. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44306. attribs.push(BABYLON.VertexBuffer.UVKind);
  44307. defines.push("#define UV1");
  44308. }
  44309. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44310. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44311. defines.push("#define UV2");
  44312. }
  44313. }
  44314. // Bones
  44315. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44316. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44317. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44318. if (mesh.numBoneInfluencers > 4) {
  44319. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44320. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44321. }
  44322. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44323. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44324. }
  44325. else {
  44326. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44327. }
  44328. // Instances
  44329. if (useInstances) {
  44330. defines.push("#define INSTANCES");
  44331. attribs.push("world0");
  44332. attribs.push("world1");
  44333. attribs.push("world2");
  44334. attribs.push("world3");
  44335. }
  44336. // Get correct effect
  44337. var join = defines.join("\n");
  44338. if (this._cachedDefines !== join) {
  44339. this._cachedDefines = join;
  44340. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  44341. }
  44342. return this._effect.isReady();
  44343. };
  44344. return OutlineRenderer;
  44345. }());
  44346. BABYLON.OutlineRenderer = OutlineRenderer;
  44347. })(BABYLON || (BABYLON = {}));
  44348. //# sourceMappingURL=babylon.outlineRenderer.js.map
  44349. var BABYLON;
  44350. (function (BABYLON) {
  44351. var MeshAssetTask = (function () {
  44352. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  44353. this.name = name;
  44354. this.meshesNames = meshesNames;
  44355. this.rootUrl = rootUrl;
  44356. this.sceneFilename = sceneFilename;
  44357. this.isCompleted = false;
  44358. }
  44359. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44360. var _this = this;
  44361. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  44362. _this.loadedMeshes = meshes;
  44363. _this.loadedParticleSystems = particleSystems;
  44364. _this.loadedSkeletons = skeletons;
  44365. _this.isCompleted = true;
  44366. if (_this.onSuccess) {
  44367. _this.onSuccess(_this);
  44368. }
  44369. onSuccess();
  44370. }, null, function () {
  44371. if (_this.onError) {
  44372. _this.onError(_this);
  44373. }
  44374. onError();
  44375. });
  44376. };
  44377. return MeshAssetTask;
  44378. }());
  44379. BABYLON.MeshAssetTask = MeshAssetTask;
  44380. var TextFileAssetTask = (function () {
  44381. function TextFileAssetTask(name, url) {
  44382. this.name = name;
  44383. this.url = url;
  44384. this.isCompleted = false;
  44385. }
  44386. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44387. var _this = this;
  44388. BABYLON.Tools.LoadFile(this.url, function (data) {
  44389. _this.text = data;
  44390. _this.isCompleted = true;
  44391. if (_this.onSuccess) {
  44392. _this.onSuccess(_this);
  44393. }
  44394. onSuccess();
  44395. }, null, scene.database, false, function () {
  44396. if (_this.onError) {
  44397. _this.onError(_this);
  44398. }
  44399. onError();
  44400. });
  44401. };
  44402. return TextFileAssetTask;
  44403. }());
  44404. BABYLON.TextFileAssetTask = TextFileAssetTask;
  44405. var BinaryFileAssetTask = (function () {
  44406. function BinaryFileAssetTask(name, url) {
  44407. this.name = name;
  44408. this.url = url;
  44409. this.isCompleted = false;
  44410. }
  44411. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44412. var _this = this;
  44413. BABYLON.Tools.LoadFile(this.url, function (data) {
  44414. _this.data = data;
  44415. _this.isCompleted = true;
  44416. if (_this.onSuccess) {
  44417. _this.onSuccess(_this);
  44418. }
  44419. onSuccess();
  44420. }, null, scene.database, true, function () {
  44421. if (_this.onError) {
  44422. _this.onError(_this);
  44423. }
  44424. onError();
  44425. });
  44426. };
  44427. return BinaryFileAssetTask;
  44428. }());
  44429. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  44430. var ImageAssetTask = (function () {
  44431. function ImageAssetTask(name, url) {
  44432. this.name = name;
  44433. this.url = url;
  44434. this.isCompleted = false;
  44435. }
  44436. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44437. var _this = this;
  44438. var img = new Image();
  44439. BABYLON.Tools.SetCorsBehavior(this.url, img);
  44440. img.onload = function () {
  44441. _this.image = img;
  44442. _this.isCompleted = true;
  44443. if (_this.onSuccess) {
  44444. _this.onSuccess(_this);
  44445. }
  44446. onSuccess();
  44447. };
  44448. img.onerror = function () {
  44449. if (_this.onError) {
  44450. _this.onError(_this);
  44451. }
  44452. onError();
  44453. };
  44454. img.src = this.url;
  44455. };
  44456. return ImageAssetTask;
  44457. }());
  44458. BABYLON.ImageAssetTask = ImageAssetTask;
  44459. var TextureAssetTask = (function () {
  44460. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  44461. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44462. this.name = name;
  44463. this.url = url;
  44464. this.noMipmap = noMipmap;
  44465. this.invertY = invertY;
  44466. this.samplingMode = samplingMode;
  44467. this.isCompleted = false;
  44468. }
  44469. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44470. var _this = this;
  44471. var onload = function () {
  44472. _this.isCompleted = true;
  44473. if (_this.onSuccess) {
  44474. _this.onSuccess(_this);
  44475. }
  44476. onSuccess();
  44477. };
  44478. var onerror = function () {
  44479. if (_this.onError) {
  44480. _this.onError(_this);
  44481. }
  44482. onError();
  44483. };
  44484. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  44485. };
  44486. return TextureAssetTask;
  44487. }());
  44488. BABYLON.TextureAssetTask = TextureAssetTask;
  44489. var CubeTextureAssetTask = (function () {
  44490. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  44491. this.name = name;
  44492. this.url = url;
  44493. this.extensions = extensions;
  44494. this.noMipmap = noMipmap;
  44495. this.files = files;
  44496. this.isCompleted = false;
  44497. }
  44498. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44499. var _this = this;
  44500. var onload = function () {
  44501. _this.isCompleted = true;
  44502. if (_this.onSuccess) {
  44503. _this.onSuccess(_this);
  44504. }
  44505. onSuccess();
  44506. };
  44507. var onerror = function () {
  44508. if (_this.onError) {
  44509. _this.onError(_this);
  44510. }
  44511. onError();
  44512. };
  44513. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  44514. };
  44515. return CubeTextureAssetTask;
  44516. }());
  44517. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  44518. var AssetsManager = (function () {
  44519. function AssetsManager(scene) {
  44520. this.tasks = new Array();
  44521. this.waitingTasksCount = 0;
  44522. this.useDefaultLoadingScreen = true;
  44523. this._scene = scene;
  44524. }
  44525. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  44526. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  44527. this.tasks.push(task);
  44528. return task;
  44529. };
  44530. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  44531. var task = new TextFileAssetTask(taskName, url);
  44532. this.tasks.push(task);
  44533. return task;
  44534. };
  44535. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  44536. var task = new BinaryFileAssetTask(taskName, url);
  44537. this.tasks.push(task);
  44538. return task;
  44539. };
  44540. AssetsManager.prototype.addImageTask = function (taskName, url) {
  44541. var task = new ImageAssetTask(taskName, url);
  44542. this.tasks.push(task);
  44543. return task;
  44544. };
  44545. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  44546. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44547. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  44548. this.tasks.push(task);
  44549. return task;
  44550. };
  44551. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  44552. this.waitingTasksCount--;
  44553. if (this.waitingTasksCount === 0) {
  44554. if (this.onFinish) {
  44555. this.onFinish(this.tasks);
  44556. }
  44557. this._scene.getEngine().hideLoadingUI();
  44558. }
  44559. };
  44560. AssetsManager.prototype._runTask = function (task) {
  44561. var _this = this;
  44562. task.run(this._scene, function () {
  44563. if (_this.onTaskSuccess) {
  44564. _this.onTaskSuccess(task);
  44565. }
  44566. _this._decreaseWaitingTasksCount();
  44567. }, function () {
  44568. if (_this.onTaskError) {
  44569. _this.onTaskError(task);
  44570. }
  44571. _this._decreaseWaitingTasksCount();
  44572. });
  44573. };
  44574. AssetsManager.prototype.reset = function () {
  44575. this.tasks = new Array();
  44576. return this;
  44577. };
  44578. AssetsManager.prototype.load = function () {
  44579. this.waitingTasksCount = this.tasks.length;
  44580. if (this.waitingTasksCount === 0) {
  44581. if (this.onFinish) {
  44582. this.onFinish(this.tasks);
  44583. }
  44584. return this;
  44585. }
  44586. if (this.useDefaultLoadingScreen) {
  44587. this._scene.getEngine().displayLoadingUI();
  44588. }
  44589. for (var index = 0; index < this.tasks.length; index++) {
  44590. var task = this.tasks[index];
  44591. this._runTask(task);
  44592. }
  44593. return this;
  44594. };
  44595. return AssetsManager;
  44596. }());
  44597. BABYLON.AssetsManager = AssetsManager;
  44598. })(BABYLON || (BABYLON = {}));
  44599. //# sourceMappingURL=babylon.assetsManager.js.map
  44600. var BABYLON;
  44601. (function (BABYLON) {
  44602. var VRCameraMetrics = (function () {
  44603. function VRCameraMetrics() {
  44604. this.compensateDistortion = true;
  44605. }
  44606. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  44607. get: function () {
  44608. return this.hResolution / (2 * this.vResolution);
  44609. },
  44610. enumerable: true,
  44611. configurable: true
  44612. });
  44613. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  44614. get: function () {
  44615. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  44616. },
  44617. enumerable: true,
  44618. configurable: true
  44619. });
  44620. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  44621. get: function () {
  44622. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44623. var h = (4 * meters) / this.hScreenSize;
  44624. return BABYLON.Matrix.Translation(h, 0, 0);
  44625. },
  44626. enumerable: true,
  44627. configurable: true
  44628. });
  44629. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  44630. get: function () {
  44631. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44632. var h = (4 * meters) / this.hScreenSize;
  44633. return BABYLON.Matrix.Translation(-h, 0, 0);
  44634. },
  44635. enumerable: true,
  44636. configurable: true
  44637. });
  44638. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  44639. get: function () {
  44640. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  44641. },
  44642. enumerable: true,
  44643. configurable: true
  44644. });
  44645. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  44646. get: function () {
  44647. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  44648. },
  44649. enumerable: true,
  44650. configurable: true
  44651. });
  44652. VRCameraMetrics.GetDefault = function () {
  44653. var result = new VRCameraMetrics();
  44654. result.hResolution = 1280;
  44655. result.vResolution = 800;
  44656. result.hScreenSize = 0.149759993;
  44657. result.vScreenSize = 0.0935999975;
  44658. result.vScreenCenter = 0.0467999987,
  44659. result.eyeToScreenDistance = 0.0410000011;
  44660. result.lensSeparationDistance = 0.0635000020;
  44661. result.interpupillaryDistance = 0.0640000030;
  44662. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  44663. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  44664. result.postProcessScaleFactor = 1.714605507808412;
  44665. result.lensCenterOffset = 0.151976421;
  44666. return result;
  44667. };
  44668. return VRCameraMetrics;
  44669. }());
  44670. BABYLON.VRCameraMetrics = VRCameraMetrics;
  44671. })(BABYLON || (BABYLON = {}));
  44672. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  44673. var BABYLON;
  44674. (function (BABYLON) {
  44675. var WebVRFreeCamera = (function (_super) {
  44676. __extends(WebVRFreeCamera, _super);
  44677. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  44678. var _this = this;
  44679. if (compensateDistortion === void 0) { compensateDistortion = false; }
  44680. if (webVROptions === void 0) { webVROptions = {}; }
  44681. _super.call(this, name, position, scene);
  44682. this.webVROptions = webVROptions;
  44683. this._vrDevice = null;
  44684. this._cacheState = null;
  44685. this._vrEnabled = false;
  44686. this._attached = false;
  44687. //using the position provided as the current position offset
  44688. this._positionOffset = position;
  44689. //enable VR
  44690. this.getEngine().initWebVR();
  44691. if (!this.getEngine().vrDisplaysPromise) {
  44692. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  44693. }
  44694. else {
  44695. //TODO get the metrics updated using the device's eye parameters!
  44696. //TODO also check that the device has the right capabilities!
  44697. this._frameData = new VRFrameData();
  44698. this.getEngine().vrDisplaysPromise.then(function (devices) {
  44699. if (devices.length > 0) {
  44700. _this._vrEnabled = true;
  44701. if (_this.webVROptions.displayName) {
  44702. var found = devices.some(function (device) {
  44703. if (device.displayName === _this.webVROptions.displayName) {
  44704. _this._vrDevice = device;
  44705. return true;
  44706. }
  44707. else {
  44708. return false;
  44709. }
  44710. });
  44711. if (!found) {
  44712. _this._vrDevice = devices[0];
  44713. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  44714. }
  44715. }
  44716. else {
  44717. //choose the first one
  44718. _this._vrDevice = devices[0];
  44719. }
  44720. //reset the rig parameters.
  44721. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  44722. if (_this._attached) {
  44723. _this.getEngine().enableVR(_this._vrDevice);
  44724. }
  44725. }
  44726. else {
  44727. BABYLON.Tools.Error("No WebVR devices found!");
  44728. }
  44729. });
  44730. }
  44731. this.rotationQuaternion = new BABYLON.Quaternion();
  44732. this._quaternionCache = new BABYLON.Quaternion();
  44733. }
  44734. WebVRFreeCamera.prototype._checkInputs = function () {
  44735. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  44736. var currentPost = this._frameData.pose;
  44737. //make sure we have data
  44738. if (currentPost && currentPost.orientation) {
  44739. this._cacheState = currentPost;
  44740. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  44741. if (this.webVROptions.trackPosition && this._cacheState.position) {
  44742. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  44743. //scale the position accordingly
  44744. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  44745. //add the position offset
  44746. this.position.addInPlace(this._positionOffset);
  44747. }
  44748. }
  44749. }
  44750. _super.prototype._checkInputs.call(this);
  44751. };
  44752. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44753. _super.prototype.attachControl.call(this, element, noPreventDefault);
  44754. this._attached = true;
  44755. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  44756. if (this._vrEnabled) {
  44757. this.getEngine().enableVR(this._vrDevice);
  44758. }
  44759. };
  44760. WebVRFreeCamera.prototype.detachControl = function (element) {
  44761. _super.prototype.detachControl.call(this, element);
  44762. this._vrEnabled = false;
  44763. this._attached = false;
  44764. this.getEngine().disableVR();
  44765. };
  44766. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  44767. //Backwards comp.
  44768. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  44769. //this.getEngine().switchFullscreen(requestPointerlock);
  44770. };
  44771. WebVRFreeCamera.prototype.getTypeName = function () {
  44772. return "WebVRFreeCamera";
  44773. };
  44774. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  44775. //uses the vrDisplay's "resetPose()".
  44776. //pitch and roll won't be affected.
  44777. this._vrDevice.resetPose();
  44778. };
  44779. /**
  44780. *
  44781. * Set the position offset of the VR camera
  44782. * The offset will be added to the WebVR pose, after scaling it (if set).
  44783. *
  44784. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  44785. *
  44786. * @memberOf WebVRFreeCamera
  44787. */
  44788. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  44789. if (newPosition) {
  44790. this._positionOffset = newPosition;
  44791. }
  44792. else {
  44793. this._positionOffset.copyFrom(this.position);
  44794. }
  44795. };
  44796. return WebVRFreeCamera;
  44797. }(BABYLON.FreeCamera));
  44798. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  44799. })(BABYLON || (BABYLON = {}));
  44800. //# sourceMappingURL=babylon.webVRCamera.js.map
  44801. var BABYLON;
  44802. (function (BABYLON) {
  44803. // Standard optimizations
  44804. var SceneOptimization = (function () {
  44805. function SceneOptimization(priority) {
  44806. if (priority === void 0) { priority = 0; }
  44807. this.priority = priority;
  44808. this.apply = function (scene) {
  44809. return true; // Return true if everything that can be done was applied
  44810. };
  44811. }
  44812. return SceneOptimization;
  44813. }());
  44814. BABYLON.SceneOptimization = SceneOptimization;
  44815. var TextureOptimization = (function (_super) {
  44816. __extends(TextureOptimization, _super);
  44817. function TextureOptimization(priority, maximumSize) {
  44818. var _this = this;
  44819. if (priority === void 0) { priority = 0; }
  44820. if (maximumSize === void 0) { maximumSize = 1024; }
  44821. _super.call(this, priority);
  44822. this.priority = priority;
  44823. this.maximumSize = maximumSize;
  44824. this.apply = function (scene) {
  44825. var allDone = true;
  44826. for (var index = 0; index < scene.textures.length; index++) {
  44827. var texture = scene.textures[index];
  44828. if (!texture.canRescale) {
  44829. continue;
  44830. }
  44831. var currentSize = texture.getSize();
  44832. var maxDimension = Math.max(currentSize.width, currentSize.height);
  44833. if (maxDimension > _this.maximumSize) {
  44834. texture.scale(0.5);
  44835. allDone = false;
  44836. }
  44837. }
  44838. return allDone;
  44839. };
  44840. }
  44841. return TextureOptimization;
  44842. }(SceneOptimization));
  44843. BABYLON.TextureOptimization = TextureOptimization;
  44844. var HardwareScalingOptimization = (function (_super) {
  44845. __extends(HardwareScalingOptimization, _super);
  44846. function HardwareScalingOptimization(priority, maximumScale) {
  44847. var _this = this;
  44848. if (priority === void 0) { priority = 0; }
  44849. if (maximumScale === void 0) { maximumScale = 2; }
  44850. _super.call(this, priority);
  44851. this.priority = priority;
  44852. this.maximumScale = maximumScale;
  44853. this._currentScale = 1;
  44854. this.apply = function (scene) {
  44855. _this._currentScale++;
  44856. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  44857. return _this._currentScale >= _this.maximumScale;
  44858. };
  44859. }
  44860. return HardwareScalingOptimization;
  44861. }(SceneOptimization));
  44862. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  44863. var ShadowsOptimization = (function (_super) {
  44864. __extends(ShadowsOptimization, _super);
  44865. function ShadowsOptimization() {
  44866. _super.apply(this, arguments);
  44867. this.apply = function (scene) {
  44868. scene.shadowsEnabled = false;
  44869. return true;
  44870. };
  44871. }
  44872. return ShadowsOptimization;
  44873. }(SceneOptimization));
  44874. BABYLON.ShadowsOptimization = ShadowsOptimization;
  44875. var PostProcessesOptimization = (function (_super) {
  44876. __extends(PostProcessesOptimization, _super);
  44877. function PostProcessesOptimization() {
  44878. _super.apply(this, arguments);
  44879. this.apply = function (scene) {
  44880. scene.postProcessesEnabled = false;
  44881. return true;
  44882. };
  44883. }
  44884. return PostProcessesOptimization;
  44885. }(SceneOptimization));
  44886. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  44887. var LensFlaresOptimization = (function (_super) {
  44888. __extends(LensFlaresOptimization, _super);
  44889. function LensFlaresOptimization() {
  44890. _super.apply(this, arguments);
  44891. this.apply = function (scene) {
  44892. scene.lensFlaresEnabled = false;
  44893. return true;
  44894. };
  44895. }
  44896. return LensFlaresOptimization;
  44897. }(SceneOptimization));
  44898. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  44899. var ParticlesOptimization = (function (_super) {
  44900. __extends(ParticlesOptimization, _super);
  44901. function ParticlesOptimization() {
  44902. _super.apply(this, arguments);
  44903. this.apply = function (scene) {
  44904. scene.particlesEnabled = false;
  44905. return true;
  44906. };
  44907. }
  44908. return ParticlesOptimization;
  44909. }(SceneOptimization));
  44910. BABYLON.ParticlesOptimization = ParticlesOptimization;
  44911. var RenderTargetsOptimization = (function (_super) {
  44912. __extends(RenderTargetsOptimization, _super);
  44913. function RenderTargetsOptimization() {
  44914. _super.apply(this, arguments);
  44915. this.apply = function (scene) {
  44916. scene.renderTargetsEnabled = false;
  44917. return true;
  44918. };
  44919. }
  44920. return RenderTargetsOptimization;
  44921. }(SceneOptimization));
  44922. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  44923. var MergeMeshesOptimization = (function (_super) {
  44924. __extends(MergeMeshesOptimization, _super);
  44925. function MergeMeshesOptimization() {
  44926. var _this = this;
  44927. _super.apply(this, arguments);
  44928. this._canBeMerged = function (abstractMesh) {
  44929. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  44930. return false;
  44931. }
  44932. var mesh = abstractMesh;
  44933. if (!mesh.isVisible || !mesh.isEnabled()) {
  44934. return false;
  44935. }
  44936. if (mesh.instances.length > 0) {
  44937. return false;
  44938. }
  44939. if (mesh.skeleton || mesh.hasLODLevels) {
  44940. return false;
  44941. }
  44942. if (mesh.parent) {
  44943. return false;
  44944. }
  44945. return true;
  44946. };
  44947. this.apply = function (scene, updateSelectionTree) {
  44948. var globalPool = scene.meshes.slice(0);
  44949. var globalLength = globalPool.length;
  44950. for (var index = 0; index < globalLength; index++) {
  44951. var currentPool = new Array();
  44952. var current = globalPool[index];
  44953. // Checks
  44954. if (!_this._canBeMerged(current)) {
  44955. continue;
  44956. }
  44957. currentPool.push(current);
  44958. // Find compatible meshes
  44959. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  44960. var otherMesh = globalPool[subIndex];
  44961. if (!_this._canBeMerged(otherMesh)) {
  44962. continue;
  44963. }
  44964. if (otherMesh.material !== current.material) {
  44965. continue;
  44966. }
  44967. if (otherMesh.checkCollisions !== current.checkCollisions) {
  44968. continue;
  44969. }
  44970. currentPool.push(otherMesh);
  44971. globalLength--;
  44972. globalPool.splice(subIndex, 1);
  44973. subIndex--;
  44974. }
  44975. if (currentPool.length < 2) {
  44976. continue;
  44977. }
  44978. // Merge meshes
  44979. BABYLON.Mesh.MergeMeshes(currentPool);
  44980. }
  44981. if (updateSelectionTree != undefined) {
  44982. if (updateSelectionTree) {
  44983. scene.createOrUpdateSelectionOctree();
  44984. }
  44985. }
  44986. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  44987. scene.createOrUpdateSelectionOctree();
  44988. }
  44989. return true;
  44990. };
  44991. }
  44992. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  44993. get: function () {
  44994. return MergeMeshesOptimization._UpdateSelectionTree;
  44995. },
  44996. set: function (value) {
  44997. MergeMeshesOptimization._UpdateSelectionTree = value;
  44998. },
  44999. enumerable: true,
  45000. configurable: true
  45001. });
  45002. MergeMeshesOptimization._UpdateSelectionTree = false;
  45003. return MergeMeshesOptimization;
  45004. }(SceneOptimization));
  45005. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45006. // Options
  45007. var SceneOptimizerOptions = (function () {
  45008. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45009. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45010. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45011. this.targetFrameRate = targetFrameRate;
  45012. this.trackerDuration = trackerDuration;
  45013. this.optimizations = new Array();
  45014. }
  45015. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45016. var result = new SceneOptimizerOptions(targetFrameRate);
  45017. var priority = 0;
  45018. result.optimizations.push(new MergeMeshesOptimization(priority));
  45019. result.optimizations.push(new ShadowsOptimization(priority));
  45020. result.optimizations.push(new LensFlaresOptimization(priority));
  45021. // Next priority
  45022. priority++;
  45023. result.optimizations.push(new PostProcessesOptimization(priority));
  45024. result.optimizations.push(new ParticlesOptimization(priority));
  45025. // Next priority
  45026. priority++;
  45027. result.optimizations.push(new TextureOptimization(priority, 1024));
  45028. return result;
  45029. };
  45030. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45031. var result = new SceneOptimizerOptions(targetFrameRate);
  45032. var priority = 0;
  45033. result.optimizations.push(new MergeMeshesOptimization(priority));
  45034. result.optimizations.push(new ShadowsOptimization(priority));
  45035. result.optimizations.push(new LensFlaresOptimization(priority));
  45036. // Next priority
  45037. priority++;
  45038. result.optimizations.push(new PostProcessesOptimization(priority));
  45039. result.optimizations.push(new ParticlesOptimization(priority));
  45040. // Next priority
  45041. priority++;
  45042. result.optimizations.push(new TextureOptimization(priority, 512));
  45043. // Next priority
  45044. priority++;
  45045. result.optimizations.push(new RenderTargetsOptimization(priority));
  45046. // Next priority
  45047. priority++;
  45048. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45049. return result;
  45050. };
  45051. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45052. var result = new SceneOptimizerOptions(targetFrameRate);
  45053. var priority = 0;
  45054. result.optimizations.push(new MergeMeshesOptimization(priority));
  45055. result.optimizations.push(new ShadowsOptimization(priority));
  45056. result.optimizations.push(new LensFlaresOptimization(priority));
  45057. // Next priority
  45058. priority++;
  45059. result.optimizations.push(new PostProcessesOptimization(priority));
  45060. result.optimizations.push(new ParticlesOptimization(priority));
  45061. // Next priority
  45062. priority++;
  45063. result.optimizations.push(new TextureOptimization(priority, 256));
  45064. // Next priority
  45065. priority++;
  45066. result.optimizations.push(new RenderTargetsOptimization(priority));
  45067. // Next priority
  45068. priority++;
  45069. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45070. return result;
  45071. };
  45072. return SceneOptimizerOptions;
  45073. }());
  45074. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45075. // Scene optimizer tool
  45076. var SceneOptimizer = (function () {
  45077. function SceneOptimizer() {
  45078. }
  45079. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45080. // TODO: add an epsilon
  45081. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45082. if (onSuccess) {
  45083. onSuccess();
  45084. }
  45085. return;
  45086. }
  45087. // Apply current level of optimizations
  45088. var allDone = true;
  45089. var noOptimizationApplied = true;
  45090. for (var index = 0; index < options.optimizations.length; index++) {
  45091. var optimization = options.optimizations[index];
  45092. if (optimization.priority === currentPriorityLevel) {
  45093. noOptimizationApplied = false;
  45094. allDone = allDone && optimization.apply(scene);
  45095. }
  45096. }
  45097. // If no optimization was applied, this is a failure :(
  45098. if (noOptimizationApplied) {
  45099. if (onFailure) {
  45100. onFailure();
  45101. }
  45102. return;
  45103. }
  45104. // If all optimizations were done, move to next level
  45105. if (allDone) {
  45106. currentPriorityLevel++;
  45107. }
  45108. // Let's the system running for a specific amount of time before checking FPS
  45109. scene.executeWhenReady(function () {
  45110. setTimeout(function () {
  45111. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45112. }, options.trackerDuration);
  45113. });
  45114. };
  45115. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45116. if (!options) {
  45117. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45118. }
  45119. // Let's the system running for a specific amount of time before checking FPS
  45120. scene.executeWhenReady(function () {
  45121. setTimeout(function () {
  45122. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45123. }, options.trackerDuration);
  45124. });
  45125. };
  45126. return SceneOptimizer;
  45127. }());
  45128. BABYLON.SceneOptimizer = SceneOptimizer;
  45129. })(BABYLON || (BABYLON = {}));
  45130. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45131. var BABYLON;
  45132. (function (BABYLON) {
  45133. var Internals;
  45134. (function (Internals) {
  45135. var MeshLODLevel = (function () {
  45136. function MeshLODLevel(distance, mesh) {
  45137. this.distance = distance;
  45138. this.mesh = mesh;
  45139. }
  45140. return MeshLODLevel;
  45141. }());
  45142. Internals.MeshLODLevel = MeshLODLevel;
  45143. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45144. })(BABYLON || (BABYLON = {}));
  45145. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45146. var BABYLON;
  45147. (function (BABYLON) {
  45148. var RawTexture = (function (_super) {
  45149. __extends(RawTexture, _super);
  45150. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45151. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45152. if (invertY === void 0) { invertY = false; }
  45153. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45154. _super.call(this, null, scene, !generateMipMaps, invertY);
  45155. this.format = format;
  45156. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45157. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45158. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45159. }
  45160. RawTexture.prototype.update = function (data) {
  45161. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45162. };
  45163. // Statics
  45164. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45165. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45166. if (invertY === void 0) { invertY = false; }
  45167. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45168. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45169. };
  45170. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45171. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45172. if (invertY === void 0) { invertY = false; }
  45173. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45174. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45175. };
  45176. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45177. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45178. if (invertY === void 0) { invertY = false; }
  45179. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45180. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45181. };
  45182. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45183. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45184. if (invertY === void 0) { invertY = false; }
  45185. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45186. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45187. };
  45188. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45189. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45190. if (invertY === void 0) { invertY = false; }
  45191. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45192. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45193. };
  45194. return RawTexture;
  45195. }(BABYLON.Texture));
  45196. BABYLON.RawTexture = RawTexture;
  45197. })(BABYLON || (BABYLON = {}));
  45198. //# sourceMappingURL=babylon.rawTexture.js.map
  45199. var BABYLON;
  45200. (function (BABYLON) {
  45201. var IndexedVector2 = (function (_super) {
  45202. __extends(IndexedVector2, _super);
  45203. function IndexedVector2(original, index) {
  45204. _super.call(this, original.x, original.y);
  45205. this.index = index;
  45206. }
  45207. return IndexedVector2;
  45208. }(BABYLON.Vector2));
  45209. var PolygonPoints = (function () {
  45210. function PolygonPoints() {
  45211. this.elements = new Array();
  45212. }
  45213. PolygonPoints.prototype.add = function (originalPoints) {
  45214. var _this = this;
  45215. var result = new Array();
  45216. originalPoints.forEach(function (point) {
  45217. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45218. var newPoint = new IndexedVector2(point, _this.elements.length);
  45219. result.push(newPoint);
  45220. _this.elements.push(newPoint);
  45221. }
  45222. });
  45223. return result;
  45224. };
  45225. PolygonPoints.prototype.computeBounds = function () {
  45226. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45227. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45228. this.elements.forEach(function (point) {
  45229. // x
  45230. if (point.x < lmin.x) {
  45231. lmin.x = point.x;
  45232. }
  45233. else if (point.x > lmax.x) {
  45234. lmax.x = point.x;
  45235. }
  45236. // y
  45237. if (point.y < lmin.y) {
  45238. lmin.y = point.y;
  45239. }
  45240. else if (point.y > lmax.y) {
  45241. lmax.y = point.y;
  45242. }
  45243. });
  45244. return {
  45245. min: lmin,
  45246. max: lmax,
  45247. width: lmax.x - lmin.x,
  45248. height: lmax.y - lmin.y
  45249. };
  45250. };
  45251. return PolygonPoints;
  45252. }());
  45253. var Polygon = (function () {
  45254. function Polygon() {
  45255. }
  45256. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45257. return [
  45258. new BABYLON.Vector2(xmin, ymin),
  45259. new BABYLON.Vector2(xmax, ymin),
  45260. new BABYLON.Vector2(xmax, ymax),
  45261. new BABYLON.Vector2(xmin, ymax)
  45262. ];
  45263. };
  45264. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45265. if (cx === void 0) { cx = 0; }
  45266. if (cy === void 0) { cy = 0; }
  45267. if (numberOfSides === void 0) { numberOfSides = 32; }
  45268. var result = new Array();
  45269. var angle = 0;
  45270. var increment = (Math.PI * 2) / numberOfSides;
  45271. for (var i = 0; i < numberOfSides; i++) {
  45272. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  45273. angle -= increment;
  45274. }
  45275. return result;
  45276. };
  45277. Polygon.Parse = function (input) {
  45278. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  45279. var i, result = [];
  45280. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  45281. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  45282. }
  45283. return result;
  45284. };
  45285. Polygon.StartingAt = function (x, y) {
  45286. return BABYLON.Path2.StartingAt(x, y);
  45287. };
  45288. return Polygon;
  45289. }());
  45290. BABYLON.Polygon = Polygon;
  45291. var PolygonMeshBuilder = (function () {
  45292. function PolygonMeshBuilder(name, contours, scene) {
  45293. this._points = new PolygonPoints();
  45294. this._outlinepoints = new PolygonPoints();
  45295. this._holes = [];
  45296. this._epoints = new Array();
  45297. this._eholes = new Array();
  45298. this._name = name;
  45299. this._scene = scene;
  45300. var points;
  45301. if (contours instanceof BABYLON.Path2) {
  45302. points = contours.getPoints();
  45303. }
  45304. else {
  45305. points = contours;
  45306. }
  45307. this._addToepoint(points);
  45308. this._points.add(points);
  45309. this._outlinepoints.add(points);
  45310. }
  45311. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  45312. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  45313. var p = points_1[_i];
  45314. this._epoints.push(p.x, p.y);
  45315. }
  45316. };
  45317. PolygonMeshBuilder.prototype.addHole = function (hole) {
  45318. this._points.add(hole);
  45319. var holepoints = new PolygonPoints();
  45320. holepoints.add(hole);
  45321. this._holes.push(holepoints);
  45322. this._eholes.push(this._epoints.length / 2);
  45323. this._addToepoint(hole);
  45324. return this;
  45325. };
  45326. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  45327. var _this = this;
  45328. if (updatable === void 0) { updatable = false; }
  45329. var result = new BABYLON.Mesh(this._name, this._scene);
  45330. var normals = [];
  45331. var positions = [];
  45332. var uvs = [];
  45333. var bounds = this._points.computeBounds();
  45334. this._points.elements.forEach(function (p) {
  45335. normals.push(0, 1.0, 0);
  45336. positions.push(p.x, 0, p.y);
  45337. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  45338. });
  45339. var indices = [];
  45340. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  45341. for (var i = 0; i < res.length; i++) {
  45342. indices.push(res[i]);
  45343. }
  45344. if (depth > 0) {
  45345. var positionscount = (positions.length / 3); //get the current pointcount
  45346. this._points.elements.forEach(function (p) {
  45347. normals.push(0, -1.0, 0);
  45348. positions.push(p.x, -depth, p.y);
  45349. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  45350. });
  45351. var totalCount = indices.length;
  45352. for (var i = 0; i < totalCount; i += 3) {
  45353. var i0 = indices[i + 0];
  45354. var i1 = indices[i + 1];
  45355. var i2 = indices[i + 2];
  45356. indices.push(i2 + positionscount);
  45357. indices.push(i1 + positionscount);
  45358. indices.push(i0 + positionscount);
  45359. }
  45360. //Add the sides
  45361. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  45362. this._holes.forEach(function (hole) {
  45363. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  45364. });
  45365. }
  45366. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  45367. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  45368. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  45369. result.setIndices(indices);
  45370. return result;
  45371. };
  45372. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  45373. var StartIndex = positions.length / 3;
  45374. var ulength = 0;
  45375. for (var i = 0; i < points.elements.length; i++) {
  45376. var p = points.elements[i];
  45377. var p1;
  45378. if ((i + 1) > points.elements.length - 1) {
  45379. p1 = points.elements[0];
  45380. }
  45381. else {
  45382. p1 = points.elements[i + 1];
  45383. }
  45384. positions.push(p.x, 0, p.y);
  45385. positions.push(p.x, -depth, p.y);
  45386. positions.push(p1.x, 0, p1.y);
  45387. positions.push(p1.x, -depth, p1.y);
  45388. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  45389. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  45390. var v3 = v2.subtract(v1);
  45391. var v4 = new BABYLON.Vector3(0, 1, 0);
  45392. var vn = BABYLON.Vector3.Cross(v3, v4);
  45393. vn = vn.normalize();
  45394. uvs.push(ulength / bounds.width, 0);
  45395. uvs.push(ulength / bounds.width, 1);
  45396. ulength += v3.length();
  45397. uvs.push((ulength / bounds.width), 0);
  45398. uvs.push((ulength / bounds.width), 1);
  45399. if (!flip) {
  45400. normals.push(-vn.x, -vn.y, -vn.z);
  45401. normals.push(-vn.x, -vn.y, -vn.z);
  45402. normals.push(-vn.x, -vn.y, -vn.z);
  45403. normals.push(-vn.x, -vn.y, -vn.z);
  45404. indices.push(StartIndex);
  45405. indices.push(StartIndex + 1);
  45406. indices.push(StartIndex + 2);
  45407. indices.push(StartIndex + 1);
  45408. indices.push(StartIndex + 3);
  45409. indices.push(StartIndex + 2);
  45410. }
  45411. else {
  45412. normals.push(vn.x, vn.y, vn.z);
  45413. normals.push(vn.x, vn.y, vn.z);
  45414. normals.push(vn.x, vn.y, vn.z);
  45415. normals.push(vn.x, vn.y, vn.z);
  45416. indices.push(StartIndex);
  45417. indices.push(StartIndex + 2);
  45418. indices.push(StartIndex + 1);
  45419. indices.push(StartIndex + 1);
  45420. indices.push(StartIndex + 2);
  45421. indices.push(StartIndex + 3);
  45422. }
  45423. StartIndex += 4;
  45424. }
  45425. ;
  45426. };
  45427. return PolygonMeshBuilder;
  45428. }());
  45429. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  45430. })(BABYLON || (BABYLON = {}));
  45431. //# sourceMappingURL=babylon.polygonMesh.js.map
  45432. var BABYLON;
  45433. (function (BABYLON) {
  45434. var Octree = (function () {
  45435. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  45436. if (maxDepth === void 0) { maxDepth = 2; }
  45437. this.maxDepth = maxDepth;
  45438. this.dynamicContent = new Array();
  45439. this._maxBlockCapacity = maxBlockCapacity || 64;
  45440. this._selectionContent = new BABYLON.SmartArray(1024);
  45441. this._creationFunc = creationFunc;
  45442. }
  45443. // Methods
  45444. Octree.prototype.update = function (worldMin, worldMax, entries) {
  45445. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  45446. };
  45447. Octree.prototype.addMesh = function (entry) {
  45448. for (var index = 0; index < this.blocks.length; index++) {
  45449. var block = this.blocks[index];
  45450. block.addEntry(entry);
  45451. }
  45452. };
  45453. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  45454. this._selectionContent.reset();
  45455. for (var index = 0; index < this.blocks.length; index++) {
  45456. var block = this.blocks[index];
  45457. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  45458. }
  45459. if (allowDuplicate) {
  45460. this._selectionContent.concat(this.dynamicContent);
  45461. }
  45462. else {
  45463. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45464. }
  45465. return this._selectionContent;
  45466. };
  45467. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  45468. this._selectionContent.reset();
  45469. for (var index = 0; index < this.blocks.length; index++) {
  45470. var block = this.blocks[index];
  45471. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  45472. }
  45473. if (allowDuplicate) {
  45474. this._selectionContent.concat(this.dynamicContent);
  45475. }
  45476. else {
  45477. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45478. }
  45479. return this._selectionContent;
  45480. };
  45481. Octree.prototype.intersectsRay = function (ray) {
  45482. this._selectionContent.reset();
  45483. for (var index = 0; index < this.blocks.length; index++) {
  45484. var block = this.blocks[index];
  45485. block.intersectsRay(ray, this._selectionContent);
  45486. }
  45487. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45488. return this._selectionContent;
  45489. };
  45490. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  45491. target.blocks = new Array();
  45492. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  45493. // Segmenting space
  45494. for (var x = 0; x < 2; x++) {
  45495. for (var y = 0; y < 2; y++) {
  45496. for (var z = 0; z < 2; z++) {
  45497. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  45498. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  45499. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  45500. block.addEntries(entries);
  45501. target.blocks.push(block);
  45502. }
  45503. }
  45504. }
  45505. };
  45506. Octree.CreationFuncForMeshes = function (entry, block) {
  45507. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45508. block.entries.push(entry);
  45509. }
  45510. };
  45511. Octree.CreationFuncForSubMeshes = function (entry, block) {
  45512. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45513. block.entries.push(entry);
  45514. }
  45515. };
  45516. return Octree;
  45517. }());
  45518. BABYLON.Octree = Octree;
  45519. })(BABYLON || (BABYLON = {}));
  45520. //# sourceMappingURL=babylon.octree.js.map
  45521. var BABYLON;
  45522. (function (BABYLON) {
  45523. var OctreeBlock = (function () {
  45524. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  45525. this.entries = new Array();
  45526. this._boundingVectors = new Array();
  45527. this._capacity = capacity;
  45528. this._depth = depth;
  45529. this._maxDepth = maxDepth;
  45530. this._creationFunc = creationFunc;
  45531. this._minPoint = minPoint;
  45532. this._maxPoint = maxPoint;
  45533. this._boundingVectors.push(minPoint.clone());
  45534. this._boundingVectors.push(maxPoint.clone());
  45535. this._boundingVectors.push(minPoint.clone());
  45536. this._boundingVectors[2].x = maxPoint.x;
  45537. this._boundingVectors.push(minPoint.clone());
  45538. this._boundingVectors[3].y = maxPoint.y;
  45539. this._boundingVectors.push(minPoint.clone());
  45540. this._boundingVectors[4].z = maxPoint.z;
  45541. this._boundingVectors.push(maxPoint.clone());
  45542. this._boundingVectors[5].z = minPoint.z;
  45543. this._boundingVectors.push(maxPoint.clone());
  45544. this._boundingVectors[6].x = minPoint.x;
  45545. this._boundingVectors.push(maxPoint.clone());
  45546. this._boundingVectors[7].y = minPoint.y;
  45547. }
  45548. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  45549. // Property
  45550. get: function () {
  45551. return this._capacity;
  45552. },
  45553. enumerable: true,
  45554. configurable: true
  45555. });
  45556. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  45557. get: function () {
  45558. return this._minPoint;
  45559. },
  45560. enumerable: true,
  45561. configurable: true
  45562. });
  45563. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  45564. get: function () {
  45565. return this._maxPoint;
  45566. },
  45567. enumerable: true,
  45568. configurable: true
  45569. });
  45570. // Methods
  45571. OctreeBlock.prototype.addEntry = function (entry) {
  45572. if (this.blocks) {
  45573. for (var index = 0; index < this.blocks.length; index++) {
  45574. var block = this.blocks[index];
  45575. block.addEntry(entry);
  45576. }
  45577. return;
  45578. }
  45579. this._creationFunc(entry, this);
  45580. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  45581. this.createInnerBlocks();
  45582. }
  45583. };
  45584. OctreeBlock.prototype.addEntries = function (entries) {
  45585. for (var index = 0; index < entries.length; index++) {
  45586. var mesh = entries[index];
  45587. this.addEntry(mesh);
  45588. }
  45589. };
  45590. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  45591. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  45592. if (this.blocks) {
  45593. for (var index = 0; index < this.blocks.length; index++) {
  45594. var block = this.blocks[index];
  45595. block.select(frustumPlanes, selection, allowDuplicate);
  45596. }
  45597. return;
  45598. }
  45599. if (allowDuplicate) {
  45600. selection.concat(this.entries);
  45601. }
  45602. else {
  45603. selection.concatWithNoDuplicate(this.entries);
  45604. }
  45605. }
  45606. };
  45607. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  45608. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  45609. if (this.blocks) {
  45610. for (var index = 0; index < this.blocks.length; index++) {
  45611. var block = this.blocks[index];
  45612. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  45613. }
  45614. return;
  45615. }
  45616. if (allowDuplicate) {
  45617. selection.concat(this.entries);
  45618. }
  45619. else {
  45620. selection.concatWithNoDuplicate(this.entries);
  45621. }
  45622. }
  45623. };
  45624. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  45625. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  45626. if (this.blocks) {
  45627. for (var index = 0; index < this.blocks.length; index++) {
  45628. var block = this.blocks[index];
  45629. block.intersectsRay(ray, selection);
  45630. }
  45631. return;
  45632. }
  45633. selection.concatWithNoDuplicate(this.entries);
  45634. }
  45635. };
  45636. OctreeBlock.prototype.createInnerBlocks = function () {
  45637. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  45638. };
  45639. return OctreeBlock;
  45640. }());
  45641. BABYLON.OctreeBlock = OctreeBlock;
  45642. })(BABYLON || (BABYLON = {}));
  45643. //# sourceMappingURL=babylon.octreeBlock.js.map
  45644. var BABYLON;
  45645. (function (BABYLON) {
  45646. var BlurPostProcess = (function (_super) {
  45647. __extends(BlurPostProcess, _super);
  45648. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  45649. var _this = this;
  45650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45651. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  45652. this.direction = direction;
  45653. this.blurWidth = blurWidth;
  45654. this.onApplyObservable.add(function (effect) {
  45655. effect.setFloat2("screenSize", _this.width, _this.height);
  45656. effect.setVector2("direction", _this.direction);
  45657. effect.setFloat("blurWidth", _this.blurWidth);
  45658. });
  45659. }
  45660. return BlurPostProcess;
  45661. }(BABYLON.PostProcess));
  45662. BABYLON.BlurPostProcess = BlurPostProcess;
  45663. })(BABYLON || (BABYLON = {}));
  45664. //# sourceMappingURL=babylon.blurPostProcess.js.map
  45665. var BABYLON;
  45666. (function (BABYLON) {
  45667. var RefractionPostProcess = (function (_super) {
  45668. __extends(RefractionPostProcess, _super);
  45669. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  45670. var _this = this;
  45671. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  45672. this.color = color;
  45673. this.depth = depth;
  45674. this.colorLevel = colorLevel;
  45675. this.onActivateObservable.add(function (cam) {
  45676. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  45677. });
  45678. this.onApplyObservable.add(function (effect) {
  45679. effect.setColor3("baseColor", _this.color);
  45680. effect.setFloat("depth", _this.depth);
  45681. effect.setFloat("colorLevel", _this.colorLevel);
  45682. effect.setTexture("refractionSampler", _this._refRexture);
  45683. });
  45684. }
  45685. // Methods
  45686. RefractionPostProcess.prototype.dispose = function (camera) {
  45687. if (this._refRexture) {
  45688. this._refRexture.dispose();
  45689. }
  45690. _super.prototype.dispose.call(this, camera);
  45691. };
  45692. return RefractionPostProcess;
  45693. }(BABYLON.PostProcess));
  45694. BABYLON.RefractionPostProcess = RefractionPostProcess;
  45695. })(BABYLON || (BABYLON = {}));
  45696. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  45697. var BABYLON;
  45698. (function (BABYLON) {
  45699. var BlackAndWhitePostProcess = (function (_super) {
  45700. __extends(BlackAndWhitePostProcess, _super);
  45701. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  45702. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  45703. }
  45704. return BlackAndWhitePostProcess;
  45705. }(BABYLON.PostProcess));
  45706. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  45707. })(BABYLON || (BABYLON = {}));
  45708. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  45709. var BABYLON;
  45710. (function (BABYLON) {
  45711. var ConvolutionPostProcess = (function (_super) {
  45712. __extends(ConvolutionPostProcess, _super);
  45713. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  45714. var _this = this;
  45715. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  45716. this.kernel = kernel;
  45717. this.onApply = function (effect) {
  45718. effect.setFloat2("screenSize", _this.width, _this.height);
  45719. effect.setArray("kernel", _this.kernel);
  45720. };
  45721. }
  45722. // Statics
  45723. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  45724. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  45725. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  45726. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  45727. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  45728. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  45729. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  45730. return ConvolutionPostProcess;
  45731. }(BABYLON.PostProcess));
  45732. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  45733. })(BABYLON || (BABYLON = {}));
  45734. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  45735. var BABYLON;
  45736. (function (BABYLON) {
  45737. var FilterPostProcess = (function (_super) {
  45738. __extends(FilterPostProcess, _super);
  45739. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  45740. var _this = this;
  45741. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  45742. this.kernelMatrix = kernelMatrix;
  45743. this.onApply = function (effect) {
  45744. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  45745. };
  45746. }
  45747. return FilterPostProcess;
  45748. }(BABYLON.PostProcess));
  45749. BABYLON.FilterPostProcess = FilterPostProcess;
  45750. })(BABYLON || (BABYLON = {}));
  45751. //# sourceMappingURL=babylon.filterPostProcess.js.map
  45752. var BABYLON;
  45753. (function (BABYLON) {
  45754. var FxaaPostProcess = (function (_super) {
  45755. __extends(FxaaPostProcess, _super);
  45756. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  45757. var _this = this;
  45758. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  45759. this.onSizeChangedObservable.add(function () {
  45760. _this.texelWidth = 1.0 / _this.width;
  45761. _this.texelHeight = 1.0 / _this.height;
  45762. });
  45763. this.onApplyObservable.add(function (effect) {
  45764. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  45765. });
  45766. }
  45767. return FxaaPostProcess;
  45768. }(BABYLON.PostProcess));
  45769. BABYLON.FxaaPostProcess = FxaaPostProcess;
  45770. })(BABYLON || (BABYLON = {}));
  45771. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  45772. var BABYLON;
  45773. (function (BABYLON) {
  45774. var StereoscopicInterlacePostProcess = (function (_super) {
  45775. __extends(StereoscopicInterlacePostProcess, _super);
  45776. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  45777. var _this = this;
  45778. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  45779. this._passedProcess = rigCameras[0]._rigPostProcess;
  45780. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  45781. this.onSizeChangedObservable.add(function () {
  45782. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45783. });
  45784. this.onApplyObservable.add(function (effect) {
  45785. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  45786. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  45787. });
  45788. }
  45789. return StereoscopicInterlacePostProcess;
  45790. }(BABYLON.PostProcess));
  45791. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  45792. })(BABYLON || (BABYLON = {}));
  45793. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  45794. var BABYLON;
  45795. (function (BABYLON) {
  45796. var LensFlare = (function () {
  45797. function LensFlare(size, position, color, imgUrl, system) {
  45798. this.size = size;
  45799. this.position = position;
  45800. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  45801. this.dispose = function () {
  45802. if (this.texture) {
  45803. this.texture.dispose();
  45804. }
  45805. // Remove from scene
  45806. var index = this._system.lensFlares.indexOf(this);
  45807. this._system.lensFlares.splice(index, 1);
  45808. };
  45809. this.color = color || new BABYLON.Color3(1, 1, 1);
  45810. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  45811. this._system = system;
  45812. system.lensFlares.push(this);
  45813. }
  45814. return LensFlare;
  45815. }());
  45816. BABYLON.LensFlare = LensFlare;
  45817. })(BABYLON || (BABYLON = {}));
  45818. //# sourceMappingURL=babylon.lensFlare.js.map
  45819. var BABYLON;
  45820. (function (BABYLON) {
  45821. var LensFlareSystem = (function () {
  45822. function LensFlareSystem(name, emitter, scene) {
  45823. this.name = name;
  45824. this.lensFlares = new Array();
  45825. this.borderLimit = 300;
  45826. this.viewportBorder = 0;
  45827. this.layerMask = 0x0FFFFFFF;
  45828. this._vertexBuffers = {};
  45829. this._isEnabled = true;
  45830. this._scene = scene;
  45831. this._emitter = emitter;
  45832. this.id = name;
  45833. scene.lensFlareSystems.push(this);
  45834. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  45835. var engine = scene.getEngine();
  45836. // VBO
  45837. var vertices = [];
  45838. vertices.push(1, 1);
  45839. vertices.push(-1, 1);
  45840. vertices.push(-1, -1);
  45841. vertices.push(1, -1);
  45842. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  45843. // Indices
  45844. var indices = [];
  45845. indices.push(0);
  45846. indices.push(1);
  45847. indices.push(2);
  45848. indices.push(0);
  45849. indices.push(2);
  45850. indices.push(3);
  45851. this._indexBuffer = engine.createIndexBuffer(indices);
  45852. // Effects
  45853. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  45854. }
  45855. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  45856. get: function () {
  45857. return this._isEnabled;
  45858. },
  45859. set: function (value) {
  45860. this._isEnabled = value;
  45861. },
  45862. enumerable: true,
  45863. configurable: true
  45864. });
  45865. LensFlareSystem.prototype.getScene = function () {
  45866. return this._scene;
  45867. };
  45868. LensFlareSystem.prototype.getEmitter = function () {
  45869. return this._emitter;
  45870. };
  45871. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  45872. this._emitter = newEmitter;
  45873. };
  45874. LensFlareSystem.prototype.getEmitterPosition = function () {
  45875. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  45876. };
  45877. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  45878. var position = this.getEmitterPosition();
  45879. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  45880. this._positionX = position.x;
  45881. this._positionY = position.y;
  45882. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  45883. if (this.viewportBorder > 0) {
  45884. globalViewport.x -= this.viewportBorder;
  45885. globalViewport.y -= this.viewportBorder;
  45886. globalViewport.width += this.viewportBorder * 2;
  45887. globalViewport.height += this.viewportBorder * 2;
  45888. position.x += this.viewportBorder;
  45889. position.y += this.viewportBorder;
  45890. this._positionX += this.viewportBorder;
  45891. this._positionY += this.viewportBorder;
  45892. }
  45893. if (position.z > 0) {
  45894. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  45895. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  45896. return true;
  45897. }
  45898. return true;
  45899. }
  45900. return false;
  45901. };
  45902. LensFlareSystem.prototype._isVisible = function () {
  45903. if (!this._isEnabled) {
  45904. return false;
  45905. }
  45906. var emitterPosition = this.getEmitterPosition();
  45907. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  45908. var distance = direction.length();
  45909. direction.normalize();
  45910. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  45911. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  45912. return !pickInfo.hit || pickInfo.distance > distance;
  45913. };
  45914. LensFlareSystem.prototype.render = function () {
  45915. if (!this._effect.isReady())
  45916. return false;
  45917. var engine = this._scene.getEngine();
  45918. var viewport = this._scene.activeCamera.viewport;
  45919. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  45920. // Position
  45921. if (!this.computeEffectivePosition(globalViewport)) {
  45922. return false;
  45923. }
  45924. // Visibility
  45925. if (!this._isVisible()) {
  45926. return false;
  45927. }
  45928. // Intensity
  45929. var awayX;
  45930. var awayY;
  45931. if (this._positionX < this.borderLimit + globalViewport.x) {
  45932. awayX = this.borderLimit + globalViewport.x - this._positionX;
  45933. }
  45934. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  45935. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  45936. }
  45937. else {
  45938. awayX = 0;
  45939. }
  45940. if (this._positionY < this.borderLimit + globalViewport.y) {
  45941. awayY = this.borderLimit + globalViewport.y - this._positionY;
  45942. }
  45943. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  45944. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  45945. }
  45946. else {
  45947. awayY = 0;
  45948. }
  45949. var away = (awayX > awayY) ? awayX : awayY;
  45950. away -= this.viewportBorder;
  45951. if (away > this.borderLimit) {
  45952. away = this.borderLimit;
  45953. }
  45954. var intensity = 1.0 - (away / this.borderLimit);
  45955. if (intensity < 0) {
  45956. return false;
  45957. }
  45958. if (intensity > 1.0) {
  45959. intensity = 1.0;
  45960. }
  45961. if (this.viewportBorder > 0) {
  45962. globalViewport.x += this.viewportBorder;
  45963. globalViewport.y += this.viewportBorder;
  45964. globalViewport.width -= this.viewportBorder * 2;
  45965. globalViewport.height -= this.viewportBorder * 2;
  45966. this._positionX -= this.viewportBorder;
  45967. this._positionY -= this.viewportBorder;
  45968. }
  45969. // Position
  45970. var centerX = globalViewport.x + globalViewport.width / 2;
  45971. var centerY = globalViewport.y + globalViewport.height / 2;
  45972. var distX = centerX - this._positionX;
  45973. var distY = centerY - this._positionY;
  45974. // Effects
  45975. engine.enableEffect(this._effect);
  45976. engine.setState(false);
  45977. engine.setDepthBuffer(false);
  45978. // VBOs
  45979. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  45980. // Flares
  45981. for (var index = 0; index < this.lensFlares.length; index++) {
  45982. var flare = this.lensFlares[index];
  45983. engine.setAlphaMode(flare.alphaMode);
  45984. var x = centerX - (distX * flare.position);
  45985. var y = centerY - (distY * flare.position);
  45986. var cw = flare.size;
  45987. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  45988. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  45989. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  45990. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  45991. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  45992. // Texture
  45993. this._effect.setTexture("textureSampler", flare.texture);
  45994. // Color
  45995. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  45996. // Draw order
  45997. engine.draw(true, 0, 6);
  45998. }
  45999. engine.setDepthBuffer(true);
  46000. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46001. return true;
  46002. };
  46003. LensFlareSystem.prototype.dispose = function () {
  46004. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46005. if (vertexBuffer) {
  46006. vertexBuffer.dispose();
  46007. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46008. }
  46009. if (this._indexBuffer) {
  46010. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46011. this._indexBuffer = null;
  46012. }
  46013. while (this.lensFlares.length) {
  46014. this.lensFlares[0].dispose();
  46015. }
  46016. // Remove from scene
  46017. var index = this._scene.lensFlareSystems.indexOf(this);
  46018. this._scene.lensFlareSystems.splice(index, 1);
  46019. };
  46020. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46021. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46022. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46023. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46024. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46025. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46026. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46027. var parsedFlare = parsedLensFlareSystem.flares[index];
  46028. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46029. }
  46030. return lensFlareSystem;
  46031. };
  46032. LensFlareSystem.prototype.serialize = function () {
  46033. var serializationObject = {};
  46034. serializationObject.id = this.id;
  46035. serializationObject.name = this.name;
  46036. serializationObject.emitterId = this.getEmitter().id;
  46037. serializationObject.borderLimit = this.borderLimit;
  46038. serializationObject.flares = [];
  46039. for (var index = 0; index < this.lensFlares.length; index++) {
  46040. var flare = this.lensFlares[index];
  46041. serializationObject.flares.push({
  46042. size: flare.size,
  46043. position: flare.position,
  46044. color: flare.color.asArray(),
  46045. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46046. });
  46047. }
  46048. return serializationObject;
  46049. };
  46050. return LensFlareSystem;
  46051. }());
  46052. BABYLON.LensFlareSystem = LensFlareSystem;
  46053. })(BABYLON || (BABYLON = {}));
  46054. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46055. var BABYLON;
  46056. (function (BABYLON) {
  46057. // We're mainly based on the logic defined into the FreeCamera code
  46058. var DeviceOrientationCamera = (function (_super) {
  46059. __extends(DeviceOrientationCamera, _super);
  46060. function DeviceOrientationCamera(name, position, scene) {
  46061. _super.call(this, name, position, scene);
  46062. this._quaternionCache = new BABYLON.Quaternion();
  46063. this.inputs.addDeviceOrientation();
  46064. }
  46065. DeviceOrientationCamera.prototype.getTypeName = function () {
  46066. return "DeviceOrientationCamera";
  46067. };
  46068. DeviceOrientationCamera.prototype._checkInputs = function () {
  46069. _super.prototype._checkInputs.call(this);
  46070. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46071. if (this._initialQuaternion) {
  46072. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46073. }
  46074. };
  46075. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46076. var _this = this;
  46077. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46078. //can only work if this camera has a rotation quaternion already.
  46079. if (!this.rotationQuaternion)
  46080. return;
  46081. if (!this._initialQuaternion) {
  46082. this._initialQuaternion = new BABYLON.Quaternion();
  46083. }
  46084. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46085. ['x', 'y', 'z'].forEach(function (axisName) {
  46086. if (!axis[axisName]) {
  46087. _this._initialQuaternion[axisName] = 0;
  46088. }
  46089. else {
  46090. _this._initialQuaternion[axisName] *= -1;
  46091. }
  46092. });
  46093. this._initialQuaternion.normalize();
  46094. //force rotation update
  46095. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46096. };
  46097. return DeviceOrientationCamera;
  46098. }(BABYLON.FreeCamera));
  46099. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46100. })(BABYLON || (BABYLON = {}));
  46101. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46102. var BABYLON;
  46103. (function (BABYLON) {
  46104. var VRDeviceOrientationFreeCamera = (function (_super) {
  46105. __extends(VRDeviceOrientationFreeCamera, _super);
  46106. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46107. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46108. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46109. _super.call(this, name, position, scene);
  46110. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46111. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46112. }
  46113. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  46114. return "VRDeviceOrientationFreeCamera";
  46115. };
  46116. return VRDeviceOrientationFreeCamera;
  46117. }(BABYLON.DeviceOrientationCamera));
  46118. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46119. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46120. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46121. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46122. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46123. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46124. _super.call(this, name, alpha, beta, radius, target, scene);
  46125. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46126. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46127. this.inputs.addVRDeviceOrientation();
  46128. }
  46129. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  46130. return "VRDeviceOrientationArcRotateCamera";
  46131. };
  46132. return VRDeviceOrientationArcRotateCamera;
  46133. }(BABYLON.ArcRotateCamera));
  46134. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46135. })(BABYLON || (BABYLON = {}));
  46136. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46137. var BABYLON;
  46138. (function (BABYLON) {
  46139. // We're mainly based on the logic defined into the FreeCamera code
  46140. var UniversalCamera = (function (_super) {
  46141. __extends(UniversalCamera, _super);
  46142. //-- end properties for backward compatibility for inputs
  46143. function UniversalCamera(name, position, scene) {
  46144. _super.call(this, name, position, scene);
  46145. this.inputs.addGamepad();
  46146. }
  46147. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46148. //-- Begin properties for backward compatibility for inputs
  46149. get: function () {
  46150. var gamepad = this.inputs.attached["gamepad"];
  46151. if (gamepad)
  46152. return gamepad.gamepadAngularSensibility;
  46153. },
  46154. set: function (value) {
  46155. var gamepad = this.inputs.attached["gamepad"];
  46156. if (gamepad)
  46157. gamepad.gamepadAngularSensibility = value;
  46158. },
  46159. enumerable: true,
  46160. configurable: true
  46161. });
  46162. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46163. get: function () {
  46164. var gamepad = this.inputs.attached["gamepad"];
  46165. if (gamepad)
  46166. return gamepad.gamepadMoveSensibility;
  46167. },
  46168. set: function (value) {
  46169. var gamepad = this.inputs.attached["gamepad"];
  46170. if (gamepad)
  46171. gamepad.gamepadMoveSensibility = value;
  46172. },
  46173. enumerable: true,
  46174. configurable: true
  46175. });
  46176. UniversalCamera.prototype.getTypeName = function () {
  46177. return "UniversalCamera";
  46178. };
  46179. return UniversalCamera;
  46180. }(BABYLON.TouchCamera));
  46181. BABYLON.UniversalCamera = UniversalCamera;
  46182. })(BABYLON || (BABYLON = {}));
  46183. //# sourceMappingURL=babylon.universalCamera.js.map
  46184. var BABYLON;
  46185. (function (BABYLON) {
  46186. var Gamepads = (function () {
  46187. function Gamepads(ongamedpadconnected) {
  46188. var _this = this;
  46189. this.babylonGamepads = [];
  46190. this.oneGamepadConnected = false;
  46191. this.isMonitoring = false;
  46192. this.gamepadEventSupported = 'GamepadEvent' in window;
  46193. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46194. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46195. this._callbackGamepadConnected = ongamedpadconnected;
  46196. if (this.gamepadSupportAvailable) {
  46197. // Checking if the gamepad connected event is supported (like in Firefox)
  46198. if (this.gamepadEventSupported) {
  46199. this._onGamepadConnectedEvent = function (evt) {
  46200. _this._onGamepadConnected(evt);
  46201. };
  46202. this._onGamepadDisonnectedEvent = function (evt) {
  46203. _this._onGamepadDisconnected(evt);
  46204. };
  46205. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46206. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46207. }
  46208. else {
  46209. this._startMonitoringGamepads();
  46210. }
  46211. }
  46212. }
  46213. Gamepads.prototype.dispose = function () {
  46214. if (Gamepads.gamepadDOMInfo) {
  46215. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46216. }
  46217. if (this._onGamepadConnectedEvent) {
  46218. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46219. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46220. this._onGamepadConnectedEvent = null;
  46221. this._onGamepadDisonnectedEvent = null;
  46222. }
  46223. };
  46224. Gamepads.prototype._onGamepadConnected = function (evt) {
  46225. var newGamepad = this._addNewGamepad(evt.gamepad);
  46226. if (this._callbackGamepadConnected)
  46227. this._callbackGamepadConnected(newGamepad);
  46228. this._startMonitoringGamepads();
  46229. };
  46230. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46231. if (!this.oneGamepadConnected) {
  46232. this.oneGamepadConnected = true;
  46233. if (Gamepads.gamepadDOMInfo) {
  46234. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46235. Gamepads.gamepadDOMInfo = null;
  46236. }
  46237. }
  46238. var newGamepad;
  46239. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46240. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46241. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46242. }
  46243. else {
  46244. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46245. }
  46246. this.babylonGamepads.push(newGamepad);
  46247. return newGamepad;
  46248. };
  46249. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  46250. // Remove the gamepad from the list of gamepads to monitor.
  46251. for (var i in this.babylonGamepads) {
  46252. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  46253. this.babylonGamepads.splice(+i, 1);
  46254. break;
  46255. }
  46256. }
  46257. // If no gamepads are left, stop the polling loop.
  46258. if (this.babylonGamepads.length == 0) {
  46259. this._stopMonitoringGamepads();
  46260. }
  46261. };
  46262. Gamepads.prototype._startMonitoringGamepads = function () {
  46263. if (!this.isMonitoring) {
  46264. this.isMonitoring = true;
  46265. this._checkGamepadsStatus();
  46266. }
  46267. };
  46268. Gamepads.prototype._stopMonitoringGamepads = function () {
  46269. this.isMonitoring = false;
  46270. };
  46271. Gamepads.prototype._checkGamepadsStatus = function () {
  46272. var _this = this;
  46273. // updating gamepad objects
  46274. this._updateGamepadObjects();
  46275. for (var i in this.babylonGamepads) {
  46276. this.babylonGamepads[i].update();
  46277. }
  46278. if (this.isMonitoring) {
  46279. if (window.requestAnimationFrame) {
  46280. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46281. }
  46282. else if (window.mozRequestAnimationFrame) {
  46283. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46284. }
  46285. else if (window.webkitRequestAnimationFrame) {
  46286. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46287. }
  46288. }
  46289. };
  46290. // This function is called only on Chrome, which does not yet support
  46291. // connection/disconnection events, but requires you to monitor
  46292. // an array for changes.
  46293. Gamepads.prototype._updateGamepadObjects = function () {
  46294. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  46295. for (var i = 0; i < gamepads.length; i++) {
  46296. if (gamepads[i]) {
  46297. if (!(gamepads[i].index in this.babylonGamepads)) {
  46298. var newGamepad = this._addNewGamepad(gamepads[i]);
  46299. if (this._callbackGamepadConnected) {
  46300. this._callbackGamepadConnected(newGamepad);
  46301. }
  46302. }
  46303. else {
  46304. this.babylonGamepads[i].browserGamepad = gamepads[i];
  46305. }
  46306. }
  46307. }
  46308. };
  46309. return Gamepads;
  46310. }());
  46311. BABYLON.Gamepads = Gamepads;
  46312. var StickValues = (function () {
  46313. function StickValues(x, y) {
  46314. this.x = x;
  46315. this.y = y;
  46316. }
  46317. return StickValues;
  46318. }());
  46319. BABYLON.StickValues = StickValues;
  46320. var Gamepad = (function () {
  46321. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  46322. if (leftStickX === void 0) { leftStickX = 0; }
  46323. if (leftStickY === void 0) { leftStickY = 1; }
  46324. if (rightStickX === void 0) { rightStickX = 2; }
  46325. if (rightStickY === void 0) { rightStickY = 3; }
  46326. this.id = id;
  46327. this.index = index;
  46328. this.browserGamepad = browserGamepad;
  46329. this._leftStickAxisX = leftStickX;
  46330. this._leftStickAxisY = leftStickY;
  46331. this._rightStickAxisX = rightStickX;
  46332. this._rightStickAxisY = rightStickY;
  46333. if (this.browserGamepad.axes.length >= 2) {
  46334. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46335. }
  46336. if (this.browserGamepad.axes.length >= 4) {
  46337. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46338. }
  46339. }
  46340. Gamepad.prototype.onleftstickchanged = function (callback) {
  46341. this._onleftstickchanged = callback;
  46342. };
  46343. Gamepad.prototype.onrightstickchanged = function (callback) {
  46344. this._onrightstickchanged = callback;
  46345. };
  46346. Object.defineProperty(Gamepad.prototype, "leftStick", {
  46347. get: function () {
  46348. return this._leftStick;
  46349. },
  46350. set: function (newValues) {
  46351. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  46352. this._onleftstickchanged(newValues);
  46353. }
  46354. this._leftStick = newValues;
  46355. },
  46356. enumerable: true,
  46357. configurable: true
  46358. });
  46359. Object.defineProperty(Gamepad.prototype, "rightStick", {
  46360. get: function () {
  46361. return this._rightStick;
  46362. },
  46363. set: function (newValues) {
  46364. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  46365. this._onrightstickchanged(newValues);
  46366. }
  46367. this._rightStick = newValues;
  46368. },
  46369. enumerable: true,
  46370. configurable: true
  46371. });
  46372. Gamepad.prototype.update = function () {
  46373. if (this._leftStick) {
  46374. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46375. }
  46376. if (this._rightStick) {
  46377. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46378. }
  46379. };
  46380. return Gamepad;
  46381. }());
  46382. BABYLON.Gamepad = Gamepad;
  46383. var GenericPad = (function (_super) {
  46384. __extends(GenericPad, _super);
  46385. function GenericPad(id, index, gamepad) {
  46386. _super.call(this, id, index, gamepad);
  46387. this.id = id;
  46388. this.index = index;
  46389. this.gamepad = gamepad;
  46390. this._buttons = new Array(gamepad.buttons.length);
  46391. }
  46392. GenericPad.prototype.onbuttondown = function (callback) {
  46393. this._onbuttondown = callback;
  46394. };
  46395. GenericPad.prototype.onbuttonup = function (callback) {
  46396. this._onbuttonup = callback;
  46397. };
  46398. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  46399. if (newValue !== currentValue) {
  46400. if (this._onbuttondown && newValue === 1) {
  46401. this._onbuttondown(buttonIndex);
  46402. }
  46403. if (this._onbuttonup && newValue === 0) {
  46404. this._onbuttonup(buttonIndex);
  46405. }
  46406. }
  46407. return newValue;
  46408. };
  46409. GenericPad.prototype.update = function () {
  46410. _super.prototype.update.call(this);
  46411. for (var index = 0; index < this._buttons.length; index++) {
  46412. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  46413. }
  46414. };
  46415. return GenericPad;
  46416. }(Gamepad));
  46417. BABYLON.GenericPad = GenericPad;
  46418. (function (Xbox360Button) {
  46419. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  46420. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  46421. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  46422. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  46423. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  46424. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  46425. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  46426. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  46427. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  46428. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  46429. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  46430. var Xbox360Button = BABYLON.Xbox360Button;
  46431. (function (Xbox360Dpad) {
  46432. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  46433. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  46434. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  46435. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  46436. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  46437. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  46438. var Xbox360Pad = (function (_super) {
  46439. __extends(Xbox360Pad, _super);
  46440. function Xbox360Pad(id, index, gamepad, xboxOne) {
  46441. if (xboxOne === void 0) { xboxOne = false; }
  46442. _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3));
  46443. this._leftTrigger = 0;
  46444. this._rightTrigger = 0;
  46445. this._buttonA = 0;
  46446. this._buttonB = 0;
  46447. this._buttonX = 0;
  46448. this._buttonY = 0;
  46449. this._buttonBack = 0;
  46450. this._buttonStart = 0;
  46451. this._buttonLB = 0;
  46452. this._buttonRB = 0;
  46453. this._buttonLeftStick = 0;
  46454. this._buttonRightStick = 0;
  46455. this._dPadUp = 0;
  46456. this._dPadDown = 0;
  46457. this._dPadLeft = 0;
  46458. this._dPadRight = 0;
  46459. this._isXboxOnePad = false;
  46460. this._isXboxOnePad = xboxOne;
  46461. }
  46462. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  46463. this._onlefttriggerchanged = callback;
  46464. };
  46465. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  46466. this._onrighttriggerchanged = callback;
  46467. };
  46468. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  46469. get: function () {
  46470. return this._leftTrigger;
  46471. },
  46472. set: function (newValue) {
  46473. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  46474. this._onlefttriggerchanged(newValue);
  46475. }
  46476. this._leftTrigger = newValue;
  46477. },
  46478. enumerable: true,
  46479. configurable: true
  46480. });
  46481. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  46482. get: function () {
  46483. return this._rightTrigger;
  46484. },
  46485. set: function (newValue) {
  46486. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  46487. this._onrighttriggerchanged(newValue);
  46488. }
  46489. this._rightTrigger = newValue;
  46490. },
  46491. enumerable: true,
  46492. configurable: true
  46493. });
  46494. Xbox360Pad.prototype.onbuttondown = function (callback) {
  46495. this._onbuttondown = callback;
  46496. };
  46497. Xbox360Pad.prototype.onbuttonup = function (callback) {
  46498. this._onbuttonup = callback;
  46499. };
  46500. Xbox360Pad.prototype.ondpaddown = function (callback) {
  46501. this._ondpaddown = callback;
  46502. };
  46503. Xbox360Pad.prototype.ondpadup = function (callback) {
  46504. this._ondpadup = callback;
  46505. };
  46506. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  46507. if (newValue !== currentValue) {
  46508. if (this._onbuttondown && newValue === 1) {
  46509. this._onbuttondown(buttonType);
  46510. }
  46511. if (this._onbuttonup && newValue === 0) {
  46512. this._onbuttonup(buttonType);
  46513. }
  46514. }
  46515. return newValue;
  46516. };
  46517. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  46518. if (newValue !== currentValue) {
  46519. if (this._ondpaddown && newValue === 1) {
  46520. this._ondpaddown(buttonType);
  46521. }
  46522. if (this._ondpadup && newValue === 0) {
  46523. this._ondpadup(buttonType);
  46524. }
  46525. }
  46526. return newValue;
  46527. };
  46528. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  46529. get: function () {
  46530. return this._buttonA;
  46531. },
  46532. set: function (value) {
  46533. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  46534. },
  46535. enumerable: true,
  46536. configurable: true
  46537. });
  46538. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  46539. get: function () {
  46540. return this._buttonB;
  46541. },
  46542. set: function (value) {
  46543. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  46544. },
  46545. enumerable: true,
  46546. configurable: true
  46547. });
  46548. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  46549. get: function () {
  46550. return this._buttonX;
  46551. },
  46552. set: function (value) {
  46553. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  46554. },
  46555. enumerable: true,
  46556. configurable: true
  46557. });
  46558. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  46559. get: function () {
  46560. return this._buttonY;
  46561. },
  46562. set: function (value) {
  46563. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  46564. },
  46565. enumerable: true,
  46566. configurable: true
  46567. });
  46568. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  46569. get: function () {
  46570. return this._buttonStart;
  46571. },
  46572. set: function (value) {
  46573. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  46574. },
  46575. enumerable: true,
  46576. configurable: true
  46577. });
  46578. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  46579. get: function () {
  46580. return this._buttonBack;
  46581. },
  46582. set: function (value) {
  46583. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  46584. },
  46585. enumerable: true,
  46586. configurable: true
  46587. });
  46588. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  46589. get: function () {
  46590. return this._buttonLB;
  46591. },
  46592. set: function (value) {
  46593. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  46594. },
  46595. enumerable: true,
  46596. configurable: true
  46597. });
  46598. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  46599. get: function () {
  46600. return this._buttonRB;
  46601. },
  46602. set: function (value) {
  46603. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  46604. },
  46605. enumerable: true,
  46606. configurable: true
  46607. });
  46608. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  46609. get: function () {
  46610. return this._buttonLeftStick;
  46611. },
  46612. set: function (value) {
  46613. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  46614. },
  46615. enumerable: true,
  46616. configurable: true
  46617. });
  46618. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  46619. get: function () {
  46620. return this._buttonRightStick;
  46621. },
  46622. set: function (value) {
  46623. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  46624. },
  46625. enumerable: true,
  46626. configurable: true
  46627. });
  46628. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  46629. get: function () {
  46630. return this._dPadUp;
  46631. },
  46632. set: function (value) {
  46633. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  46634. },
  46635. enumerable: true,
  46636. configurable: true
  46637. });
  46638. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  46639. get: function () {
  46640. return this._dPadDown;
  46641. },
  46642. set: function (value) {
  46643. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  46644. },
  46645. enumerable: true,
  46646. configurable: true
  46647. });
  46648. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  46649. get: function () {
  46650. return this._dPadLeft;
  46651. },
  46652. set: function (value) {
  46653. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  46654. },
  46655. enumerable: true,
  46656. configurable: true
  46657. });
  46658. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  46659. get: function () {
  46660. return this._dPadRight;
  46661. },
  46662. set: function (value) {
  46663. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  46664. },
  46665. enumerable: true,
  46666. configurable: true
  46667. });
  46668. Xbox360Pad.prototype.update = function () {
  46669. _super.prototype.update.call(this);
  46670. if (this._isXboxOnePad) {
  46671. this.buttonA = this.browserGamepad.buttons[0].value;
  46672. this.buttonB = this.browserGamepad.buttons[1].value;
  46673. this.buttonX = this.browserGamepad.buttons[2].value;
  46674. this.buttonY = this.browserGamepad.buttons[3].value;
  46675. this.buttonLB = this.browserGamepad.buttons[4].value;
  46676. this.buttonRB = this.browserGamepad.buttons[5].value;
  46677. this.leftTrigger = this.browserGamepad.axes[2];
  46678. this.rightTrigger = this.browserGamepad.axes[5];
  46679. this.buttonBack = this.browserGamepad.buttons[9].value;
  46680. this.buttonStart = this.browserGamepad.buttons[8].value;
  46681. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  46682. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  46683. this.dPadUp = this.browserGamepad.buttons[11].value;
  46684. this.dPadDown = this.browserGamepad.buttons[12].value;
  46685. this.dPadLeft = this.browserGamepad.buttons[13].value;
  46686. this.dPadRight = this.browserGamepad.buttons[14].value;
  46687. }
  46688. else {
  46689. this.buttonA = this.browserGamepad.buttons[0].value;
  46690. this.buttonB = this.browserGamepad.buttons[1].value;
  46691. this.buttonX = this.browserGamepad.buttons[2].value;
  46692. this.buttonY = this.browserGamepad.buttons[3].value;
  46693. this.buttonLB = this.browserGamepad.buttons[4].value;
  46694. this.buttonRB = this.browserGamepad.buttons[5].value;
  46695. this.leftTrigger = this.browserGamepad.buttons[6].value;
  46696. this.rightTrigger = this.browserGamepad.buttons[7].value;
  46697. this.buttonBack = this.browserGamepad.buttons[8].value;
  46698. this.buttonStart = this.browserGamepad.buttons[9].value;
  46699. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  46700. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  46701. this.dPadUp = this.browserGamepad.buttons[12].value;
  46702. this.dPadDown = this.browserGamepad.buttons[13].value;
  46703. this.dPadLeft = this.browserGamepad.buttons[14].value;
  46704. this.dPadRight = this.browserGamepad.buttons[15].value;
  46705. }
  46706. };
  46707. return Xbox360Pad;
  46708. }(Gamepad));
  46709. BABYLON.Xbox360Pad = Xbox360Pad;
  46710. })(BABYLON || (BABYLON = {}));
  46711. //# sourceMappingURL=babylon.gamepads.js.map
  46712. var BABYLON;
  46713. (function (BABYLON) {
  46714. // We're mainly based on the logic defined into the FreeCamera code
  46715. var GamepadCamera = (function (_super) {
  46716. __extends(GamepadCamera, _super);
  46717. //-- end properties for backward compatibility for inputs
  46718. function GamepadCamera(name, position, scene) {
  46719. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  46720. _super.call(this, name, position, scene);
  46721. }
  46722. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46723. //-- Begin properties for backward compatibility for inputs
  46724. get: function () {
  46725. var gamepad = this.inputs.attached["gamepad"];
  46726. if (gamepad)
  46727. return gamepad.gamepadAngularSensibility;
  46728. },
  46729. set: function (value) {
  46730. var gamepad = this.inputs.attached["gamepad"];
  46731. if (gamepad)
  46732. gamepad.gamepadAngularSensibility = value;
  46733. },
  46734. enumerable: true,
  46735. configurable: true
  46736. });
  46737. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46738. get: function () {
  46739. var gamepad = this.inputs.attached["gamepad"];
  46740. if (gamepad)
  46741. return gamepad.gamepadMoveSensibility;
  46742. },
  46743. set: function (value) {
  46744. var gamepad = this.inputs.attached["gamepad"];
  46745. if (gamepad)
  46746. gamepad.gamepadMoveSensibility = value;
  46747. },
  46748. enumerable: true,
  46749. configurable: true
  46750. });
  46751. GamepadCamera.prototype.getTypeName = function () {
  46752. return "GamepadCamera";
  46753. };
  46754. return GamepadCamera;
  46755. }(BABYLON.UniversalCamera));
  46756. BABYLON.GamepadCamera = GamepadCamera;
  46757. })(BABYLON || (BABYLON = {}));
  46758. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46759. var BABYLON;
  46760. (function (BABYLON) {
  46761. var Analyser = (function () {
  46762. function Analyser(scene) {
  46763. this.SMOOTHING = 0.75;
  46764. this.FFT_SIZE = 512;
  46765. this.BARGRAPHAMPLITUDE = 256;
  46766. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  46767. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  46768. this._scene = scene;
  46769. this._audioEngine = BABYLON.Engine.audioEngine;
  46770. if (this._audioEngine.canUseWebAudio) {
  46771. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  46772. this._webAudioAnalyser.minDecibels = -140;
  46773. this._webAudioAnalyser.maxDecibels = 0;
  46774. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46775. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46776. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  46777. }
  46778. }
  46779. Analyser.prototype.getFrequencyBinCount = function () {
  46780. if (this._audioEngine.canUseWebAudio) {
  46781. return this._webAudioAnalyser.frequencyBinCount;
  46782. }
  46783. else {
  46784. return 0;
  46785. }
  46786. };
  46787. Analyser.prototype.getByteFrequencyData = function () {
  46788. if (this._audioEngine.canUseWebAudio) {
  46789. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46790. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46791. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  46792. }
  46793. return this._byteFreqs;
  46794. };
  46795. Analyser.prototype.getByteTimeDomainData = function () {
  46796. if (this._audioEngine.canUseWebAudio) {
  46797. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46798. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46799. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  46800. }
  46801. return this._byteTime;
  46802. };
  46803. Analyser.prototype.getFloatFrequencyData = function () {
  46804. if (this._audioEngine.canUseWebAudio) {
  46805. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46806. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46807. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  46808. }
  46809. return this._floatFreqs;
  46810. };
  46811. Analyser.prototype.drawDebugCanvas = function () {
  46812. var _this = this;
  46813. if (this._audioEngine.canUseWebAudio) {
  46814. if (!this._debugCanvas) {
  46815. this._debugCanvas = document.createElement("canvas");
  46816. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  46817. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  46818. this._debugCanvas.style.position = "absolute";
  46819. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  46820. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  46821. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  46822. document.body.appendChild(this._debugCanvas);
  46823. this._registerFunc = function () {
  46824. _this.drawDebugCanvas();
  46825. };
  46826. this._scene.registerBeforeRender(this._registerFunc);
  46827. }
  46828. if (this._registerFunc) {
  46829. var workingArray = this.getByteFrequencyData();
  46830. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  46831. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  46832. // Draw the frequency domain chart.
  46833. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  46834. var value = workingArray[i];
  46835. var percent = value / this.BARGRAPHAMPLITUDE;
  46836. var height = this.DEBUGCANVASSIZE.height * percent;
  46837. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  46838. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  46839. var hue = i / this.getFrequencyBinCount() * 360;
  46840. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  46841. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  46842. }
  46843. }
  46844. }
  46845. };
  46846. Analyser.prototype.stopDebugCanvas = function () {
  46847. if (this._debugCanvas) {
  46848. this._scene.unregisterBeforeRender(this._registerFunc);
  46849. this._registerFunc = null;
  46850. document.body.removeChild(this._debugCanvas);
  46851. this._debugCanvas = null;
  46852. this._debugCanvasContext = null;
  46853. }
  46854. };
  46855. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  46856. if (this._audioEngine.canUseWebAudio) {
  46857. inputAudioNode.connect(this._webAudioAnalyser);
  46858. this._webAudioAnalyser.connect(outputAudioNode);
  46859. }
  46860. };
  46861. Analyser.prototype.dispose = function () {
  46862. if (this._audioEngine.canUseWebAudio) {
  46863. this._webAudioAnalyser.disconnect();
  46864. }
  46865. };
  46866. return Analyser;
  46867. }());
  46868. BABYLON.Analyser = Analyser;
  46869. })(BABYLON || (BABYLON = {}));
  46870. //# sourceMappingURL=babylon.analyser.js.map
  46871. var BABYLON;
  46872. (function (BABYLON) {
  46873. var DepthRenderer = (function () {
  46874. function DepthRenderer(scene, type) {
  46875. var _this = this;
  46876. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  46877. this._viewMatrix = BABYLON.Matrix.Zero();
  46878. this._projectionMatrix = BABYLON.Matrix.Zero();
  46879. this._transformMatrix = BABYLON.Matrix.Zero();
  46880. this._worldViewProjection = BABYLON.Matrix.Zero();
  46881. this._scene = scene;
  46882. var engine = scene.getEngine();
  46883. // Render target
  46884. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  46885. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46886. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46887. this._depthMap.refreshRate = 1;
  46888. this._depthMap.renderParticles = false;
  46889. this._depthMap.renderList = null;
  46890. // set default depth value to 1.0 (far away)
  46891. this._depthMap.onClearObservable.add(function (engine) {
  46892. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46893. });
  46894. // Custom render function
  46895. var renderSubMesh = function (subMesh) {
  46896. var mesh = subMesh.getRenderingMesh();
  46897. var scene = _this._scene;
  46898. var engine = scene.getEngine();
  46899. // Culling
  46900. engine.setState(subMesh.getMaterial().backFaceCulling);
  46901. // Managing instances
  46902. var batch = mesh._getInstancesRenderList(subMesh._id);
  46903. if (batch.mustReturn) {
  46904. return;
  46905. }
  46906. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46907. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46908. engine.enableEffect(_this._effect);
  46909. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  46910. var material = subMesh.getMaterial();
  46911. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  46912. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  46913. // Alpha test
  46914. if (material && material.needAlphaTesting()) {
  46915. var alphaTexture = material.getAlphaTestTexture();
  46916. _this._effect.setTexture("diffuseSampler", alphaTexture);
  46917. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46918. }
  46919. // Bones
  46920. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46921. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46922. }
  46923. // Draw
  46924. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46925. }
  46926. };
  46927. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  46928. var index;
  46929. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46930. renderSubMesh(opaqueSubMeshes.data[index]);
  46931. }
  46932. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46933. renderSubMesh(alphaTestSubMeshes.data[index]);
  46934. }
  46935. };
  46936. }
  46937. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  46938. var material = subMesh.getMaterial();
  46939. if (material.disableDepthWrite) {
  46940. return false;
  46941. }
  46942. var defines = [];
  46943. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46944. var mesh = subMesh.getMesh();
  46945. var scene = mesh.getScene();
  46946. // Alpha test
  46947. if (material && material.needAlphaTesting()) {
  46948. defines.push("#define ALPHATEST");
  46949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46950. attribs.push(BABYLON.VertexBuffer.UVKind);
  46951. defines.push("#define UV1");
  46952. }
  46953. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46954. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46955. defines.push("#define UV2");
  46956. }
  46957. }
  46958. // Bones
  46959. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46960. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46961. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46962. if (mesh.numBoneInfluencers > 4) {
  46963. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46964. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46965. }
  46966. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46967. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46968. }
  46969. else {
  46970. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46971. }
  46972. // Instances
  46973. if (useInstances) {
  46974. defines.push("#define INSTANCES");
  46975. attribs.push("world0");
  46976. attribs.push("world1");
  46977. attribs.push("world2");
  46978. attribs.push("world3");
  46979. }
  46980. // Get correct effect
  46981. var join = defines.join("\n");
  46982. if (this._cachedDefines !== join) {
  46983. this._cachedDefines = join;
  46984. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  46985. }
  46986. return this._effect.isReady();
  46987. };
  46988. DepthRenderer.prototype.getDepthMap = function () {
  46989. return this._depthMap;
  46990. };
  46991. // Methods
  46992. DepthRenderer.prototype.dispose = function () {
  46993. this._depthMap.dispose();
  46994. };
  46995. return DepthRenderer;
  46996. }());
  46997. BABYLON.DepthRenderer = DepthRenderer;
  46998. })(BABYLON || (BABYLON = {}));
  46999. //# sourceMappingURL=babylon.depthRenderer.js.map
  47000. var BABYLON;
  47001. (function (BABYLON) {
  47002. var SSAORenderingPipeline = (function (_super) {
  47003. __extends(SSAORenderingPipeline, _super);
  47004. /**
  47005. * @constructor
  47006. * @param {string} name - The rendering pipeline name
  47007. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47008. * @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 }
  47009. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47010. */
  47011. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47012. var _this = this;
  47013. _super.call(this, scene.getEngine(), name);
  47014. // Members
  47015. /**
  47016. * The PassPostProcess id in the pipeline that contains the original scene color
  47017. * @type {string}
  47018. */
  47019. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47020. /**
  47021. * The SSAO PostProcess id in the pipeline
  47022. * @type {string}
  47023. */
  47024. this.SSAORenderEffect = "SSAORenderEffect";
  47025. /**
  47026. * The horizontal blur PostProcess id in the pipeline
  47027. * @type {string}
  47028. */
  47029. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47030. /**
  47031. * The vertical blur PostProcess id in the pipeline
  47032. * @type {string}
  47033. */
  47034. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47035. /**
  47036. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47037. * @type {string}
  47038. */
  47039. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47040. /**
  47041. * The output strength of the SSAO post-process. Default value is 1.0.
  47042. * @type {number}
  47043. */
  47044. this.totalStrength = 1.0;
  47045. /**
  47046. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47047. * @type {number}
  47048. */
  47049. this.radius = 0.0001;
  47050. /**
  47051. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47052. * Must not be equal to fallOff and superior to fallOff.
  47053. * Default value is 0.975
  47054. * @type {number}
  47055. */
  47056. this.area = 0.0075;
  47057. /**
  47058. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47059. * Must not be equal to area and inferior to area.
  47060. * Default value is 0.0
  47061. * @type {number}
  47062. */
  47063. this.fallOff = 0.000001;
  47064. /**
  47065. * The base color of the SSAO post-process
  47066. * The final result is "base + ssao" between [0, 1]
  47067. * @type {number}
  47068. */
  47069. this.base = 0.5;
  47070. this._firstUpdate = true;
  47071. this._scene = scene;
  47072. // Set up assets
  47073. this._createRandomTexture();
  47074. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47075. var ssaoRatio = ratio.ssaoRatio || ratio;
  47076. var combineRatio = ratio.combineRatio || ratio;
  47077. this._ratio = {
  47078. ssaoRatio: ssaoRatio,
  47079. combineRatio: combineRatio
  47080. };
  47081. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47082. this._createSSAOPostProcess(ssaoRatio);
  47083. this._createBlurPostProcess(ssaoRatio);
  47084. this._createSSAOCombinePostProcess(combineRatio);
  47085. // Set up pipeline
  47086. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47087. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47088. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47089. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47090. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47091. // Finish
  47092. scene.postProcessRenderPipelineManager.addPipeline(this);
  47093. if (cameras)
  47094. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47095. }
  47096. // Public Methods
  47097. /**
  47098. * Returns the horizontal blur PostProcess
  47099. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47100. */
  47101. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47102. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47103. return null;
  47104. };
  47105. /**
  47106. * Returns the vertical blur PostProcess
  47107. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47108. */
  47109. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47110. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47111. return null;
  47112. };
  47113. /**
  47114. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47115. */
  47116. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47117. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47118. for (var i = 0; i < this._scene.cameras.length; i++) {
  47119. var camera = this._scene.cameras[i];
  47120. this._originalColorPostProcess.dispose(camera);
  47121. this._ssaoPostProcess.dispose(camera);
  47122. this._blurHPostProcess.dispose(camera);
  47123. this._blurVPostProcess.dispose(camera);
  47124. this._ssaoCombinePostProcess.dispose(camera);
  47125. }
  47126. this._randomTexture.dispose();
  47127. if (disableDepthRender)
  47128. this._scene.disableDepthRenderer();
  47129. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47130. };
  47131. // Private Methods
  47132. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47133. var _this = this;
  47134. /*
  47135. var samplerOffsets = [
  47136. -8.0, -6.0, -4.0, -2.0,
  47137. 0.0,
  47138. 2.0, 4.0, 6.0, 8.0
  47139. ];
  47140. */
  47141. var samples = 16;
  47142. var samplerOffsets = [];
  47143. for (var i = -8; i < 8; i++) {
  47144. samplerOffsets.push(i * 2);
  47145. }
  47146. 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");
  47147. this._blurHPostProcess.onApply = function (effect) {
  47148. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47149. effect.setTexture("depthSampler", _this._depthTexture);
  47150. if (_this._firstUpdate) {
  47151. effect.setArray("samplerOffsets", samplerOffsets);
  47152. }
  47153. };
  47154. 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");
  47155. this._blurVPostProcess.onApply = function (effect) {
  47156. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47157. effect.setTexture("depthSampler", _this._depthTexture);
  47158. if (_this._firstUpdate) {
  47159. effect.setArray("samplerOffsets", samplerOffsets);
  47160. _this._firstUpdate = false;
  47161. }
  47162. };
  47163. };
  47164. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47165. var _this = this;
  47166. var numSamples = 16;
  47167. var sampleSphere = [
  47168. 0.5381, 0.1856, -0.4319,
  47169. 0.1379, 0.2486, 0.4430,
  47170. 0.3371, 0.5679, -0.0057,
  47171. -0.6999, -0.0451, -0.0019,
  47172. 0.0689, -0.1598, -0.8547,
  47173. 0.0560, 0.0069, -0.1843,
  47174. -0.0146, 0.1402, 0.0762,
  47175. 0.0100, -0.1924, -0.0344,
  47176. -0.3577, -0.5301, -0.4358,
  47177. -0.3169, 0.1063, 0.0158,
  47178. 0.0103, -0.5869, 0.0046,
  47179. -0.0897, -0.4940, 0.3287,
  47180. 0.7119, -0.0154, -0.0918,
  47181. -0.0533, 0.0596, -0.5411,
  47182. 0.0352, -0.0631, 0.5460,
  47183. -0.4776, 0.2847, -0.0271
  47184. ];
  47185. var samplesFactor = 1.0 / numSamples;
  47186. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47187. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47188. "area", "fallOff", "base", "range", "viewport"
  47189. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47190. var viewport = new BABYLON.Vector2(0, 0);
  47191. this._ssaoPostProcess.onApply = function (effect) {
  47192. if (_this._firstUpdate) {
  47193. effect.setArray3("sampleSphere", sampleSphere);
  47194. effect.setFloat("samplesFactor", samplesFactor);
  47195. effect.setFloat("randTextureTiles", 4.0);
  47196. }
  47197. effect.setFloat("totalStrength", _this.totalStrength);
  47198. effect.setFloat("radius", _this.radius);
  47199. effect.setFloat("area", _this.area);
  47200. effect.setFloat("fallOff", _this.fallOff);
  47201. effect.setFloat("base", _this.base);
  47202. effect.setTexture("textureSampler", _this._depthTexture);
  47203. effect.setTexture("randomSampler", _this._randomTexture);
  47204. };
  47205. };
  47206. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47207. var _this = this;
  47208. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47209. this._ssaoCombinePostProcess.onApply = function (effect) {
  47210. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47211. };
  47212. };
  47213. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47214. var size = 512;
  47215. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47216. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47217. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47218. var context = this._randomTexture.getContext();
  47219. var rand = function (min, max) {
  47220. return Math.random() * (max - min) + min;
  47221. };
  47222. var randVector = BABYLON.Vector3.Zero();
  47223. for (var x = 0; x < size; x++) {
  47224. for (var y = 0; y < size; y++) {
  47225. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47226. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47227. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47228. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47229. context.fillRect(x, y, 1, 1);
  47230. }
  47231. }
  47232. this._randomTexture.update(false);
  47233. };
  47234. __decorate([
  47235. BABYLON.serialize()
  47236. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47237. __decorate([
  47238. BABYLON.serialize()
  47239. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47240. __decorate([
  47241. BABYLON.serialize()
  47242. ], SSAORenderingPipeline.prototype, "area", void 0);
  47243. __decorate([
  47244. BABYLON.serialize()
  47245. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47246. __decorate([
  47247. BABYLON.serialize()
  47248. ], SSAORenderingPipeline.prototype, "base", void 0);
  47249. __decorate([
  47250. BABYLON.serialize()
  47251. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47252. return SSAORenderingPipeline;
  47253. }(BABYLON.PostProcessRenderPipeline));
  47254. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47255. })(BABYLON || (BABYLON = {}));
  47256. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47257. var BABYLON;
  47258. (function (BABYLON) {
  47259. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47260. var VolumetricLightScatteringPostProcess = (function (_super) {
  47261. __extends(VolumetricLightScatteringPostProcess, _super);
  47262. /**
  47263. * @constructor
  47264. * @param {string} name - The post-process name
  47265. * @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)
  47266. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47267. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47268. * @param {number} samples - The post-process quality, default 100
  47269. * @param {number} samplingMode - The post-process filtering mode
  47270. * @param {BABYLON.Engine} engine - The babylon engine
  47271. * @param {boolean} reusable - If the post-process is reusable
  47272. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47273. */
  47274. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47275. var _this = this;
  47276. if (samples === void 0) { samples = 100; }
  47277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47278. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  47279. this._screenCoordinates = BABYLON.Vector2.Zero();
  47280. /**
  47281. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47282. * @type {Vector3}
  47283. */
  47284. this.customMeshPosition = BABYLON.Vector3.Zero();
  47285. /**
  47286. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47287. * @type {boolean}
  47288. */
  47289. this.useCustomMeshPosition = false;
  47290. /**
  47291. * If the post-process should inverse the light scattering direction
  47292. * @type {boolean}
  47293. */
  47294. this.invert = true;
  47295. /**
  47296. * Array containing the excluded meshes not rendered in the internal pass
  47297. */
  47298. this.excludedMeshes = new Array();
  47299. /**
  47300. * Controls the overall intensity of the post-process
  47301. * @type {number}
  47302. */
  47303. this.exposure = 0.3;
  47304. /**
  47305. * Dissipates each sample's contribution in range [0, 1]
  47306. * @type {number}
  47307. */
  47308. this.decay = 0.96815;
  47309. /**
  47310. * Controls the overall intensity of each sample
  47311. * @type {number}
  47312. */
  47313. this.weight = 0.58767;
  47314. /**
  47315. * Controls the density of each sample
  47316. * @type {number}
  47317. */
  47318. this.density = 0.926;
  47319. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47320. var engine = scene.getEngine();
  47321. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47322. // Configure mesh
  47323. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47324. // Configure
  47325. this._createPass(scene, ratio.passRatio || ratio);
  47326. this.onActivate = function (camera) {
  47327. if (!_this.isSupported) {
  47328. _this.dispose(camera);
  47329. }
  47330. _this.onActivate = null;
  47331. };
  47332. this.onApplyObservable.add(function (effect) {
  47333. _this._updateMeshScreenCoordinates(scene);
  47334. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47335. effect.setFloat("exposure", _this.exposure);
  47336. effect.setFloat("decay", _this.decay);
  47337. effect.setFloat("weight", _this.weight);
  47338. effect.setFloat("density", _this.density);
  47339. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47340. });
  47341. }
  47342. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47343. get: function () {
  47344. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47345. return false;
  47346. },
  47347. set: function (useDiffuseColor) {
  47348. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47349. },
  47350. enumerable: true,
  47351. configurable: true
  47352. });
  47353. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47354. var mesh = subMesh.getMesh();
  47355. // Render this.mesh as default
  47356. if (mesh === this.mesh) {
  47357. return mesh.material.isReady(mesh);
  47358. }
  47359. var defines = [];
  47360. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47361. var material = subMesh.getMaterial();
  47362. var needUV = false;
  47363. // Alpha test
  47364. if (material) {
  47365. if (material.needAlphaTesting()) {
  47366. defines.push("#define ALPHATEST");
  47367. }
  47368. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47369. attribs.push(BABYLON.VertexBuffer.UVKind);
  47370. defines.push("#define UV1");
  47371. }
  47372. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47373. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47374. defines.push("#define UV2");
  47375. }
  47376. }
  47377. // Bones
  47378. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47379. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47380. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47381. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47382. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47383. }
  47384. else {
  47385. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47386. }
  47387. // Instances
  47388. if (useInstances) {
  47389. defines.push("#define INSTANCES");
  47390. attribs.push("world0");
  47391. attribs.push("world1");
  47392. attribs.push("world2");
  47393. attribs.push("world3");
  47394. }
  47395. // Get correct effect
  47396. var join = defines.join("\n");
  47397. if (this._cachedDefines !== join) {
  47398. this._cachedDefines = join;
  47399. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47400. }
  47401. return this._volumetricLightScatteringPass.isReady();
  47402. };
  47403. /**
  47404. * Sets the new light position for light scattering effect
  47405. * @param {BABYLON.Vector3} The new custom light position
  47406. */
  47407. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47408. this.customMeshPosition = position;
  47409. };
  47410. /**
  47411. * Returns the light position for light scattering effect
  47412. * @return {BABYLON.Vector3} The custom light position
  47413. */
  47414. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47415. return this.customMeshPosition;
  47416. };
  47417. /**
  47418. * Disposes the internal assets and detaches the post-process from the camera
  47419. */
  47420. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47421. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47422. if (rttIndex !== -1) {
  47423. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47424. }
  47425. this._volumetricLightScatteringRTT.dispose();
  47426. _super.prototype.dispose.call(this, camera);
  47427. };
  47428. /**
  47429. * Returns the render target texture used by the post-process
  47430. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47431. */
  47432. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47433. return this._volumetricLightScatteringRTT;
  47434. };
  47435. // Private methods
  47436. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47437. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47438. return true;
  47439. }
  47440. return false;
  47441. };
  47442. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47443. var _this = this;
  47444. var engine = scene.getEngine();
  47445. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47446. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47447. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47448. this._volumetricLightScatteringRTT.renderList = null;
  47449. this._volumetricLightScatteringRTT.renderParticles = false;
  47450. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47451. // Custom render function for submeshes
  47452. var renderSubMesh = function (subMesh) {
  47453. var mesh = subMesh.getRenderingMesh();
  47454. if (_this._meshExcluded(mesh)) {
  47455. return;
  47456. }
  47457. var scene = mesh.getScene();
  47458. var engine = scene.getEngine();
  47459. // Culling
  47460. engine.setState(subMesh.getMaterial().backFaceCulling);
  47461. // Managing instances
  47462. var batch = mesh._getInstancesRenderList(subMesh._id);
  47463. if (batch.mustReturn) {
  47464. return;
  47465. }
  47466. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47467. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47468. var effect = _this._volumetricLightScatteringPass;
  47469. if (mesh === _this.mesh) {
  47470. effect = subMesh.getMaterial().getEffect();
  47471. }
  47472. engine.enableEffect(effect);
  47473. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47474. if (mesh === _this.mesh) {
  47475. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47476. }
  47477. else {
  47478. var material = subMesh.getMaterial();
  47479. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47480. // Alpha test
  47481. if (material && material.needAlphaTesting()) {
  47482. var alphaTexture = material.getAlphaTestTexture();
  47483. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47484. if (alphaTexture) {
  47485. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47486. }
  47487. }
  47488. // Bones
  47489. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47490. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47491. }
  47492. }
  47493. // Draw
  47494. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47495. }
  47496. };
  47497. // Render target texture callbacks
  47498. var savedSceneClearColor;
  47499. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47500. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47501. savedSceneClearColor = scene.clearColor;
  47502. scene.clearColor = sceneClearColor;
  47503. });
  47504. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47505. scene.clearColor = savedSceneClearColor;
  47506. });
  47507. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47508. var engine = scene.getEngine();
  47509. var index;
  47510. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47511. renderSubMesh(opaqueSubMeshes.data[index]);
  47512. }
  47513. engine.setAlphaTesting(true);
  47514. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47515. renderSubMesh(alphaTestSubMeshes.data[index]);
  47516. }
  47517. engine.setAlphaTesting(false);
  47518. if (transparentSubMeshes.length) {
  47519. // Sort sub meshes
  47520. for (index = 0; index < transparentSubMeshes.length; index++) {
  47521. var submesh = transparentSubMeshes.data[index];
  47522. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47523. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47524. }
  47525. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47526. sortedArray.sort(function (a, b) {
  47527. // Alpha index first
  47528. if (a._alphaIndex > b._alphaIndex) {
  47529. return 1;
  47530. }
  47531. if (a._alphaIndex < b._alphaIndex) {
  47532. return -1;
  47533. }
  47534. // Then distance to camera
  47535. if (a._distanceToCamera < b._distanceToCamera) {
  47536. return 1;
  47537. }
  47538. if (a._distanceToCamera > b._distanceToCamera) {
  47539. return -1;
  47540. }
  47541. return 0;
  47542. });
  47543. // Render sub meshes
  47544. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47545. for (index = 0; index < sortedArray.length; index++) {
  47546. renderSubMesh(sortedArray[index]);
  47547. }
  47548. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47549. }
  47550. };
  47551. };
  47552. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47553. var transform = scene.getTransformMatrix();
  47554. var meshPosition;
  47555. if (this.useCustomMeshPosition) {
  47556. meshPosition = this.customMeshPosition;
  47557. }
  47558. else if (this.attachedNode) {
  47559. meshPosition = this.attachedNode.position;
  47560. }
  47561. else {
  47562. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47563. }
  47564. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47565. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47566. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47567. if (this.invert)
  47568. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47569. };
  47570. // Static methods
  47571. /**
  47572. * Creates a default mesh for the Volumeric Light Scattering post-process
  47573. * @param {string} The mesh name
  47574. * @param {BABYLON.Scene} The scene where to create the mesh
  47575. * @return {BABYLON.Mesh} the default mesh
  47576. */
  47577. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47578. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47579. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47580. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47581. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47582. mesh.material = material;
  47583. return mesh;
  47584. };
  47585. __decorate([
  47586. BABYLON.serializeAsVector3()
  47587. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47588. __decorate([
  47589. BABYLON.serialize()
  47590. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47591. __decorate([
  47592. BABYLON.serialize()
  47593. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47594. __decorate([
  47595. BABYLON.serializeAsMeshReference()
  47596. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47597. __decorate([
  47598. BABYLON.serialize()
  47599. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47600. __decorate([
  47601. BABYLON.serialize()
  47602. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47603. __decorate([
  47604. BABYLON.serialize()
  47605. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47606. __decorate([
  47607. BABYLON.serialize()
  47608. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47609. __decorate([
  47610. BABYLON.serialize()
  47611. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47612. return VolumetricLightScatteringPostProcess;
  47613. }(BABYLON.PostProcess));
  47614. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47615. })(BABYLON || (BABYLON = {}));
  47616. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  47617. // BABYLON.JS Chromatic Aberration GLSL Shader
  47618. // Author: Olivier Guyot
  47619. // Separates very slightly R, G and B colors on the edges of the screen
  47620. // Inspired by Francois Tarlier & Martins Upitis
  47621. var BABYLON;
  47622. (function (BABYLON) {
  47623. var LensRenderingPipeline = (function (_super) {
  47624. __extends(LensRenderingPipeline, _super);
  47625. /**
  47626. * @constructor
  47627. *
  47628. * Effect parameters are as follow:
  47629. * {
  47630. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47631. * edge_blur: number; // from 0 to x (1 for realism)
  47632. * distortion: number; // from 0 to x (1 for realism)
  47633. * grain_amount: number; // from 0 to 1
  47634. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47635. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47636. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47637. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47638. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47639. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47640. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47641. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47642. * }
  47643. * Note: if an effect parameter is unset, effect is disabled
  47644. *
  47645. * @param {string} name - The rendering pipeline name
  47646. * @param {object} parameters - An object containing all parameters (see above)
  47647. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47648. * @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)
  47649. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47650. */
  47651. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47652. var _this = this;
  47653. if (ratio === void 0) { ratio = 1.0; }
  47654. _super.call(this, scene.getEngine(), name);
  47655. // Lens effects can be of the following:
  47656. // - chromatic aberration (slight shift of RGB colors)
  47657. // - blur on the edge of the lens
  47658. // - lens distortion
  47659. // - depth-of-field blur & highlights enhancing
  47660. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47661. // - grain effect (noise or custom texture)
  47662. // Two additional texture samplers are needed:
  47663. // - depth map (for depth-of-field)
  47664. // - grain texture
  47665. /**
  47666. * The chromatic aberration PostProcess id in the pipeline
  47667. * @type {string}
  47668. */
  47669. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47670. /**
  47671. * The highlights enhancing PostProcess id in the pipeline
  47672. * @type {string}
  47673. */
  47674. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47675. /**
  47676. * The depth-of-field PostProcess id in the pipeline
  47677. * @type {string}
  47678. */
  47679. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47680. this._scene = scene;
  47681. // Fetch texture samplers
  47682. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47683. if (parameters.grain_texture) {
  47684. this._grainTexture = parameters.grain_texture;
  47685. }
  47686. else {
  47687. this._createGrainTexture();
  47688. }
  47689. // save parameters
  47690. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47691. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47692. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47693. this._distortion = parameters.distortion ? parameters.distortion : 0;
  47694. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47695. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47696. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47697. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47698. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47699. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47700. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47701. // Create effects
  47702. this._createChromaticAberrationPostProcess(ratio);
  47703. this._createHighlightsPostProcess(ratio);
  47704. this._createDepthOfFieldPostProcess(ratio / 4);
  47705. // Set up pipeline
  47706. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47707. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47708. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47709. if (this._highlightsGain === -1) {
  47710. this._disableEffect(this.HighlightsEnhancingEffect, null);
  47711. }
  47712. // Finish
  47713. scene.postProcessRenderPipelineManager.addPipeline(this);
  47714. if (cameras) {
  47715. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47716. }
  47717. }
  47718. // public methods (self explanatory)
  47719. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47720. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47721. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47722. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47723. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47724. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47725. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47726. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47727. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47728. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47729. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47730. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47731. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47732. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47733. };
  47734. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47735. this._highlightsPostProcess.updateEffect();
  47736. };
  47737. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47738. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47739. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47740. this._highlightsGain = amount;
  47741. };
  47742. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47743. if (this._highlightsGain === -1) {
  47744. this._highlightsGain = 1.0;
  47745. }
  47746. this._highlightsThreshold = amount;
  47747. };
  47748. LensRenderingPipeline.prototype.disableHighlights = function () {
  47749. this._highlightsGain = -1;
  47750. };
  47751. /**
  47752. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47753. */
  47754. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47755. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47756. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47757. this._chromaticAberrationPostProcess = undefined;
  47758. this._highlightsPostProcess = undefined;
  47759. this._depthOfFieldPostProcess = undefined;
  47760. this._grainTexture.dispose();
  47761. if (disableDepthRender)
  47762. this._scene.disableDepthRenderer();
  47763. };
  47764. // colors shifting and distortion
  47765. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47766. var _this = this;
  47767. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47768. [], // samplers
  47769. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47770. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47771. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47772. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47773. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47774. };
  47775. };
  47776. // highlights enhancing
  47777. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47778. var _this = this;
  47779. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47780. [], // samplers
  47781. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47782. this._highlightsPostProcess.onApply = function (effect) {
  47783. effect.setFloat('gain', _this._highlightsGain);
  47784. effect.setFloat('threshold', _this._highlightsThreshold);
  47785. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47786. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47787. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47788. };
  47789. };
  47790. // colors shifting and distortion
  47791. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47792. var _this = this;
  47793. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47794. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47795. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47796. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47797. this._depthOfFieldPostProcess.onApply = function (effect) {
  47798. effect.setTexture("depthSampler", _this._depthTexture);
  47799. effect.setTexture("grainSampler", _this._grainTexture);
  47800. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47801. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47802. effect.setFloat('grain_amount', _this._grainAmount);
  47803. effect.setBool('blur_noise', _this._blurNoise);
  47804. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47805. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47806. effect.setFloat('distortion', _this._distortion);
  47807. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  47808. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  47809. effect.setFloat('aperture', _this._dofAperture);
  47810. effect.setFloat('darken', _this._dofDarken);
  47811. effect.setFloat('edge_blur', _this._edgeBlur);
  47812. effect.setBool('highlights', (_this._highlightsGain !== -1));
  47813. effect.setFloat('near', _this._scene.activeCamera.minZ);
  47814. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  47815. };
  47816. };
  47817. // creates a black and white random noise texture, 512x512
  47818. LensRenderingPipeline.prototype._createGrainTexture = function () {
  47819. var size = 512;
  47820. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47821. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47822. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47823. var context = this._grainTexture.getContext();
  47824. var rand = function (min, max) {
  47825. return Math.random() * (max - min) + min;
  47826. };
  47827. var value;
  47828. for (var x = 0; x < size; x++) {
  47829. for (var y = 0; y < size; y++) {
  47830. value = Math.floor(rand(0.42, 0.58) * 255);
  47831. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  47832. context.fillRect(x, y, 1, 1);
  47833. }
  47834. }
  47835. this._grainTexture.update(false);
  47836. };
  47837. return LensRenderingPipeline;
  47838. }(BABYLON.PostProcessRenderPipeline));
  47839. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  47840. })(BABYLON || (BABYLON = {}));
  47841. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  47842. //
  47843. // This post-process allows the modification of rendered colors by using
  47844. // a 'look-up table' (LUT). This effect is also called Color Grading.
  47845. //
  47846. // The object needs to be provided an url to a texture containing the color
  47847. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  47848. // Use an image editing software to tweak the LUT to match your needs.
  47849. //
  47850. // For an example of a color LUT, see here:
  47851. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  47852. // For explanations on color grading, see here:
  47853. // http://udn.epicgames.com/Three/ColorGrading.html
  47854. //
  47855. var BABYLON;
  47856. (function (BABYLON) {
  47857. var ColorCorrectionPostProcess = (function (_super) {
  47858. __extends(ColorCorrectionPostProcess, _super);
  47859. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  47860. var _this = this;
  47861. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  47862. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47863. this._colorTableTexture.anisotropicFilteringLevel = 1;
  47864. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47865. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47866. this.onApply = function (effect) {
  47867. effect.setTexture("colorTable", _this._colorTableTexture);
  47868. };
  47869. }
  47870. return ColorCorrectionPostProcess;
  47871. }(BABYLON.PostProcess));
  47872. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  47873. })(BABYLON || (BABYLON = {}));
  47874. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  47875. var BABYLON;
  47876. (function (BABYLON) {
  47877. var AnaglyphFreeCamera = (function (_super) {
  47878. __extends(AnaglyphFreeCamera, _super);
  47879. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  47880. _super.call(this, name, position, scene);
  47881. this.interaxialDistance = interaxialDistance;
  47882. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47883. }
  47884. AnaglyphFreeCamera.prototype.getTypeName = function () {
  47885. return "AnaglyphFreeCamera";
  47886. };
  47887. return AnaglyphFreeCamera;
  47888. }(BABYLON.FreeCamera));
  47889. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  47890. var AnaglyphArcRotateCamera = (function (_super) {
  47891. __extends(AnaglyphArcRotateCamera, _super);
  47892. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  47893. _super.call(this, name, alpha, beta, radius, target, scene);
  47894. this.interaxialDistance = interaxialDistance;
  47895. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47896. }
  47897. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  47898. return "AnaglyphArcRotateCamera";
  47899. };
  47900. return AnaglyphArcRotateCamera;
  47901. }(BABYLON.ArcRotateCamera));
  47902. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  47903. var AnaglyphGamepadCamera = (function (_super) {
  47904. __extends(AnaglyphGamepadCamera, _super);
  47905. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  47906. _super.call(this, name, position, scene);
  47907. this.interaxialDistance = interaxialDistance;
  47908. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47909. }
  47910. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  47911. return "AnaglyphGamepadCamera";
  47912. };
  47913. return AnaglyphGamepadCamera;
  47914. }(BABYLON.GamepadCamera));
  47915. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  47916. var AnaglyphUniversalCamera = (function (_super) {
  47917. __extends(AnaglyphUniversalCamera, _super);
  47918. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  47919. _super.call(this, name, position, scene);
  47920. this.interaxialDistance = interaxialDistance;
  47921. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47922. }
  47923. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  47924. return "AnaglyphUniversalCamera";
  47925. };
  47926. return AnaglyphUniversalCamera;
  47927. }(BABYLON.UniversalCamera));
  47928. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  47929. var StereoscopicFreeCamera = (function (_super) {
  47930. __extends(StereoscopicFreeCamera, _super);
  47931. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  47932. _super.call(this, name, position, scene);
  47933. this.interaxialDistance = interaxialDistance;
  47934. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47935. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47936. }
  47937. StereoscopicFreeCamera.prototype.getTypeName = function () {
  47938. return "StereoscopicFreeCamera";
  47939. };
  47940. return StereoscopicFreeCamera;
  47941. }(BABYLON.FreeCamera));
  47942. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  47943. var StereoscopicArcRotateCamera = (function (_super) {
  47944. __extends(StereoscopicArcRotateCamera, _super);
  47945. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  47946. _super.call(this, name, alpha, beta, radius, target, scene);
  47947. this.interaxialDistance = interaxialDistance;
  47948. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47949. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47950. }
  47951. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  47952. return "StereoscopicArcRotateCamera";
  47953. };
  47954. return StereoscopicArcRotateCamera;
  47955. }(BABYLON.ArcRotateCamera));
  47956. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  47957. var StereoscopicGamepadCamera = (function (_super) {
  47958. __extends(StereoscopicGamepadCamera, _super);
  47959. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  47960. _super.call(this, name, position, scene);
  47961. this.interaxialDistance = interaxialDistance;
  47962. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47963. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47964. }
  47965. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  47966. return "StereoscopicGamepadCamera";
  47967. };
  47968. return StereoscopicGamepadCamera;
  47969. }(BABYLON.GamepadCamera));
  47970. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  47971. var StereoscopicUniversalCamera = (function (_super) {
  47972. __extends(StereoscopicUniversalCamera, _super);
  47973. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  47974. _super.call(this, name, position, scene);
  47975. this.interaxialDistance = interaxialDistance;
  47976. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47977. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47978. }
  47979. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  47980. return "StereoscopicUniversalCamera";
  47981. };
  47982. return StereoscopicUniversalCamera;
  47983. }(BABYLON.UniversalCamera));
  47984. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  47985. })(BABYLON || (BABYLON = {}));
  47986. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  47987. var BABYLON;
  47988. (function (BABYLON) {
  47989. var HDRRenderingPipeline = (function (_super) {
  47990. __extends(HDRRenderingPipeline, _super);
  47991. /**
  47992. * @constructor
  47993. * @param {string} name - The rendering pipeline name
  47994. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47995. * @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)
  47996. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47997. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47998. */
  47999. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48000. var _this = this;
  48001. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48002. _super.call(this, scene.getEngine(), name);
  48003. /**
  48004. * Public members
  48005. */
  48006. // Gaussian Blur
  48007. /**
  48008. * Gaussian blur coefficient
  48009. * @type {number}
  48010. */
  48011. this.gaussCoeff = 0.3;
  48012. /**
  48013. * Gaussian blur mean
  48014. * @type {number}
  48015. */
  48016. this.gaussMean = 1.0;
  48017. /**
  48018. * Gaussian blur standard deviation
  48019. * @type {number}
  48020. */
  48021. this.gaussStandDev = 0.8;
  48022. /**
  48023. * Gaussian blur multiplier. Multiplies the blur effect
  48024. * @type {number}
  48025. */
  48026. this.gaussMultiplier = 4.0;
  48027. // HDR
  48028. /**
  48029. * Exposure, controls the overall intensity of the pipeline
  48030. * @type {number}
  48031. */
  48032. this.exposure = 1.0;
  48033. /**
  48034. * Minimum luminance that the post-process can output. Luminance is >= 0
  48035. * @type {number}
  48036. */
  48037. this.minimumLuminance = 1.0;
  48038. /**
  48039. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48040. * @type {number}
  48041. */
  48042. this.maximumLuminance = 1e20;
  48043. /**
  48044. * Increase rate for luminance: eye adaptation speed to dark
  48045. * @type {number}
  48046. */
  48047. this.luminanceIncreaserate = 0.5;
  48048. /**
  48049. * Decrease rate for luminance: eye adaptation speed to bright
  48050. * @type {number}
  48051. */
  48052. this.luminanceDecreaseRate = 0.5;
  48053. // Bright pass
  48054. /**
  48055. * Minimum luminance needed to compute HDR
  48056. * @type {number}
  48057. */
  48058. this.brightThreshold = 0.8;
  48059. this._needUpdate = true;
  48060. this._scene = scene;
  48061. // Bright pass
  48062. this._createBrightPassPostProcess(scene, ratio);
  48063. // Down sample X4
  48064. this._createDownSampleX4PostProcess(scene, ratio);
  48065. // Create gaussian blur post-processes
  48066. this._createGaussianBlurPostProcess(scene, ratio);
  48067. // Texture adder
  48068. this._createTextureAdderPostProcess(scene, ratio);
  48069. // Luminance generator
  48070. this._createLuminanceGeneratorPostProcess(scene);
  48071. // HDR
  48072. this._createHDRPostProcess(scene, ratio);
  48073. // Pass postprocess
  48074. if (originalPostProcess === null) {
  48075. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48076. }
  48077. else {
  48078. this._originalPostProcess = originalPostProcess;
  48079. }
  48080. // Configure pipeline
  48081. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48082. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48083. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48084. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48085. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48086. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48087. var addDownSamplerPostProcess = function (id) {
  48088. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48089. };
  48090. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48091. addDownSamplerPostProcess(i);
  48092. }
  48093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48094. // Finish
  48095. scene.postProcessRenderPipelineManager.addPipeline(this);
  48096. if (cameras !== null) {
  48097. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48098. }
  48099. this.update();
  48100. }
  48101. /**
  48102. * Tells the pipeline to update its post-processes
  48103. */
  48104. HDRRenderingPipeline.prototype.update = function () {
  48105. this._needUpdate = true;
  48106. };
  48107. /**
  48108. * Returns the current calculated luminance
  48109. */
  48110. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48111. return this._hdrCurrentLuminance;
  48112. };
  48113. /**
  48114. * Returns the currently drawn luminance
  48115. */
  48116. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48117. return this._hdrOutputLuminance;
  48118. };
  48119. /**
  48120. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48121. */
  48122. HDRRenderingPipeline.prototype.dispose = function () {
  48123. this._originalPostProcess = undefined;
  48124. this._brightPassPostProcess = undefined;
  48125. this._downSampleX4PostProcess = undefined;
  48126. this._guassianBlurHPostProcess = undefined;
  48127. this._guassianBlurVPostProcess = undefined;
  48128. this._textureAdderPostProcess = undefined;
  48129. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48130. this._downSamplePostProcesses[i] = undefined;
  48131. }
  48132. this._hdrPostProcess = undefined;
  48133. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48134. };
  48135. /**
  48136. * Creates the HDR post-process and computes the luminance adaptation
  48137. */
  48138. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  48139. var _this = this;
  48140. var hdrLastLuminance = 0.0;
  48141. this._hdrOutputLuminance = -1.0;
  48142. this._hdrCurrentLuminance = 1.0;
  48143. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  48144. this._hdrPostProcess.onApply = function (effect) {
  48145. if (_this._hdrOutputLuminance < 0.0) {
  48146. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48147. }
  48148. else {
  48149. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  48150. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  48151. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  48152. }
  48153. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  48154. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  48155. }
  48156. else {
  48157. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48158. }
  48159. }
  48160. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  48161. hdrLastLuminance += scene.getEngine().getDeltaTime();
  48162. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48163. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48164. effect.setFloat("exposure", _this.exposure);
  48165. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  48166. _this._needUpdate = false;
  48167. };
  48168. };
  48169. /**
  48170. * Texture Adder post-process
  48171. */
  48172. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48173. var _this = this;
  48174. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  48175. this._textureAdderPostProcess.onApply = function (effect) {
  48176. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48177. };
  48178. };
  48179. /**
  48180. * Down sample X4 post-process
  48181. */
  48182. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48183. var _this = this;
  48184. var downSampleX4Offsets = new Array(32);
  48185. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  48186. this._downSampleX4PostProcess.onApply = function (effect) {
  48187. if (_this._needUpdate) {
  48188. var id = 0;
  48189. for (var i = -2; i < 2; i++) {
  48190. for (var j = -2; j < 2; j++) {
  48191. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  48192. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  48193. id += 2;
  48194. }
  48195. }
  48196. }
  48197. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48198. };
  48199. };
  48200. /**
  48201. * Bright pass post-process
  48202. */
  48203. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48204. var _this = this;
  48205. var brightOffsets = new Array(8);
  48206. var brightPassCallback = function (effect) {
  48207. if (_this._needUpdate) {
  48208. var sU = (1.0 / _this._brightPassPostProcess.width);
  48209. var sV = (1.0 / _this._brightPassPostProcess.height);
  48210. brightOffsets[0] = -0.5 * sU;
  48211. brightOffsets[1] = 0.5 * sV;
  48212. brightOffsets[2] = 0.5 * sU;
  48213. brightOffsets[3] = 0.5 * sV;
  48214. brightOffsets[4] = -0.5 * sU;
  48215. brightOffsets[5] = -0.5 * sV;
  48216. brightOffsets[6] = 0.5 * sU;
  48217. brightOffsets[7] = -0.5 * sV;
  48218. }
  48219. effect.setArray2("dsOffsets", brightOffsets);
  48220. effect.setFloat("brightThreshold", _this.brightThreshold);
  48221. };
  48222. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  48223. this._brightPassPostProcess.onApply = brightPassCallback;
  48224. };
  48225. /**
  48226. * Luminance generator. Creates the luminance post-process and down sample post-processes
  48227. */
  48228. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  48229. var _this = this;
  48230. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  48231. var luminanceOffsets = new Array(8);
  48232. var downSampleOffsets = new Array(18);
  48233. var halfDestPixelSize;
  48234. this._downSamplePostProcesses = new Array(lumSteps);
  48235. // Utils for luminance
  48236. var luminanceUpdateSourceOffsets = function (width, height) {
  48237. var sU = (1.0 / width);
  48238. var sV = (1.0 / height);
  48239. luminanceOffsets[0] = -0.5 * sU;
  48240. luminanceOffsets[1] = 0.5 * sV;
  48241. luminanceOffsets[2] = 0.5 * sU;
  48242. luminanceOffsets[3] = 0.5 * sV;
  48243. luminanceOffsets[4] = -0.5 * sU;
  48244. luminanceOffsets[5] = -0.5 * sV;
  48245. luminanceOffsets[6] = 0.5 * sU;
  48246. luminanceOffsets[7] = -0.5 * sV;
  48247. };
  48248. var luminanceUpdateDestOffsets = function (width, height) {
  48249. var id = 0;
  48250. for (var x = -1; x < 2; x++) {
  48251. for (var y = -1; y < 2; y++) {
  48252. downSampleOffsets[id] = (x) / width;
  48253. downSampleOffsets[id + 1] = (y) / height;
  48254. id += 2;
  48255. }
  48256. }
  48257. };
  48258. // Luminance callback
  48259. var luminanceCallback = function (effect) {
  48260. if (_this._needUpdate) {
  48261. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  48262. }
  48263. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48264. effect.setArray2("lumOffsets", luminanceOffsets);
  48265. };
  48266. // Down sample callbacks
  48267. var downSampleCallback = function (indice) {
  48268. var i = indice;
  48269. return function (effect) {
  48270. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48271. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48272. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  48273. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  48274. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  48275. effect.setArray2("dsOffsets", downSampleOffsets);
  48276. };
  48277. };
  48278. var downSampleAfterRenderCallback = function (effect) {
  48279. // Unpack result
  48280. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48281. 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);
  48282. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48283. };
  48284. // Create luminance post-process
  48285. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  48286. 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);
  48287. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  48288. // Create down sample post-processes
  48289. for (var i = lumSteps - 2; i >= 0; i--) {
  48290. var length = Math.pow(3, i);
  48291. ratio = { width: length, height: length };
  48292. var defines = "#define DOWN_SAMPLE\n";
  48293. if (i === 0) {
  48294. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  48295. }
  48296. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48297. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  48298. if (i === 0) {
  48299. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  48300. }
  48301. }
  48302. };
  48303. /**
  48304. * Gaussian blur post-processes. Horizontal and Vertical
  48305. */
  48306. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  48307. var _this = this;
  48308. var blurOffsetsW = new Array(9);
  48309. var blurOffsetsH = new Array(9);
  48310. var blurWeights = new Array(9);
  48311. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  48312. // Utils for gaussian blur
  48313. var calculateBlurOffsets = function (height) {
  48314. var lastOutputDimensions = {
  48315. width: scene.getEngine().getRenderWidth(),
  48316. height: scene.getEngine().getRenderHeight()
  48317. };
  48318. for (var i = 0; i < 9; i++) {
  48319. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48320. if (height) {
  48321. blurOffsetsH[i] = value;
  48322. }
  48323. else {
  48324. blurOffsetsW[i] = value;
  48325. }
  48326. }
  48327. };
  48328. var calculateWeights = function () {
  48329. var x = 0.0;
  48330. for (var i = 0; i < 9; i++) {
  48331. x = (i - 4.0) / 4.0;
  48332. 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));
  48333. }
  48334. };
  48335. // Callback
  48336. var gaussianBlurCallback = function (height) {
  48337. return function (effect) {
  48338. if (_this._needUpdate) {
  48339. calculateWeights();
  48340. calculateBlurOffsets(height);
  48341. }
  48342. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  48343. effect.setArray("blurWeights", blurWeights);
  48344. effect.setFloat("multiplier", _this.gaussMultiplier);
  48345. };
  48346. };
  48347. // Create horizontal gaussian blur post-processes
  48348. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  48349. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  48350. // Create vertical gaussian blur post-process
  48351. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  48352. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  48353. };
  48354. // Luminance generator
  48355. HDRRenderingPipeline.LUM_STEPS = 6;
  48356. return HDRRenderingPipeline;
  48357. }(BABYLON.PostProcessRenderPipeline));
  48358. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  48359. })(BABYLON || (BABYLON = {}));
  48360. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  48361. var BABYLON;
  48362. (function (BABYLON) {
  48363. var FaceAdjacencies = (function () {
  48364. function FaceAdjacencies() {
  48365. this.edges = new Array();
  48366. this.edgesConnectedCount = 0;
  48367. }
  48368. return FaceAdjacencies;
  48369. }());
  48370. var EdgesRenderer = (function () {
  48371. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  48372. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  48373. if (epsilon === void 0) { epsilon = 0.95; }
  48374. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  48375. this.edgesWidthScalerForOrthographic = 1000.0;
  48376. this.edgesWidthScalerForPerspective = 50.0;
  48377. this._linesPositions = new Array();
  48378. this._linesNormals = new Array();
  48379. this._linesIndices = new Array();
  48380. this._buffers = {};
  48381. this._checkVerticesInsteadOfIndices = false;
  48382. this._source = source;
  48383. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  48384. this._epsilon = epsilon;
  48385. this._prepareRessources();
  48386. this._generateEdgesLines();
  48387. }
  48388. EdgesRenderer.prototype._prepareRessources = function () {
  48389. if (this._lineShader) {
  48390. return;
  48391. }
  48392. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  48393. attributes: ["position", "normal"],
  48394. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  48395. });
  48396. this._lineShader.disableDepthWrite = true;
  48397. this._lineShader.backFaceCulling = false;
  48398. };
  48399. EdgesRenderer.prototype.dispose = function () {
  48400. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  48401. if (buffer) {
  48402. buffer.dispose();
  48403. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  48404. }
  48405. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  48406. if (buffer) {
  48407. buffer.dispose();
  48408. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  48409. }
  48410. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  48411. this._lineShader.dispose();
  48412. };
  48413. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  48414. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  48415. return 0;
  48416. }
  48417. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  48418. return 1;
  48419. }
  48420. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  48421. return 2;
  48422. }
  48423. return -1;
  48424. };
  48425. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  48426. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  48427. return 0;
  48428. }
  48429. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  48430. return 1;
  48431. }
  48432. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  48433. return 2;
  48434. }
  48435. return -1;
  48436. };
  48437. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  48438. var needToCreateLine;
  48439. if (edge === undefined) {
  48440. needToCreateLine = true;
  48441. }
  48442. else {
  48443. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  48444. needToCreateLine = dotProduct < this._epsilon;
  48445. }
  48446. if (needToCreateLine) {
  48447. var offset = this._linesPositions.length / 3;
  48448. var normal = p0.subtract(p1);
  48449. normal.normalize();
  48450. // Positions
  48451. this._linesPositions.push(p0.x);
  48452. this._linesPositions.push(p0.y);
  48453. this._linesPositions.push(p0.z);
  48454. this._linesPositions.push(p0.x);
  48455. this._linesPositions.push(p0.y);
  48456. this._linesPositions.push(p0.z);
  48457. this._linesPositions.push(p1.x);
  48458. this._linesPositions.push(p1.y);
  48459. this._linesPositions.push(p1.z);
  48460. this._linesPositions.push(p1.x);
  48461. this._linesPositions.push(p1.y);
  48462. this._linesPositions.push(p1.z);
  48463. // Normals
  48464. this._linesNormals.push(p1.x);
  48465. this._linesNormals.push(p1.y);
  48466. this._linesNormals.push(p1.z);
  48467. this._linesNormals.push(-1);
  48468. this._linesNormals.push(p1.x);
  48469. this._linesNormals.push(p1.y);
  48470. this._linesNormals.push(p1.z);
  48471. this._linesNormals.push(1);
  48472. this._linesNormals.push(p0.x);
  48473. this._linesNormals.push(p0.y);
  48474. this._linesNormals.push(p0.z);
  48475. this._linesNormals.push(-1);
  48476. this._linesNormals.push(p0.x);
  48477. this._linesNormals.push(p0.y);
  48478. this._linesNormals.push(p0.z);
  48479. this._linesNormals.push(1);
  48480. // Indices
  48481. this._linesIndices.push(offset);
  48482. this._linesIndices.push(offset + 1);
  48483. this._linesIndices.push(offset + 2);
  48484. this._linesIndices.push(offset);
  48485. this._linesIndices.push(offset + 2);
  48486. this._linesIndices.push(offset + 3);
  48487. }
  48488. };
  48489. EdgesRenderer.prototype._generateEdgesLines = function () {
  48490. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48491. var indices = this._source.getIndices();
  48492. // First let's find adjacencies
  48493. var adjacencies = new Array();
  48494. var faceNormals = new Array();
  48495. var index;
  48496. var faceAdjacencies;
  48497. // Prepare faces
  48498. for (index = 0; index < indices.length; index += 3) {
  48499. faceAdjacencies = new FaceAdjacencies();
  48500. var p0Index = indices[index];
  48501. var p1Index = indices[index + 1];
  48502. var p2Index = indices[index + 2];
  48503. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  48504. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  48505. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  48506. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  48507. faceNormal.normalize();
  48508. faceNormals.push(faceNormal);
  48509. adjacencies.push(faceAdjacencies);
  48510. }
  48511. // Scan
  48512. for (index = 0; index < adjacencies.length; index++) {
  48513. faceAdjacencies = adjacencies[index];
  48514. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  48515. var otherFaceAdjacencies = adjacencies[otherIndex];
  48516. if (faceAdjacencies.edgesConnectedCount === 3) {
  48517. break;
  48518. }
  48519. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  48520. continue;
  48521. }
  48522. var otherP0 = indices[otherIndex * 3];
  48523. var otherP1 = indices[otherIndex * 3 + 1];
  48524. var otherP2 = indices[otherIndex * 3 + 2];
  48525. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  48526. var otherEdgeIndex;
  48527. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  48528. continue;
  48529. }
  48530. switch (edgeIndex) {
  48531. case 0:
  48532. if (this._checkVerticesInsteadOfIndices) {
  48533. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48534. }
  48535. else {
  48536. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  48537. }
  48538. break;
  48539. case 1:
  48540. if (this._checkVerticesInsteadOfIndices) {
  48541. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48542. }
  48543. else {
  48544. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  48545. }
  48546. break;
  48547. case 2:
  48548. if (this._checkVerticesInsteadOfIndices) {
  48549. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48550. }
  48551. else {
  48552. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  48553. }
  48554. break;
  48555. }
  48556. if (otherEdgeIndex === -1) {
  48557. continue;
  48558. }
  48559. faceAdjacencies.edges[edgeIndex] = otherIndex;
  48560. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  48561. faceAdjacencies.edgesConnectedCount++;
  48562. otherFaceAdjacencies.edgesConnectedCount++;
  48563. if (faceAdjacencies.edgesConnectedCount === 3) {
  48564. break;
  48565. }
  48566. }
  48567. }
  48568. }
  48569. // Create lines
  48570. for (index = 0; index < adjacencies.length; index++) {
  48571. // 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
  48572. var current = adjacencies[index];
  48573. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  48574. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  48575. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  48576. }
  48577. // Merge into a single mesh
  48578. var engine = this._source.getScene().getEngine();
  48579. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  48580. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  48581. this._ib = engine.createIndexBuffer(this._linesIndices);
  48582. this._indicesCount = this._linesIndices.length;
  48583. };
  48584. EdgesRenderer.prototype.render = function () {
  48585. if (!this._lineShader.isReady()) {
  48586. return;
  48587. }
  48588. var scene = this._source.getScene();
  48589. var engine = scene.getEngine();
  48590. this._lineShader._preBind();
  48591. // VBOs
  48592. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  48593. scene.resetCachedMaterial();
  48594. this._lineShader.setColor4("color", this._source.edgesColor);
  48595. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  48596. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  48597. }
  48598. else {
  48599. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  48600. }
  48601. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  48602. this._lineShader.bind(this._source.getWorldMatrix());
  48603. // Draw order
  48604. engine.draw(true, 0, this._indicesCount);
  48605. this._lineShader.unbind();
  48606. engine.setDepthWrite(true);
  48607. };
  48608. return EdgesRenderer;
  48609. }());
  48610. BABYLON.EdgesRenderer = EdgesRenderer;
  48611. })(BABYLON || (BABYLON = {}));
  48612. //# sourceMappingURL=babylon.edgesRenderer.js.map
  48613. var BABYLON;
  48614. (function (BABYLON) {
  48615. (function (TonemappingOperator) {
  48616. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48617. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48618. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48619. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48620. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48621. var TonemappingOperator = BABYLON.TonemappingOperator;
  48622. ;
  48623. var TonemapPostProcess = (function (_super) {
  48624. __extends(TonemapPostProcess, _super);
  48625. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48626. var _this = this;
  48627. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48628. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48629. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  48630. this._operator = _operator;
  48631. this.exposureAdjustment = exposureAdjustment;
  48632. var defines = "#define ";
  48633. if (this._operator === TonemappingOperator.Hable)
  48634. defines += "HABLE_TONEMAPPING";
  48635. else if (this._operator === TonemappingOperator.Reinhard)
  48636. defines += "REINHARD_TONEMAPPING";
  48637. else if (this._operator === TonemappingOperator.HejiDawson)
  48638. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48639. else if (this._operator === TonemappingOperator.Photographic)
  48640. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48641. //sadly a second call to create the effect.
  48642. this.updateEffect(defines);
  48643. this.onApply = function (effect) {
  48644. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48645. };
  48646. }
  48647. return TonemapPostProcess;
  48648. }(BABYLON.PostProcess));
  48649. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48650. })(BABYLON || (BABYLON = {}));
  48651. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48652. var BABYLON;
  48653. (function (BABYLON) {
  48654. var ReflectionProbe = (function () {
  48655. function ReflectionProbe(name, size, scene, generateMipMaps) {
  48656. var _this = this;
  48657. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48658. this.name = name;
  48659. this._viewMatrix = BABYLON.Matrix.Identity();
  48660. this._target = BABYLON.Vector3.Zero();
  48661. this._add = BABYLON.Vector3.Zero();
  48662. this.invertYAxis = false;
  48663. this.position = BABYLON.Vector3.Zero();
  48664. this._scene = scene;
  48665. this._scene.reflectionProbes.push(this);
  48666. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  48667. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  48668. switch (faceIndex) {
  48669. case 0:
  48670. _this._add.copyFromFloats(1, 0, 0);
  48671. break;
  48672. case 1:
  48673. _this._add.copyFromFloats(-1, 0, 0);
  48674. break;
  48675. case 2:
  48676. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  48677. break;
  48678. case 3:
  48679. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  48680. break;
  48681. case 4:
  48682. _this._add.copyFromFloats(0, 0, 1);
  48683. break;
  48684. case 5:
  48685. _this._add.copyFromFloats(0, 0, -1);
  48686. break;
  48687. }
  48688. if (_this._attachedMesh) {
  48689. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  48690. }
  48691. _this.position.addToRef(_this._add, _this._target);
  48692. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  48693. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  48694. });
  48695. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  48696. scene.updateTransformMatrix(true);
  48697. });
  48698. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  48699. }
  48700. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  48701. get: function () {
  48702. return this._renderTargetTexture.refreshRate;
  48703. },
  48704. set: function (value) {
  48705. this._renderTargetTexture.refreshRate = value;
  48706. },
  48707. enumerable: true,
  48708. configurable: true
  48709. });
  48710. ReflectionProbe.prototype.getScene = function () {
  48711. return this._scene;
  48712. };
  48713. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  48714. get: function () {
  48715. return this._renderTargetTexture;
  48716. },
  48717. enumerable: true,
  48718. configurable: true
  48719. });
  48720. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  48721. get: function () {
  48722. return this._renderTargetTexture.renderList;
  48723. },
  48724. enumerable: true,
  48725. configurable: true
  48726. });
  48727. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  48728. this._attachedMesh = mesh;
  48729. };
  48730. ReflectionProbe.prototype.dispose = function () {
  48731. var index = this._scene.reflectionProbes.indexOf(this);
  48732. if (index !== -1) {
  48733. // Remove from the scene if found
  48734. this._scene.reflectionProbes.splice(index, 1);
  48735. }
  48736. if (this._renderTargetTexture) {
  48737. this._renderTargetTexture.dispose();
  48738. this._renderTargetTexture = null;
  48739. }
  48740. };
  48741. return ReflectionProbe;
  48742. }());
  48743. BABYLON.ReflectionProbe = ReflectionProbe;
  48744. })(BABYLON || (BABYLON = {}));
  48745. //# sourceMappingURL=babylon.reflectionProbe.js.map
  48746. var BABYLON;
  48747. (function (BABYLON) {
  48748. var SolidParticle = (function () {
  48749. /**
  48750. * Creates a Solid Particle object.
  48751. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48752. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48753. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48754. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  48755. * `shapeId` (integer) is the model shape identifier in the SPS.
  48756. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48757. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  48758. */
  48759. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48760. this.idx = 0; // particle global index
  48761. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  48762. this.position = BABYLON.Vector3.Zero(); // position
  48763. this.rotation = BABYLON.Vector3.Zero(); // rotation
  48764. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  48765. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  48766. this.velocity = BABYLON.Vector3.Zero(); // velocity
  48767. this.alive = true; // alive
  48768. this.isVisible = true; // visibility
  48769. this._pos = 0; // index of this particle in the global "positions" array
  48770. this.shapeId = 0; // model shape id
  48771. this.idxInShape = 0; // index of the particle in its shape id
  48772. this.idx = particleIndex;
  48773. this._pos = positionIndex;
  48774. this._model = model;
  48775. this.shapeId = shapeId;
  48776. this.idxInShape = idxInShape;
  48777. this._sps = sps;
  48778. if (modelBoundingInfo) {
  48779. this._modelBoundingInfo = modelBoundingInfo;
  48780. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48781. }
  48782. }
  48783. Object.defineProperty(SolidParticle.prototype, "scale", {
  48784. /**
  48785. * legacy support, changed scale to scaling
  48786. */
  48787. get: function () {
  48788. return this.scaling;
  48789. },
  48790. set: function (scale) {
  48791. this.scaling = scale;
  48792. },
  48793. enumerable: true,
  48794. configurable: true
  48795. });
  48796. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48797. /**
  48798. * legacy support, changed quaternion to rotationQuaternion
  48799. */
  48800. get: function () {
  48801. return this.rotationQuaternion;
  48802. },
  48803. set: function (q) {
  48804. this.rotationQuaternion = q;
  48805. },
  48806. enumerable: true,
  48807. configurable: true
  48808. });
  48809. /**
  48810. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48811. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48812. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  48813. */
  48814. SolidParticle.prototype.intersectsMesh = function (target) {
  48815. if (!this._boundingInfo || !target._boundingInfo) {
  48816. return false;
  48817. }
  48818. if (this._sps._bSphereOnly) {
  48819. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48820. }
  48821. return this._boundingInfo.intersects(target._boundingInfo, false);
  48822. };
  48823. return SolidParticle;
  48824. }());
  48825. BABYLON.SolidParticle = SolidParticle;
  48826. var ModelShape = (function () {
  48827. /**
  48828. * 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.
  48829. * SPS internal tool, don't use it manually.
  48830. */
  48831. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  48832. this.shapeID = id;
  48833. this._shape = shape;
  48834. this._shapeUV = shapeUV;
  48835. this._positionFunction = posFunction;
  48836. this._vertexFunction = vtxFunction;
  48837. }
  48838. return ModelShape;
  48839. }());
  48840. BABYLON.ModelShape = ModelShape;
  48841. })(BABYLON || (BABYLON = {}));
  48842. //# sourceMappingURL=babylon.solidParticle.js.map
  48843. var BABYLON;
  48844. (function (BABYLON) {
  48845. /**
  48846. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  48847. */
  48848. var SolidParticleSystem = (function () {
  48849. /**
  48850. * Creates a SPS (Solid Particle System) object.
  48851. * `name` (String) is the SPS name, this will be the underlying mesh name.
  48852. * `scene` (Scene) is the scene in which the SPS is added.
  48853. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  48854. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  48855. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  48856. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  48857. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  48858. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  48859. */
  48860. function SolidParticleSystem(name, scene, options) {
  48861. // public members
  48862. /**
  48863. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  48864. * Example : var p = SPS.particles[i];
  48865. */
  48866. this.particles = new Array();
  48867. /**
  48868. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  48869. */
  48870. this.nbParticles = 0;
  48871. /**
  48872. * If the particles must ever face the camera (default false). Useful for planar particles.
  48873. */
  48874. this.billboard = false;
  48875. /**
  48876. * Recompute normals when adding a shape
  48877. */
  48878. this.recomputeNormals = true;
  48879. /**
  48880. * This a counter ofr your own usage. It's not set by any SPS functions.
  48881. */
  48882. this.counter = 0;
  48883. /**
  48884. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  48885. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  48886. */
  48887. this.vars = {};
  48888. this._positions = new Array();
  48889. this._indices = new Array();
  48890. this._normals = new Array();
  48891. this._colors = new Array();
  48892. this._uvs = new Array();
  48893. this._index = 0; // indices index
  48894. this._updatable = true;
  48895. this._pickable = false;
  48896. this._isVisibilityBoxLocked = false;
  48897. this._alwaysVisible = false;
  48898. this._shapeCounter = 0;
  48899. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  48900. this._color = new BABYLON.Color4(0, 0, 0, 0);
  48901. this._computeParticleColor = true;
  48902. this._computeParticleTexture = true;
  48903. this._computeParticleRotation = true;
  48904. this._computeParticleVertex = false;
  48905. this._computeBoundingBox = false;
  48906. this._cam_axisZ = BABYLON.Vector3.Zero();
  48907. this._cam_axisY = BABYLON.Vector3.Zero();
  48908. this._cam_axisX = BABYLON.Vector3.Zero();
  48909. this._axisX = BABYLON.Axis.X;
  48910. this._axisY = BABYLON.Axis.Y;
  48911. this._axisZ = BABYLON.Axis.Z;
  48912. this._camDir = BABYLON.Vector3.Zero();
  48913. this._rotMatrix = new BABYLON.Matrix();
  48914. this._invertMatrix = new BABYLON.Matrix();
  48915. this._rotated = BABYLON.Vector3.Zero();
  48916. this._quaternion = new BABYLON.Quaternion();
  48917. this._vertex = BABYLON.Vector3.Zero();
  48918. this._normal = BABYLON.Vector3.Zero();
  48919. this._yaw = 0.0;
  48920. this._pitch = 0.0;
  48921. this._roll = 0.0;
  48922. this._halfroll = 0.0;
  48923. this._halfpitch = 0.0;
  48924. this._halfyaw = 0.0;
  48925. this._sinRoll = 0.0;
  48926. this._cosRoll = 0.0;
  48927. this._sinPitch = 0.0;
  48928. this._cosPitch = 0.0;
  48929. this._sinYaw = 0.0;
  48930. this._cosYaw = 0.0;
  48931. this._w = 0.0;
  48932. this._minimum = BABYLON.Tmp.Vector3[0];
  48933. this._maximum = BABYLON.Tmp.Vector3[1];
  48934. this._scale = BABYLON.Tmp.Vector3[2];
  48935. this._translation = BABYLON.Tmp.Vector3[3];
  48936. this._minBbox = BABYLON.Tmp.Vector3[4];
  48937. this._maxBbox = BABYLON.Tmp.Vector3[5];
  48938. this._particlesIntersect = false;
  48939. this._bSphereOnly = false;
  48940. this._bSphereRadiusFactor = 1.0;
  48941. this.name = name;
  48942. this._scene = scene;
  48943. this._camera = scene.activeCamera;
  48944. this._pickable = options ? options.isPickable : false;
  48945. this._particlesIntersect = options ? options.particleIntersection : false;
  48946. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  48947. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  48948. if (options && options.updatable) {
  48949. this._updatable = options.updatable;
  48950. }
  48951. else {
  48952. this._updatable = true;
  48953. }
  48954. if (this._pickable) {
  48955. this.pickedParticles = [];
  48956. }
  48957. }
  48958. /**
  48959. * Builds the SPS underlying mesh. Returns a standard Mesh.
  48960. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  48961. */
  48962. SolidParticleSystem.prototype.buildMesh = function () {
  48963. if (this.nbParticles === 0) {
  48964. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  48965. this.addShape(triangle, 1);
  48966. triangle.dispose();
  48967. }
  48968. this._positions32 = new Float32Array(this._positions);
  48969. this._uvs32 = new Float32Array(this._uvs);
  48970. this._colors32 = new Float32Array(this._colors);
  48971. if (this.recomputeNormals) {
  48972. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  48973. }
  48974. this._normals32 = new Float32Array(this._normals);
  48975. this._fixedNormal32 = new Float32Array(this._normals);
  48976. var vertexData = new BABYLON.VertexData();
  48977. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  48978. vertexData.indices = this._indices;
  48979. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  48980. if (this._uvs32) {
  48981. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  48982. ;
  48983. }
  48984. if (this._colors32) {
  48985. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  48986. }
  48987. var mesh = new BABYLON.Mesh(this.name, this._scene);
  48988. vertexData.applyToMesh(mesh, this._updatable);
  48989. this.mesh = mesh;
  48990. this.mesh.isPickable = this._pickable;
  48991. // free memory
  48992. this._positions = null;
  48993. this._normals = null;
  48994. this._uvs = null;
  48995. this._colors = null;
  48996. if (!this._updatable) {
  48997. this.particles.length = 0;
  48998. }
  48999. return mesh;
  49000. };
  49001. /**
  49002. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49003. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49004. * Thus the particles generated from `digest()` have their property `position` set yet.
  49005. * `mesh` ( Mesh ) is the mesh to be digested
  49006. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49007. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49008. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49009. */
  49010. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49011. var size = (options && options.facetNb) || 1;
  49012. var number = (options && options.number);
  49013. var delta = (options && options.delta) || 0;
  49014. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49015. var meshInd = mesh.getIndices();
  49016. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49017. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49018. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49019. var f = 0; // facet counter
  49020. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49021. // compute size from number
  49022. if (number) {
  49023. number = (number > totalFacets) ? totalFacets : number;
  49024. size = Math.round(totalFacets / number);
  49025. delta = 0;
  49026. }
  49027. else {
  49028. size = (size > totalFacets) ? totalFacets : size;
  49029. }
  49030. var facetPos = []; // submesh positions
  49031. var facetInd = []; // submesh indices
  49032. var facetUV = []; // submesh UV
  49033. var facetCol = []; // submesh colors
  49034. var barycenter = BABYLON.Tmp.Vector3[0];
  49035. var rand;
  49036. var sizeO = size;
  49037. while (f < totalFacets) {
  49038. size = sizeO + Math.floor((1 + delta) * Math.random());
  49039. if (f > totalFacets - size) {
  49040. size = totalFacets - f;
  49041. }
  49042. // reset temp arrays
  49043. facetPos.length = 0;
  49044. facetInd.length = 0;
  49045. facetUV.length = 0;
  49046. facetCol.length = 0;
  49047. // iterate over "size" facets
  49048. var fi = 0;
  49049. for (var j = f * 3; j < (f + size) * 3; j++) {
  49050. facetInd.push(fi);
  49051. var i = meshInd[j];
  49052. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49053. if (meshUV) {
  49054. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49055. }
  49056. if (meshCol) {
  49057. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49058. }
  49059. fi++;
  49060. }
  49061. // create a model shape for each single particle
  49062. var idx = this.nbParticles;
  49063. var shape = this._posToShape(facetPos);
  49064. var shapeUV = this._uvsToShapeUV(facetUV);
  49065. // compute the barycenter of the shape
  49066. var v;
  49067. for (v = 0; v < shape.length; v++) {
  49068. barycenter.addInPlace(shape[v]);
  49069. }
  49070. barycenter.scaleInPlace(1 / shape.length);
  49071. // shift the shape from its barycenter to the origin
  49072. for (v = 0; v < shape.length; v++) {
  49073. shape[v].subtractInPlace(barycenter);
  49074. }
  49075. var bInfo;
  49076. if (this._particlesIntersect) {
  49077. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49078. }
  49079. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49080. // add the particle in the SPS
  49081. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49082. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49083. // initialize the particle position
  49084. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49085. this._index += shape.length;
  49086. idx++;
  49087. this.nbParticles++;
  49088. this._shapeCounter++;
  49089. f += size;
  49090. }
  49091. return this;
  49092. };
  49093. //reset copy
  49094. SolidParticleSystem.prototype._resetCopy = function () {
  49095. this._copy.position.x = 0;
  49096. this._copy.position.y = 0;
  49097. this._copy.position.z = 0;
  49098. this._copy.rotation.x = 0;
  49099. this._copy.rotation.y = 0;
  49100. this._copy.rotation.z = 0;
  49101. this._copy.rotationQuaternion = null;
  49102. this._copy.scaling.x = 1;
  49103. this._copy.scaling.y = 1;
  49104. this._copy.scaling.z = 1;
  49105. this._copy.uvs.x = 0;
  49106. this._copy.uvs.y = 0;
  49107. this._copy.uvs.z = 1;
  49108. this._copy.uvs.w = 1;
  49109. this._copy.color = null;
  49110. };
  49111. // _meshBuilder : inserts the shape model in the global SPS mesh
  49112. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49113. var i;
  49114. var u = 0;
  49115. var c = 0;
  49116. var n = 0;
  49117. this._resetCopy();
  49118. if (options && options.positionFunction) {
  49119. options.positionFunction(this._copy, idx, idxInShape);
  49120. }
  49121. if (this._copy.rotationQuaternion) {
  49122. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49123. }
  49124. else {
  49125. this._yaw = this._copy.rotation.y;
  49126. this._pitch = this._copy.rotation.x;
  49127. this._roll = this._copy.rotation.z;
  49128. this._quaternionRotationYPR();
  49129. }
  49130. this._quaternionToRotationMatrix();
  49131. for (i = 0; i < shape.length; i++) {
  49132. this._vertex.x = shape[i].x;
  49133. this._vertex.y = shape[i].y;
  49134. this._vertex.z = shape[i].z;
  49135. if (options && options.vertexFunction) {
  49136. options.vertexFunction(this._copy, this._vertex, i);
  49137. }
  49138. this._vertex.x *= this._copy.scaling.x;
  49139. this._vertex.y *= this._copy.scaling.y;
  49140. this._vertex.z *= this._copy.scaling.z;
  49141. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49142. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49143. if (meshUV) {
  49144. 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);
  49145. u += 2;
  49146. }
  49147. if (this._copy.color) {
  49148. this._color = this._copy.color;
  49149. }
  49150. else if (meshCol && meshCol[c] !== undefined) {
  49151. this._color.r = meshCol[c];
  49152. this._color.g = meshCol[c + 1];
  49153. this._color.b = meshCol[c + 2];
  49154. this._color.a = meshCol[c + 3];
  49155. }
  49156. else {
  49157. this._color.r = 1;
  49158. this._color.g = 1;
  49159. this._color.b = 1;
  49160. this._color.a = 1;
  49161. }
  49162. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49163. c += 4;
  49164. if (!this.recomputeNormals && meshNor) {
  49165. this._normal.x = meshNor[n];
  49166. this._normal.y = meshNor[n + 1];
  49167. this._normal.z = meshNor[n + 2];
  49168. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  49169. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49170. n += 3;
  49171. }
  49172. }
  49173. for (i = 0; i < meshInd.length; i++) {
  49174. indices.push(p + meshInd[i]);
  49175. }
  49176. if (this._pickable) {
  49177. var nbfaces = meshInd.length / 3;
  49178. for (i = 0; i < nbfaces; i++) {
  49179. this.pickedParticles.push({ idx: idx, faceId: i });
  49180. }
  49181. }
  49182. };
  49183. // returns a shape array from positions array
  49184. SolidParticleSystem.prototype._posToShape = function (positions) {
  49185. var shape = [];
  49186. for (var i = 0; i < positions.length; i += 3) {
  49187. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49188. }
  49189. return shape;
  49190. };
  49191. // returns a shapeUV array from a Vector4 uvs
  49192. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49193. var shapeUV = [];
  49194. if (uvs) {
  49195. for (var i = 0; i < uvs.length; i++)
  49196. shapeUV.push(uvs[i]);
  49197. }
  49198. return shapeUV;
  49199. };
  49200. // adds a new particle object in the particles array
  49201. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  49202. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  49203. };
  49204. /**
  49205. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49206. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49207. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  49208. * `nb` (positive integer) the number of particles to be created from this model
  49209. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  49210. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  49211. */
  49212. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49213. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49214. var meshInd = mesh.getIndices();
  49215. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49216. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49217. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49218. var bbInfo;
  49219. if (this._particlesIntersect) {
  49220. bbInfo = mesh.getBoundingInfo();
  49221. }
  49222. var shape = this._posToShape(meshPos);
  49223. var shapeUV = this._uvsToShapeUV(meshUV);
  49224. var posfunc = options ? options.positionFunction : null;
  49225. var vtxfunc = options ? options.vertexFunction : null;
  49226. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  49227. // particles
  49228. var idx = this.nbParticles;
  49229. for (var i = 0; i < nb; i++) {
  49230. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49231. if (this._updatable) {
  49232. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  49233. }
  49234. this._index += shape.length;
  49235. idx++;
  49236. }
  49237. this.nbParticles += nb;
  49238. this._shapeCounter++;
  49239. return this._shapeCounter - 1;
  49240. };
  49241. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49242. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49243. this._resetCopy();
  49244. if (particle._model._positionFunction) {
  49245. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49246. }
  49247. if (this._copy.rotationQuaternion) {
  49248. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49249. }
  49250. else {
  49251. this._yaw = this._copy.rotation.y;
  49252. this._pitch = this._copy.rotation.x;
  49253. this._roll = this._copy.rotation.z;
  49254. this._quaternionRotationYPR();
  49255. }
  49256. this._quaternionToRotationMatrix();
  49257. this._shape = particle._model._shape;
  49258. for (var pt = 0; pt < this._shape.length; pt++) {
  49259. this._vertex.x = this._shape[pt].x;
  49260. this._vertex.y = this._shape[pt].y;
  49261. this._vertex.z = this._shape[pt].z;
  49262. if (particle._model._vertexFunction) {
  49263. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49264. }
  49265. this._vertex.x *= this._copy.scaling.x;
  49266. this._vertex.y *= this._copy.scaling.y;
  49267. this._vertex.z *= this._copy.scaling.z;
  49268. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49269. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49270. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49271. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49272. }
  49273. particle.position.x = 0.0;
  49274. particle.position.y = 0.0;
  49275. particle.position.z = 0.0;
  49276. particle.rotation.x = 0.0;
  49277. particle.rotation.y = 0.0;
  49278. particle.rotation.z = 0.0;
  49279. particle.rotationQuaternion = null;
  49280. particle.scaling.x = 1.0;
  49281. particle.scaling.y = 1.0;
  49282. particle.scaling.z = 1.0;
  49283. };
  49284. /**
  49285. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49286. */
  49287. SolidParticleSystem.prototype.rebuildMesh = function () {
  49288. for (var p = 0; p < this.particles.length; p++) {
  49289. this._rebuildParticle(this.particles[p]);
  49290. }
  49291. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49292. };
  49293. /**
  49294. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49295. * This method calls `updateParticle()` for each particle of the SPS.
  49296. * For an animated SPS, it is usually called within the render loop.
  49297. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49298. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49299. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49300. */
  49301. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49302. if (start === void 0) { start = 0; }
  49303. if (end === void 0) { end = this.nbParticles - 1; }
  49304. if (update === void 0) { update = true; }
  49305. if (!this._updatable) {
  49306. return;
  49307. }
  49308. // custom beforeUpdate
  49309. this.beforeUpdateParticles(start, end, update);
  49310. this._cam_axisX.x = 1.0;
  49311. this._cam_axisX.y = 0.0;
  49312. this._cam_axisX.z = 0.0;
  49313. this._cam_axisY.x = 0.0;
  49314. this._cam_axisY.y = 1.0;
  49315. this._cam_axisY.z = 0.0;
  49316. this._cam_axisZ.x = 0.0;
  49317. this._cam_axisZ.y = 0.0;
  49318. this._cam_axisZ.z = 1.0;
  49319. // if the particles will always face the camera
  49320. if (this.billboard) {
  49321. // compute the camera position and un-rotate it by the current mesh rotation
  49322. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  49323. this._quaternionToRotationMatrix();
  49324. this._rotMatrix.invertToRef(this._invertMatrix);
  49325. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  49326. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49327. this._cam_axisZ.normalize();
  49328. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  49329. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  49330. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49331. this._cam_axisY.normalize();
  49332. this._cam_axisX.normalize();
  49333. }
  49334. }
  49335. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49336. var idx = 0;
  49337. var index = 0;
  49338. var colidx = 0;
  49339. var colorIndex = 0;
  49340. var uvidx = 0;
  49341. var uvIndex = 0;
  49342. var pt = 0;
  49343. if (this._computeBoundingBox) {
  49344. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49345. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49346. }
  49347. // particle loop
  49348. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  49349. for (var p = start; p <= end; p++) {
  49350. this._particle = this.particles[p];
  49351. this._shape = this._particle._model._shape;
  49352. this._shapeUV = this._particle._model._shapeUV;
  49353. // call to custom user function to update the particle properties
  49354. this.updateParticle(this._particle);
  49355. if (this._particle.isVisible) {
  49356. // particle rotation matrix
  49357. if (this.billboard) {
  49358. this._particle.rotation.x = 0.0;
  49359. this._particle.rotation.y = 0.0;
  49360. }
  49361. if (this._computeParticleRotation || this.billboard) {
  49362. if (this._particle.rotationQuaternion) {
  49363. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49364. }
  49365. else {
  49366. this._yaw = this._particle.rotation.y;
  49367. this._pitch = this._particle.rotation.x;
  49368. this._roll = this._particle.rotation.z;
  49369. this._quaternionRotationYPR();
  49370. }
  49371. this._quaternionToRotationMatrix();
  49372. }
  49373. // particle vertex loop
  49374. for (pt = 0; pt < this._shape.length; pt++) {
  49375. idx = index + pt * 3;
  49376. colidx = colorIndex + pt * 4;
  49377. uvidx = uvIndex + pt * 2;
  49378. this._vertex.x = this._shape[pt].x;
  49379. this._vertex.y = this._shape[pt].y;
  49380. this._vertex.z = this._shape[pt].z;
  49381. if (this._computeParticleVertex) {
  49382. this.updateParticleVertex(this._particle, this._vertex, pt);
  49383. }
  49384. // positions
  49385. this._vertex.x *= this._particle.scaling.x;
  49386. this._vertex.y *= this._particle.scaling.y;
  49387. this._vertex.z *= this._particle.scaling.z;
  49388. 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];
  49389. 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;
  49390. 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;
  49391. 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;
  49392. 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;
  49393. 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;
  49394. 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;
  49395. if (this._computeBoundingBox) {
  49396. if (this._positions32[idx] < this._minimum.x) {
  49397. this._minimum.x = this._positions32[idx];
  49398. }
  49399. if (this._positions32[idx] > this._maximum.x) {
  49400. this._maximum.x = this._positions32[idx];
  49401. }
  49402. if (this._positions32[idx + 1] < this._minimum.y) {
  49403. this._minimum.y = this._positions32[idx + 1];
  49404. }
  49405. if (this._positions32[idx + 1] > this._maximum.y) {
  49406. this._maximum.y = this._positions32[idx + 1];
  49407. }
  49408. if (this._positions32[idx + 2] < this._minimum.z) {
  49409. this._minimum.z = this._positions32[idx + 2];
  49410. }
  49411. if (this._positions32[idx + 2] > this._maximum.z) {
  49412. this._maximum.z = this._positions32[idx + 2];
  49413. }
  49414. }
  49415. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  49416. if (!this._computeParticleVertex) {
  49417. this._normal.x = this._fixedNormal32[idx];
  49418. this._normal.y = this._fixedNormal32[idx + 1];
  49419. this._normal.z = this._fixedNormal32[idx + 2];
  49420. 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];
  49421. 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;
  49422. 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;
  49423. 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;
  49424. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49425. 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;
  49426. 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;
  49427. }
  49428. if (this._computeParticleColor) {
  49429. this._colors32[colidx] = this._particle.color.r;
  49430. this._colors32[colidx + 1] = this._particle.color.g;
  49431. this._colors32[colidx + 2] = this._particle.color.b;
  49432. this._colors32[colidx + 3] = this._particle.color.a;
  49433. }
  49434. if (this._computeParticleTexture) {
  49435. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49436. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49437. }
  49438. }
  49439. }
  49440. else {
  49441. for (pt = 0; pt < this._shape.length; pt++) {
  49442. idx = index + pt * 3;
  49443. colidx = colorIndex + pt * 4;
  49444. uvidx = uvIndex + pt * 2;
  49445. this._positions32[idx] = this._camera.position.x;
  49446. this._positions32[idx + 1] = this._camera.position.y;
  49447. this._positions32[idx + 2] = this._camera.position.z;
  49448. this._normals32[idx] = 0.0;
  49449. this._normals32[idx + 1] = 0.0;
  49450. this._normals32[idx + 2] = 0.0;
  49451. if (this._computeParticleColor) {
  49452. this._colors32[colidx] = this._particle.color.r;
  49453. this._colors32[colidx + 1] = this._particle.color.g;
  49454. this._colors32[colidx + 2] = this._particle.color.b;
  49455. this._colors32[colidx + 3] = this._particle.color.a;
  49456. }
  49457. if (this._computeParticleTexture) {
  49458. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49459. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49460. }
  49461. }
  49462. }
  49463. // if the particle intersections must be computed : update the bbInfo
  49464. if (this._particlesIntersect) {
  49465. var bInfo = this._particle._boundingInfo;
  49466. var bBox = bInfo.boundingBox;
  49467. var bSphere = bInfo.boundingSphere;
  49468. if (!this._bSphereOnly) {
  49469. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49470. for (var b = 0; b < bBox.vectors.length; b++) {
  49471. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49472. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49473. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49474. 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];
  49475. 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;
  49476. 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;
  49477. 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;
  49478. 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;
  49479. 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;
  49480. 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;
  49481. }
  49482. bBox._update(this.mesh._worldMatrix);
  49483. }
  49484. // place and scale the particle bouding sphere in the SPS local system, then update it
  49485. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49486. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49487. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49488. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49489. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49490. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49491. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49492. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49493. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49494. 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));
  49495. bSphere._update(this.mesh._worldMatrix);
  49496. }
  49497. // increment indexes for the next particle
  49498. index = idx + 3;
  49499. colorIndex = colidx + 4;
  49500. uvIndex = uvidx + 2;
  49501. }
  49502. // if the VBO must be updated
  49503. if (update) {
  49504. if (this._computeParticleColor) {
  49505. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49506. }
  49507. if (this._computeParticleTexture) {
  49508. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49509. }
  49510. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49511. if (!this.mesh.areNormalsFrozen) {
  49512. if (this._computeParticleVertex) {
  49513. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49514. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  49515. for (var i = 0; i < this._normals32.length; i++) {
  49516. this._fixedNormal32[i] = this._normals32[i];
  49517. }
  49518. }
  49519. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49520. }
  49521. }
  49522. if (this._computeBoundingBox) {
  49523. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49524. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49525. }
  49526. this.afterUpdateParticles(start, end, update);
  49527. };
  49528. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49529. this._halfroll = this._roll * 0.5;
  49530. this._halfpitch = this._pitch * 0.5;
  49531. this._halfyaw = this._yaw * 0.5;
  49532. this._sinRoll = Math.sin(this._halfroll);
  49533. this._cosRoll = Math.cos(this._halfroll);
  49534. this._sinPitch = Math.sin(this._halfpitch);
  49535. this._cosPitch = Math.cos(this._halfpitch);
  49536. this._sinYaw = Math.sin(this._halfyaw);
  49537. this._cosYaw = Math.cos(this._halfyaw);
  49538. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  49539. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  49540. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  49541. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  49542. };
  49543. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49544. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49545. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49546. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49547. this._rotMatrix.m[3] = 0;
  49548. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49549. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49550. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49551. this._rotMatrix.m[7] = 0;
  49552. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49553. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49554. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49555. this._rotMatrix.m[11] = 0;
  49556. this._rotMatrix.m[12] = 0;
  49557. this._rotMatrix.m[13] = 0;
  49558. this._rotMatrix.m[14] = 0;
  49559. this._rotMatrix.m[15] = 1.0;
  49560. };
  49561. /**
  49562. * Disposes the SPS
  49563. */
  49564. SolidParticleSystem.prototype.dispose = function () {
  49565. this.mesh.dispose();
  49566. this.vars = null;
  49567. // drop references to internal big arrays for the GC
  49568. this._positions = null;
  49569. this._indices = null;
  49570. this._normals = null;
  49571. this._uvs = null;
  49572. this._colors = null;
  49573. this._positions32 = null;
  49574. this._normals32 = null;
  49575. this._fixedNormal32 = null;
  49576. this._uvs32 = null;
  49577. this._colors32 = null;
  49578. this.pickedParticles = null;
  49579. };
  49580. /**
  49581. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49582. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49583. */
  49584. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49585. if (!this._isVisibilityBoxLocked) {
  49586. this.mesh.refreshBoundingInfo();
  49587. }
  49588. };
  49589. /**
  49590. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49591. * @param size the size (float) of the visibility box
  49592. * note : this doesn't lock the SPS mesh bounding box.
  49593. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49594. */
  49595. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49596. var vis = size / 2;
  49597. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49598. };
  49599. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49600. // getter and setter
  49601. get: function () {
  49602. return this._alwaysVisible;
  49603. },
  49604. /**
  49605. * Sets the SPS as always visible or not
  49606. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49607. */
  49608. set: function (val) {
  49609. this._alwaysVisible = val;
  49610. this.mesh.alwaysSelectAsActiveMesh = val;
  49611. },
  49612. enumerable: true,
  49613. configurable: true
  49614. });
  49615. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49616. get: function () {
  49617. return this._isVisibilityBoxLocked;
  49618. },
  49619. /**
  49620. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49621. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49622. */
  49623. set: function (val) {
  49624. this._isVisibilityBoxLocked = val;
  49625. this.mesh.getBoundingInfo().isLocked = val;
  49626. },
  49627. enumerable: true,
  49628. configurable: true
  49629. });
  49630. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49631. // getters
  49632. get: function () {
  49633. return this._computeParticleRotation;
  49634. },
  49635. // Optimizer setters
  49636. /**
  49637. * Tells to `setParticles()` to compute the particle rotations or not.
  49638. * Default value : true. The SPS is faster when it's set to false.
  49639. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49640. */
  49641. set: function (val) {
  49642. this._computeParticleRotation = val;
  49643. },
  49644. enumerable: true,
  49645. configurable: true
  49646. });
  49647. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49648. get: function () {
  49649. return this._computeParticleColor;
  49650. },
  49651. /**
  49652. * Tells to `setParticles()` to compute the particle colors or not.
  49653. * Default value : true. The SPS is faster when it's set to false.
  49654. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49655. */
  49656. set: function (val) {
  49657. this._computeParticleColor = val;
  49658. },
  49659. enumerable: true,
  49660. configurable: true
  49661. });
  49662. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49663. get: function () {
  49664. return this._computeParticleTexture;
  49665. },
  49666. /**
  49667. * Tells to `setParticles()` to compute the particle textures or not.
  49668. * Default value : true. The SPS is faster when it's set to false.
  49669. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49670. */
  49671. set: function (val) {
  49672. this._computeParticleTexture = val;
  49673. },
  49674. enumerable: true,
  49675. configurable: true
  49676. });
  49677. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49678. get: function () {
  49679. return this._computeParticleVertex;
  49680. },
  49681. /**
  49682. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49683. * Default value : false. The SPS is faster when it's set to false.
  49684. * Note : the particle custom vertex positions aren't stored values.
  49685. */
  49686. set: function (val) {
  49687. this._computeParticleVertex = val;
  49688. },
  49689. enumerable: true,
  49690. configurable: true
  49691. });
  49692. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49693. get: function () {
  49694. return this._computeBoundingBox;
  49695. },
  49696. /**
  49697. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49698. */
  49699. set: function (val) {
  49700. this._computeBoundingBox = val;
  49701. },
  49702. enumerable: true,
  49703. configurable: true
  49704. });
  49705. // =======================================================================
  49706. // Particle behavior logic
  49707. // these following methods may be overwritten by the user to fit his needs
  49708. /**
  49709. * This function does nothing. It may be overwritten to set all the particle first values.
  49710. * The SPS doesn't call this function, you may have to call it by your own.
  49711. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49712. */
  49713. SolidParticleSystem.prototype.initParticles = function () {
  49714. };
  49715. /**
  49716. * This function does nothing. It may be overwritten to recycle a particle.
  49717. * The SPS doesn't call this function, you may have to call it by your own.
  49718. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49719. */
  49720. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49721. return particle;
  49722. };
  49723. /**
  49724. * Updates a particle : this function should be overwritten by the user.
  49725. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49726. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49727. * ex : just set a particle position or velocity and recycle conditions
  49728. */
  49729. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49730. return particle;
  49731. };
  49732. /**
  49733. * Updates a vertex of a particle : it can be overwritten by the user.
  49734. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49735. * @param particle the current particle
  49736. * @param vertex the current index of the current particle
  49737. * @param pt the index of the current vertex in the particle shape
  49738. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49739. * ex : just set a vertex particle position
  49740. */
  49741. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49742. return vertex;
  49743. };
  49744. /**
  49745. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49746. * This does nothing and may be overwritten by the user.
  49747. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49748. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49749. * @param update the boolean update value actually passed to setParticles()
  49750. */
  49751. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49752. };
  49753. /**
  49754. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49755. * This will be passed three parameters.
  49756. * This does nothing and may be overwritten by the user.
  49757. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49758. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49759. * @param update the boolean update value actually passed to setParticles()
  49760. */
  49761. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49762. };
  49763. return SolidParticleSystem;
  49764. }());
  49765. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49766. })(BABYLON || (BABYLON = {}));
  49767. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  49768. var BABYLON;
  49769. (function (BABYLON) {
  49770. var Internals;
  49771. (function (Internals) {
  49772. var FileFaceOrientation = (function () {
  49773. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  49774. this.name = name;
  49775. this.worldAxisForNormal = worldAxisForNormal;
  49776. this.worldAxisForFileX = worldAxisForFileX;
  49777. this.worldAxisForFileY = worldAxisForFileY;
  49778. }
  49779. return FileFaceOrientation;
  49780. }());
  49781. ;
  49782. /**
  49783. * Helper class dealing with the extraction of spherical polynomial dataArray
  49784. * from a cube map.
  49785. */
  49786. var CubeMapToSphericalPolynomialTools = (function () {
  49787. function CubeMapToSphericalPolynomialTools() {
  49788. }
  49789. /**
  49790. * Converts a cubemap to the according Spherical Polynomial data.
  49791. * This extracts the first 3 orders only as they are the only one used in the lighting.
  49792. *
  49793. * @param cubeInfo The Cube map to extract the information from.
  49794. * @return The Spherical Polynomial data.
  49795. */
  49796. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  49797. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  49798. var totalSolidAngle = 0.0;
  49799. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  49800. var du = 2.0 / cubeInfo.size;
  49801. var dv = du;
  49802. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  49803. var minUV = du * 0.5 - 1.0;
  49804. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49805. var fileFace = this.FileFaces[faceIndex];
  49806. var dataArray = cubeInfo[fileFace.name];
  49807. var v = minUV;
  49808. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  49809. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  49810. // Because SP is still linear, so summation is fine in that basis.
  49811. for (var y = 0; y < cubeInfo.size; y++) {
  49812. var u = minUV;
  49813. for (var x = 0; x < cubeInfo.size; x++) {
  49814. // World direction (not normalised)
  49815. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  49816. worldDirection.normalize();
  49817. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  49818. if (1) {
  49819. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  49820. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  49821. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  49822. var color = new BABYLON.Color3(r, g, b);
  49823. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49824. }
  49825. else {
  49826. if (faceIndex == 0) {
  49827. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49828. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49829. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49830. }
  49831. else if (faceIndex == 1) {
  49832. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49833. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49834. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49835. }
  49836. else if (faceIndex == 2) {
  49837. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49838. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49839. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49840. }
  49841. else if (faceIndex == 3) {
  49842. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49843. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49844. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49845. }
  49846. else if (faceIndex == 4) {
  49847. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49848. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49849. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49850. }
  49851. else if (faceIndex == 5) {
  49852. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49853. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49854. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49855. }
  49856. 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]);
  49857. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49858. }
  49859. totalSolidAngle += deltaSolidAngle;
  49860. u += du;
  49861. }
  49862. v += dv;
  49863. }
  49864. }
  49865. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  49866. var correction = correctSolidAngle / totalSolidAngle;
  49867. sphericalHarmonics.scale(correction);
  49868. // Additionally scale by pi -- audit needed
  49869. sphericalHarmonics.scale(1.0 / Math.PI);
  49870. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  49871. };
  49872. CubeMapToSphericalPolynomialTools.FileFaces = [
  49873. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  49874. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  49875. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  49876. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  49877. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  49878. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  49879. ];
  49880. return CubeMapToSphericalPolynomialTools;
  49881. }());
  49882. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  49883. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49884. })(BABYLON || (BABYLON = {}));
  49885. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  49886. var BABYLON;
  49887. (function (BABYLON) {
  49888. var Internals;
  49889. (function (Internals) {
  49890. /**
  49891. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  49892. */
  49893. var PanoramaToCubeMapTools = (function () {
  49894. function PanoramaToCubeMapTools() {
  49895. }
  49896. /**
  49897. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  49898. *
  49899. * @param float32Array The source data.
  49900. * @param inputWidth The width of the input panorama.
  49901. * @param inputhHeight The height of the input panorama.
  49902. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  49903. * @return The cubemap data
  49904. */
  49905. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  49906. if (!float32Array) {
  49907. throw "ConvertPanoramaToCubemap: input cannot be null";
  49908. }
  49909. if (float32Array.length != inputWidth * inputHeight * 3) {
  49910. throw "ConvertPanoramaToCubemap: input size is wrong";
  49911. }
  49912. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  49913. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  49914. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  49915. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  49916. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  49917. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  49918. return {
  49919. front: textureFront,
  49920. back: textureBack,
  49921. left: textureLeft,
  49922. right: textureRight,
  49923. up: textureUp,
  49924. down: textureDown,
  49925. size: size
  49926. };
  49927. };
  49928. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  49929. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  49930. var textureArray = new Float32Array(buffer);
  49931. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  49932. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  49933. var dy = 1 / texSize;
  49934. var fy = 0;
  49935. for (var y = 0; y < texSize; y++) {
  49936. var xv1 = faceData[0];
  49937. var xv2 = faceData[2];
  49938. for (var x = 0; x < texSize; x++) {
  49939. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  49940. v.normalize();
  49941. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  49942. // 3 channels per pixels
  49943. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  49944. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  49945. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  49946. xv1 = xv1.add(rotDX1);
  49947. xv2 = xv2.add(rotDX2);
  49948. }
  49949. fy += dy;
  49950. }
  49951. return textureArray;
  49952. };
  49953. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  49954. var theta = Math.atan2(vDir.z, vDir.x);
  49955. var phi = Math.acos(vDir.y);
  49956. while (theta < -Math.PI)
  49957. theta += 2 * Math.PI;
  49958. while (theta > Math.PI)
  49959. theta -= 2 * Math.PI;
  49960. var dx = theta / Math.PI;
  49961. var dy = phi / Math.PI;
  49962. // recenter.
  49963. dx = dx * 0.5 + 0.5;
  49964. var px = Math.round(dx * inputWidth);
  49965. if (px < 0)
  49966. px = 0;
  49967. else if (px >= inputWidth)
  49968. px = inputWidth - 1;
  49969. var py = Math.round(dy * inputHeight);
  49970. if (py < 0)
  49971. py = 0;
  49972. else if (py >= inputHeight)
  49973. py = inputHeight - 1;
  49974. var inputY = (inputHeight - py - 1);
  49975. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  49976. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  49977. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  49978. return {
  49979. r: r,
  49980. g: g,
  49981. b: b
  49982. };
  49983. };
  49984. PanoramaToCubeMapTools.FACE_FRONT = [
  49985. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49986. new BABYLON.Vector3(1.0, -1.0, -1.0),
  49987. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  49988. new BABYLON.Vector3(1.0, 1.0, -1.0)
  49989. ];
  49990. PanoramaToCubeMapTools.FACE_BACK = [
  49991. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49992. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49993. new BABYLON.Vector3(1.0, 1.0, 1.0),
  49994. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  49995. ];
  49996. PanoramaToCubeMapTools.FACE_RIGHT = [
  49997. new BABYLON.Vector3(1.0, -1.0, -1.0),
  49998. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49999. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50000. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50001. ];
  50002. PanoramaToCubeMapTools.FACE_LEFT = [
  50003. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50004. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50005. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50006. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50007. ];
  50008. PanoramaToCubeMapTools.FACE_DOWN = [
  50009. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50010. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50011. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50012. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50013. ];
  50014. PanoramaToCubeMapTools.FACE_UP = [
  50015. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50016. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50017. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50018. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50019. ];
  50020. return PanoramaToCubeMapTools;
  50021. }());
  50022. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50023. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50024. })(BABYLON || (BABYLON = {}));
  50025. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50026. var BABYLON;
  50027. (function (BABYLON) {
  50028. var Internals;
  50029. (function (Internals) {
  50030. ;
  50031. /**
  50032. * This groups tools to convert HDR texture to native colors array.
  50033. */
  50034. var HDRTools = (function () {
  50035. function HDRTools() {
  50036. }
  50037. HDRTools.Ldexp = function (mantissa, exponent) {
  50038. if (exponent > 1023) {
  50039. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50040. }
  50041. if (exponent < -1074) {
  50042. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50043. }
  50044. return mantissa * Math.pow(2, exponent);
  50045. };
  50046. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50047. if (exponent > 0) {
  50048. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50049. float32array[index + 0] = red * exponent;
  50050. float32array[index + 1] = green * exponent;
  50051. float32array[index + 2] = blue * exponent;
  50052. }
  50053. else {
  50054. float32array[index + 0] = 0;
  50055. float32array[index + 1] = 0;
  50056. float32array[index + 2] = 0;
  50057. }
  50058. };
  50059. HDRTools.readStringLine = function (uint8array, startIndex) {
  50060. var line = "";
  50061. var character = "";
  50062. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50063. character = String.fromCharCode(uint8array[i]);
  50064. if (character == "\n") {
  50065. break;
  50066. }
  50067. line += character;
  50068. }
  50069. return line;
  50070. };
  50071. /**
  50072. * Reads header information from an RGBE texture stored in a native array.
  50073. * More information on this format are available here:
  50074. * https://en.wikipedia.org/wiki/RGBE_image_format
  50075. *
  50076. * @param uint8array The binary file stored in native array.
  50077. * @return The header information.
  50078. */
  50079. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50080. var height = 0;
  50081. var width = 0;
  50082. var line = this.readStringLine(uint8array, 0);
  50083. if (line[0] != '#' || line[1] != '?') {
  50084. throw "Bad HDR Format.";
  50085. }
  50086. var endOfHeader = false;
  50087. var findFormat = false;
  50088. var lineIndex = 0;
  50089. do {
  50090. lineIndex += (line.length + 1);
  50091. line = this.readStringLine(uint8array, lineIndex);
  50092. if (line == "FORMAT=32-bit_rle_rgbe") {
  50093. findFormat = true;
  50094. }
  50095. else if (line.length == 0) {
  50096. endOfHeader = true;
  50097. }
  50098. } while (!endOfHeader);
  50099. if (!findFormat) {
  50100. throw "HDR Bad header format, unsupported FORMAT";
  50101. }
  50102. lineIndex += (line.length + 1);
  50103. line = this.readStringLine(uint8array, lineIndex);
  50104. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50105. var match = sizeRegexp.exec(line);
  50106. // TODO. Support +Y and -X if needed.
  50107. if (match.length < 3) {
  50108. throw "HDR Bad header format, no size";
  50109. }
  50110. width = parseInt(match[2]);
  50111. height = parseInt(match[1]);
  50112. if (width < 8 || width > 0x7fff) {
  50113. throw "HDR Bad header format, unsupported size";
  50114. }
  50115. lineIndex += (line.length + 1);
  50116. return {
  50117. height: height,
  50118. width: width,
  50119. dataPosition: lineIndex
  50120. };
  50121. };
  50122. /**
  50123. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50124. * This RGBE texture needs to store the information as a panorama.
  50125. *
  50126. * More information on this format are available here:
  50127. * https://en.wikipedia.org/wiki/RGBE_image_format
  50128. *
  50129. * @param buffer The binary file stored in an array buffer.
  50130. * @param size The expected size of the extracted cubemap.
  50131. * @return The Cube Map information.
  50132. */
  50133. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50134. var uint8array = new Uint8Array(buffer);
  50135. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50136. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50137. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50138. return cubeMapData;
  50139. };
  50140. /**
  50141. * Returns the pixels data extracted from an RGBE texture.
  50142. * This pixels will be stored left to right up to down in the R G B order in one array.
  50143. *
  50144. * More information on this format are available here:
  50145. * https://en.wikipedia.org/wiki/RGBE_image_format
  50146. *
  50147. * @param uint8array The binary file stored in an array buffer.
  50148. * @param hdrInfo The header information of the file.
  50149. * @return The pixels data in RGB right to left up to down order.
  50150. */
  50151. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50152. // Keep for multi format supports.
  50153. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50154. };
  50155. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50156. var num_scanlines = hdrInfo.height;
  50157. var scanline_width = hdrInfo.width;
  50158. var a, b, c, d, count;
  50159. var dataIndex = hdrInfo.dataPosition;
  50160. var index = 0, endIndex = 0, i = 0;
  50161. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50162. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50163. // 3 channels of 4 bytes per pixel in float.
  50164. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50165. var resultArray = new Float32Array(resultBuffer);
  50166. // read in each successive scanline
  50167. while (num_scanlines > 0) {
  50168. a = uint8array[dataIndex++];
  50169. b = uint8array[dataIndex++];
  50170. c = uint8array[dataIndex++];
  50171. d = uint8array[dataIndex++];
  50172. if (a != 2 || b != 2 || (c & 0x80)) {
  50173. // this file is not run length encoded
  50174. throw "HDR Bad header format, not RLE";
  50175. }
  50176. if (((c << 8) | d) != scanline_width) {
  50177. throw "HDR Bad header format, wrong scan line width";
  50178. }
  50179. index = 0;
  50180. // read each of the four channels for the scanline into the buffer
  50181. for (i = 0; i < 4; i++) {
  50182. endIndex = (i + 1) * scanline_width;
  50183. while (index < endIndex) {
  50184. a = uint8array[dataIndex++];
  50185. b = uint8array[dataIndex++];
  50186. if (a > 128) {
  50187. // a run of the same value
  50188. count = a - 128;
  50189. if ((count == 0) || (count > endIndex - index)) {
  50190. throw "HDR Bad Format, bad scanline data (run)";
  50191. }
  50192. while (count-- > 0) {
  50193. scanLineArray[index++] = b;
  50194. }
  50195. }
  50196. else {
  50197. // a non-run
  50198. count = a;
  50199. if ((count == 0) || (count > endIndex - index)) {
  50200. throw "HDR Bad Format, bad scanline data (non-run)";
  50201. }
  50202. scanLineArray[index++] = b;
  50203. if (--count > 0) {
  50204. for (var j = 0; j < count; j++) {
  50205. scanLineArray[index++] = uint8array[dataIndex++];
  50206. }
  50207. }
  50208. }
  50209. }
  50210. }
  50211. // now convert data from buffer into floats
  50212. for (i = 0; i < scanline_width; i++) {
  50213. a = scanLineArray[i];
  50214. b = scanLineArray[i + scanline_width];
  50215. c = scanLineArray[i + 2 * scanline_width];
  50216. d = scanLineArray[i + 3 * scanline_width];
  50217. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50218. }
  50219. num_scanlines--;
  50220. }
  50221. return resultArray;
  50222. };
  50223. return HDRTools;
  50224. }());
  50225. Internals.HDRTools = HDRTools;
  50226. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50227. })(BABYLON || (BABYLON = {}));
  50228. //# sourceMappingURL=babylon.tools.hdr.js.map
  50229. //_______________________________________________________________
  50230. // Extracted from CubeMapGen:
  50231. // https://code.google.com/archive/p/cubemapgen/
  50232. //
  50233. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50234. //_______________________________________________________________
  50235. var BABYLON;
  50236. (function (BABYLON) {
  50237. var Internals;
  50238. (function (Internals) {
  50239. /**
  50240. * The bounding box information used during the conversion process.
  50241. */
  50242. var CMGBoundinBox = (function () {
  50243. function CMGBoundinBox() {
  50244. this.min = new BABYLON.Vector3(0, 0, 0);
  50245. this.max = new BABYLON.Vector3(0, 0, 0);
  50246. this.clear();
  50247. }
  50248. CMGBoundinBox.prototype.clear = function () {
  50249. this.min.x = CMGBoundinBox.MAX;
  50250. this.min.y = CMGBoundinBox.MAX;
  50251. this.min.z = CMGBoundinBox.MAX;
  50252. this.max.x = CMGBoundinBox.MIN;
  50253. this.max.y = CMGBoundinBox.MIN;
  50254. this.max.z = CMGBoundinBox.MIN;
  50255. };
  50256. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50257. this.min.x = Math.min(this.min.x, x);
  50258. this.min.y = Math.min(this.min.y, y);
  50259. this.min.z = Math.min(this.min.z, z);
  50260. this.max.x = Math.max(this.max.x, x);
  50261. this.max.y = Math.max(this.max.y, y);
  50262. this.max.z = Math.max(this.max.z, z);
  50263. };
  50264. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50265. this.min.x = Math.max(this.min.x, x);
  50266. this.min.y = Math.max(this.min.y, y);
  50267. this.min.z = Math.max(this.min.z, z);
  50268. };
  50269. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50270. this.max.x = Math.min(this.max.x, x);
  50271. this.max.y = Math.min(this.max.y, y);
  50272. this.max.z = Math.min(this.max.z, z);
  50273. };
  50274. CMGBoundinBox.prototype.empty = function () {
  50275. if ((this.min.x > this.max.y) ||
  50276. (this.min.y > this.max.y) ||
  50277. (this.min.z > this.max.y)) {
  50278. return true;
  50279. }
  50280. else {
  50281. return false;
  50282. }
  50283. };
  50284. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50285. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50286. return CMGBoundinBox;
  50287. }());
  50288. /**
  50289. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50290. * required by the glossinees of a material.
  50291. *
  50292. * This only supports the cosine drop power as well as Warp fixup generation method.
  50293. *
  50294. * This is using the process from CubeMapGen described here:
  50295. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50296. */
  50297. var PMREMGenerator = (function () {
  50298. /**
  50299. * Constructor of the generator.
  50300. *
  50301. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50302. * @param inputSize The size of the cubemap faces
  50303. * @param outputSize The size of the output cubemap faces
  50304. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50305. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50306. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50307. * @param specularPower The max specular level of the desired cubemap
  50308. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50309. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50310. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50311. */
  50312. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50313. this.input = input;
  50314. this.inputSize = inputSize;
  50315. this.outputSize = outputSize;
  50316. this.maxNumMipLevels = maxNumMipLevels;
  50317. this.numChannels = numChannels;
  50318. this.isFloat = isFloat;
  50319. this.specularPower = specularPower;
  50320. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50321. this.excludeBase = excludeBase;
  50322. this.fixup = fixup;
  50323. this._outputSurface = [];
  50324. this._numMipLevels = 0;
  50325. }
  50326. /**
  50327. * Launches the filter process and return the result.
  50328. *
  50329. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50330. */
  50331. PMREMGenerator.prototype.filterCubeMap = function () {
  50332. // Init cubemap processor
  50333. this.init();
  50334. // Filters the cubemap
  50335. this.filterCubeMapMipChain();
  50336. // Returns the filtered mips.
  50337. return this._outputSurface;
  50338. };
  50339. PMREMGenerator.prototype.init = function () {
  50340. var i;
  50341. var j;
  50342. var mipLevelSize;
  50343. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50344. if (this.maxNumMipLevels == 0) {
  50345. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50346. }
  50347. //first miplevel size
  50348. mipLevelSize = this.outputSize;
  50349. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50350. for (j = 0; j < this.maxNumMipLevels; j++) {
  50351. this._outputSurface.length++;
  50352. this._outputSurface[j] = [];
  50353. //Iterate over faces for output images
  50354. for (i = 0; i < 6; i++) {
  50355. this._outputSurface[j].length++;
  50356. // Initializes a new array for the output.
  50357. if (this.isFloat) {
  50358. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50359. }
  50360. else {
  50361. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50362. }
  50363. }
  50364. //next mip level is half size
  50365. mipLevelSize >>= 1;
  50366. this._numMipLevels++;
  50367. //terminate if mip chain becomes too small
  50368. if (mipLevelSize == 0) {
  50369. this.maxNumMipLevels = j;
  50370. return;
  50371. }
  50372. }
  50373. };
  50374. //--------------------------------------------------------------------------------------
  50375. //Cube map filtering and mip chain generation.
  50376. // the cube map filtereing is specified using a number of parameters:
  50377. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50378. // indicates the region of the hemisphere to filter over for each tap.
  50379. //
  50380. // Note that the top mip level is also a filtered version of the original input images
  50381. // as well in order to create mip chains for diffuse environment illumination.
  50382. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50383. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50384. //
  50385. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50386. // is a_InitialMipAngle
  50387. //
  50388. // The angle for the subsequent levels of the mip chain are specified by their parents
  50389. // filtering angle and a per-level scale and bias
  50390. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50391. //
  50392. //--------------------------------------------------------------------------------------
  50393. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50394. // First, take count of the lighting model to modify SpecularPower
  50395. // 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;
  50396. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50397. //Cone angle start (for generating subsequent mip levels)
  50398. var currentSpecularPower = this.specularPower;
  50399. //Build filter lookup tables based on the source miplevel size
  50400. this.precomputeFilterLookupTables(this.inputSize);
  50401. // Note that we need to filter the first level before generating mipmap
  50402. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50403. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50404. // TODO : Write a function to copy and scale the base mipmap in output
  50405. // I am just lazy here and just put a high specular power value, and do some if.
  50406. if (this.excludeBase && (levelIndex == 0)) {
  50407. // 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).
  50408. currentSpecularPower = 100000.0;
  50409. }
  50410. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50411. var srcCubeImage = this.input;
  50412. var dstCubeImage = this._outputSurface[levelIndex];
  50413. var dstSize = this.outputSize >> levelIndex;
  50414. // Compute required angle.
  50415. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50416. // filter cube surfaces
  50417. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50418. // fix seams
  50419. if (this.fixup) {
  50420. this.fixupCubeEdges(dstCubeImage, dstSize);
  50421. }
  50422. // Decrease the specular power to generate the mipmap chain
  50423. // TODO : Use another method for Exclude (see first comment at start of the function
  50424. if (this.excludeBase && (levelIndex == 0)) {
  50425. currentSpecularPower = this.specularPower;
  50426. }
  50427. currentSpecularPower *= this.cosinePowerDropPerMip;
  50428. }
  50429. };
  50430. //--------------------------------------------------------------------------------------
  50431. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50432. // It allow to optimize the texel to access base on the specular power.
  50433. //--------------------------------------------------------------------------------------
  50434. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50435. // We want to find the alpha such that:
  50436. // cos(alpha)^cosinePower = epsilon
  50437. // That's: acos(epsilon^(1/cosinePower))
  50438. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50439. var angle = 180.0;
  50440. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50441. angle *= 180.0 / Math.PI; // Convert to degree
  50442. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50443. return angle;
  50444. };
  50445. //--------------------------------------------------------------------------------------
  50446. //Builds the following lookup tables prior to filtering:
  50447. // -normalizer cube map
  50448. // -tap weight lookup table
  50449. //
  50450. //--------------------------------------------------------------------------------------
  50451. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50452. var srcTexelAngle;
  50453. var iCubeFace;
  50454. //clear pre-existing normalizer cube map
  50455. this._normCubeMap = [];
  50456. //Normalized vectors per cubeface and per-texel solid angle
  50457. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50458. };
  50459. //--------------------------------------------------------------------------------------
  50460. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50461. //
  50462. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50463. //
  50464. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50465. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50466. // below
  50467. //--------------------------------------------------------------------------------------
  50468. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50469. var iCubeFace;
  50470. var u;
  50471. var v;
  50472. //iterate over cube faces
  50473. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50474. //First three channels for norm cube, and last channel for solid angle
  50475. this._normCubeMap.push(new Float32Array(size * size * 4));
  50476. //fast texture walk, build normalizer cube map
  50477. var facesData = this.input[iCubeFace];
  50478. for (v = 0; v < size; v++) {
  50479. for (u = 0; u < size; u++) {
  50480. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50481. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50482. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50483. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50484. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50485. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50486. }
  50487. }
  50488. }
  50489. };
  50490. //--------------------------------------------------------------------------------------
  50491. // Convert cubemap face texel coordinates and face idx to 3D vector
  50492. // note the U and V coords are integer coords and range from 0 to size-1
  50493. // this routine can be used to generate a normalizer cube map
  50494. //--------------------------------------------------------------------------------------
  50495. // SL BEGIN
  50496. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50497. var nvcU;
  50498. var nvcV;
  50499. var tempVec;
  50500. // Change from original AMD code
  50501. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50502. // + 0.5f is for texel center addressing
  50503. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50504. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50505. // warp fixup
  50506. if (fixup && size > 1) {
  50507. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50508. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50509. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50510. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50511. }
  50512. // Get current vector
  50513. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50514. // U contribution
  50515. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50516. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50517. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50518. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50519. // V contribution and Sum
  50520. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50521. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50522. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50523. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50524. //add face axis
  50525. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50526. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50527. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50528. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50529. //normalize vector
  50530. PMREMGenerator._vectorTemp.normalize();
  50531. return PMREMGenerator._vectorTemp;
  50532. };
  50533. //--------------------------------------------------------------------------------------
  50534. // Convert 3D vector to cubemap face texel coordinates and face idx
  50535. // note the U and V coords are integer coords and range from 0 to size-1
  50536. // this routine can be used to generate a normalizer cube map
  50537. //
  50538. // returns face IDX and texel coords
  50539. //--------------------------------------------------------------------------------------
  50540. // SL BEGIN
  50541. /*
  50542. Mapping Texture Coordinates to Cube Map Faces
  50543. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50544. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50545. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50546. map arrangement in Pixar's RenderMan package.
  50547. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50548. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50549. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50550. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50551. the major axis direction). The target column in the table below explains how the major axis direction
  50552. maps to the 2D image of a particular cube map target.
  50553. major axis
  50554. direction target sc tc ma
  50555. ---------- --------------------------------- --- --- ---
  50556. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50557. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50558. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50559. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50560. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50561. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50562. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50563. an updated (s,t) is calculated as follows
  50564. s = ( sc/|ma| + 1 ) / 2
  50565. t = ( tc/|ma| + 1 ) / 2
  50566. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50567. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50568. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50569. */
  50570. // Note this method return U and V in range from 0 to size-1
  50571. // SL END
  50572. // Store the information in vector3 for convenience (faceindex, u, v)
  50573. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50574. var maxCoord;
  50575. var faceIdx;
  50576. //absolute value 3
  50577. var absX = Math.abs(x);
  50578. var absY = Math.abs(y);
  50579. var absZ = Math.abs(z);
  50580. if (absX >= absY && absX >= absZ) {
  50581. maxCoord = absX;
  50582. if (x >= 0) {
  50583. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50584. }
  50585. else {
  50586. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50587. }
  50588. }
  50589. else if (absY >= absX && absY >= absZ) {
  50590. maxCoord = absY;
  50591. if (y >= 0) {
  50592. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50593. }
  50594. else {
  50595. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50596. }
  50597. }
  50598. else {
  50599. maxCoord = absZ;
  50600. if (z >= 0) {
  50601. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50602. }
  50603. else {
  50604. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50605. }
  50606. }
  50607. //divide through by max coord so face vector lies on cube face
  50608. var scale = 1 / maxCoord;
  50609. x *= scale;
  50610. y *= scale;
  50611. z *= scale;
  50612. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50613. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50614. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50615. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50616. // Modify original AMD code to return value from 0 to Size - 1
  50617. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50618. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50619. PMREMGenerator._vectorTemp.x = faceIdx;
  50620. PMREMGenerator._vectorTemp.y = u;
  50621. PMREMGenerator._vectorTemp.z = v;
  50622. return PMREMGenerator._vectorTemp;
  50623. };
  50624. //--------------------------------------------------------------------------------------
  50625. //Original code from Ignacio CastaÒo
  50626. // This formula is from Manne ÷hrstrˆm's thesis.
  50627. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50628. // cube face and return the area of the projection of that portion on the
  50629. // surface of the sphere.
  50630. //--------------------------------------------------------------------------------------
  50631. PMREMGenerator.prototype.areaElement = function (x, y) {
  50632. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50633. };
  50634. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50635. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50636. // (+ 0.5f is for texel center addressing)
  50637. u = (2.0 * (u + 0.5) / size) - 1.0;
  50638. v = (2.0 * (v + 0.5) / size) - 1.0;
  50639. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50640. var invResolution = 1.0 / size;
  50641. // U and V are the -1..1 texture coordinate on the current face.
  50642. // Get projected area for this texel
  50643. var x0 = u - invResolution;
  50644. var y0 = v - invResolution;
  50645. var x1 = u + invResolution;
  50646. var y1 = v + invResolution;
  50647. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50648. return solidAngle;
  50649. };
  50650. //--------------------------------------------------------------------------------------
  50651. //The key to the speed of these filtering routines is to quickly define a per-face
  50652. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50653. // Later these pixels are selectively processed based on their dot products to see if
  50654. // they reside within the filtering cone.
  50655. //
  50656. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50657. // of the number of texels needed to be covered in width and height order to filter the
  50658. // region. the bounding box for the center taps face is defined first, and if the
  50659. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50660. // defined next
  50661. //--------------------------------------------------------------------------------------
  50662. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50663. // note that pixels within these regions may be rejected
  50664. // based on the anlge
  50665. var iCubeFace;
  50666. var u;
  50667. var v;
  50668. // bounding box per face to specify region to process
  50669. var filterExtents = [];
  50670. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50671. filterExtents.push(new CMGBoundinBox());
  50672. }
  50673. // min angle a src texel can cover (in degrees)
  50674. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  50675. // angle about center tap to define filter cone
  50676. // filter angle is 1/2 the cone angle
  50677. var filterAngle = filterConeAngle / 2.0;
  50678. //ensure filter angle is larger than a texel
  50679. if (filterAngle < srcTexelAngle) {
  50680. filterAngle = srcTexelAngle;
  50681. }
  50682. //ensure filter cone is always smaller than the hemisphere
  50683. if (filterAngle > 90.0) {
  50684. filterAngle = 90.0;
  50685. }
  50686. // the maximum number of texels in 1D the filter cone angle will cover
  50687. // used to determine bounding box size for filter extents
  50688. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  50689. // ensure conservative region always covers at least one texel
  50690. if (filterSize < 1) {
  50691. filterSize = 1;
  50692. }
  50693. // dotProdThresh threshold based on cone angle to determine whether or not taps
  50694. // reside within the cone angle
  50695. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  50696. // process required faces
  50697. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50698. //iterate over dst cube map face texel
  50699. for (v = 0; v < dstSize; v++) {
  50700. for (u = 0; u < dstSize; u++) {
  50701. //get center tap direction
  50702. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  50703. //clear old per-face filter extents
  50704. this.clearFilterExtents(filterExtents);
  50705. //define per-face filter extents
  50706. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  50707. //perform filtering of src faces using filter extents
  50708. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  50709. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  50710. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  50711. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  50712. }
  50713. }
  50714. }
  50715. };
  50716. //--------------------------------------------------------------------------------------
  50717. //Clear filter extents for the 6 cube map faces
  50718. //--------------------------------------------------------------------------------------
  50719. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  50720. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  50721. filterExtents[iCubeFaces].clear();
  50722. }
  50723. };
  50724. //--------------------------------------------------------------------------------------
  50725. //Define per-face bounding box filter extents
  50726. //
  50727. // These define conservative texel regions in each of the faces the filter can possibly
  50728. // process. When the pixels in the regions are actually processed, the dot product
  50729. // between the tap vector and the center tap vector is used to determine the weight of
  50730. // the tap and whether or not the tap is within the cone.
  50731. //
  50732. //--------------------------------------------------------------------------------------
  50733. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  50734. //neighboring face and bleed over amount, and width of BBOX for
  50735. // left, right, top, and bottom edges of this face
  50736. var bleedOverAmount = [0, 0, 0, 0];
  50737. var bleedOverBBoxMin = [0, 0, 0, 0];
  50738. var bleedOverBBoxMax = [0, 0, 0, 0];
  50739. var neighborFace;
  50740. var neighborEdge;
  50741. var oppositeFaceIdx;
  50742. //get face idx, and u, v info from center tap dir
  50743. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  50744. var faceIdx = result.x;
  50745. var u = result.y;
  50746. var v = result.z;
  50747. //define bbox size within face
  50748. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  50749. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  50750. filterExtents[faceIdx].clampMin(0, 0, 0);
  50751. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  50752. //u and v extent in face corresponding to center tap
  50753. var minU = filterExtents[faceIdx].min.x;
  50754. var minV = filterExtents[faceIdx].min.y;
  50755. var maxU = filterExtents[faceIdx].max.x;
  50756. var maxV = filterExtents[faceIdx].max.y;
  50757. //bleed over amounts for face across u=0 edge (left)
  50758. bleedOverAmount[0] = (bboxSize - u);
  50759. bleedOverBBoxMin[0] = minV;
  50760. bleedOverBBoxMax[0] = maxV;
  50761. //bleed over amounts for face across u=1 edge (right)
  50762. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  50763. bleedOverBBoxMin[1] = minV;
  50764. bleedOverBBoxMax[1] = maxV;
  50765. //bleed over to face across v=0 edge (up)
  50766. bleedOverAmount[2] = (bboxSize - v);
  50767. bleedOverBBoxMin[2] = minU;
  50768. bleedOverBBoxMax[2] = maxU;
  50769. //bleed over to face across v=1 edge (down)
  50770. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  50771. bleedOverBBoxMin[3] = minU;
  50772. bleedOverBBoxMax[3] = maxU;
  50773. //compute bleed over regions in neighboring faces
  50774. for (var i = 0; i < 4; i++) {
  50775. if (bleedOverAmount[i] > 0) {
  50776. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  50777. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  50778. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  50779. // be flipped: the cases are
  50780. // if a left edge mates with a left or bottom edge on the neighbor
  50781. // if a top edge mates with a top or right edge on the neighbor
  50782. // if a right edge mates with a right or top edge on the neighbor
  50783. // if a bottom edge mates with a bottom or left edge on the neighbor
  50784. //Seeing as the edges are enumerated as follows
  50785. // left =0
  50786. // right =1
  50787. // top =2
  50788. // bottom =3
  50789. //
  50790. // so if the edge enums are the same, or the sum of the enums == 3,
  50791. // the bbox needs to be flipped
  50792. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  50793. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  50794. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  50795. }
  50796. //The way the bounding box is extended onto the neighboring face
  50797. // depends on which edge of neighboring face abuts with this one
  50798. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  50799. case PMREMGenerator.CP_EDGE_LEFT:
  50800. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  50801. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50802. break;
  50803. case PMREMGenerator.CP_EDGE_RIGHT:
  50804. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  50805. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50806. break;
  50807. case PMREMGenerator.CP_EDGE_TOP:
  50808. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  50809. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  50810. break;
  50811. case PMREMGenerator.CP_EDGE_BOTTOM:
  50812. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  50813. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  50814. break;
  50815. }
  50816. //clamp filter extents in non-center tap faces to remain within surface
  50817. filterExtents[neighborFace].clampMin(0, 0, 0);
  50818. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  50819. }
  50820. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  50821. // from the center tap face, then process the opposite face entirely for now.
  50822. //Note that the cases in which this happens, what usually happens is that
  50823. // more than one edge bleeds onto the opposite face, and the bounding box
  50824. // encompasses the entire cube map face.
  50825. if (bleedOverAmount[i] > srcSize) {
  50826. //determine opposite face
  50827. switch (faceIdx) {
  50828. case PMREMGenerator.CP_FACE_X_POS:
  50829. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50830. break;
  50831. case PMREMGenerator.CP_FACE_X_NEG:
  50832. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  50833. break;
  50834. case PMREMGenerator.CP_FACE_Y_POS:
  50835. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50836. break;
  50837. case PMREMGenerator.CP_FACE_Y_NEG:
  50838. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50839. break;
  50840. case PMREMGenerator.CP_FACE_Z_POS:
  50841. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50842. break;
  50843. case PMREMGenerator.CP_FACE_Z_NEG:
  50844. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50845. break;
  50846. default:
  50847. break;
  50848. }
  50849. //just encompass entire face for now
  50850. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  50851. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  50852. }
  50853. }
  50854. };
  50855. //--------------------------------------------------------------------------------------
  50856. //ProcessFilterExtents
  50857. // Process bounding box in each cube face
  50858. //
  50859. //--------------------------------------------------------------------------------------
  50860. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  50861. //accumulators are 64-bit floats in order to have the precision needed
  50862. // over a summation of a large number of pixels
  50863. var dstAccum = [0, 0, 0, 0];
  50864. var weightAccum = 0;
  50865. var k = 0;
  50866. var nSrcChannels = this.numChannels;
  50867. // norm cube map and srcCubeMap have same face width
  50868. var faceWidth = srcSize;
  50869. //amount to add to pointer to move to next scanline in images
  50870. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  50871. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  50872. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  50873. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  50874. // iterate over cubefaces
  50875. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  50876. //if bbox is non empty
  50877. if (!filterExtents[iFaceIdx].empty()) {
  50878. var uStart = filterExtents[iFaceIdx].min.x;
  50879. var vStart = filterExtents[iFaceIdx].min.y;
  50880. var uEnd = filterExtents[iFaceIdx].max.x;
  50881. var vEnd = filterExtents[iFaceIdx].max.y;
  50882. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  50883. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  50884. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  50885. for (var v = vStart; v <= vEnd; v++) {
  50886. var normCubeRowWalk = 0;
  50887. var srcCubeRowWalk = 0;
  50888. for (var u = uStart; u <= uEnd; u++) {
  50889. //pointer to direction in cube map associated with texel
  50890. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  50891. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  50892. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  50893. //check dot product to see if texel is within cone
  50894. var tapDotProd = texelVectX * centerTapDir.x +
  50895. texelVectY * centerTapDir.y +
  50896. texelVectZ * centerTapDir.z;
  50897. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  50898. //solid angle stored in 4th channel of normalizer/solid angle cube map
  50899. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  50900. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  50901. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  50902. // so just adding one to specularpower do the trick.
  50903. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  50904. //iterate over channels
  50905. for (k = 0; k < nSrcChannels; k++) {
  50906. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  50907. srcCubeRowWalk++;
  50908. }
  50909. weightAccum += weight; //accumulate weight
  50910. }
  50911. else {
  50912. //step across source pixel
  50913. srcCubeRowWalk += nSrcChannels;
  50914. }
  50915. normCubeRowWalk += 4; // 4 channels per norm cube map.
  50916. }
  50917. startIndexNormCubeMap += normCubePitch;
  50918. startIndexSrcCubeMap += srcCubePitch;
  50919. }
  50920. }
  50921. }
  50922. //divide through by weights if weight is non zero
  50923. if (weightAccum != 0.0) {
  50924. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  50925. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  50926. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  50927. if (this.numChannels > 3) {
  50928. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  50929. }
  50930. }
  50931. else {
  50932. // otherwise sample nearest
  50933. // get face idx and u, v texel coordinate in face
  50934. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  50935. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  50936. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  50937. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  50938. if (this.numChannels > 3) {
  50939. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  50940. }
  50941. }
  50942. return PMREMGenerator._vectorTemp;
  50943. };
  50944. //--------------------------------------------------------------------------------------
  50945. // Fixup cube edges
  50946. //
  50947. // average texels on cube map faces across the edges
  50948. // WARP/BENT Method Only.
  50949. //--------------------------------------------------------------------------------------
  50950. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  50951. var k;
  50952. var j;
  50953. var i;
  50954. var iFace;
  50955. var iCorner = 0;
  50956. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  50957. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  50958. // note that if functionality to filter across the three texels for each corner, then
  50959. //indexed by corner and face idx. the array contains the face the start points belongs to.
  50960. var cornerPtr = [
  50961. [[], [], []],
  50962. [[], [], []],
  50963. [[], [], []],
  50964. [[], [], []],
  50965. [[], [], []],
  50966. [[], [], []],
  50967. [[], [], []],
  50968. [[], [], []]
  50969. ];
  50970. //if there is no fixup, or fixup width = 0, do nothing
  50971. if (cubeMapSize < 1) {
  50972. return;
  50973. }
  50974. //special case 1x1 cubemap, average face colors
  50975. if (cubeMapSize == 1) {
  50976. //iterate over channels
  50977. for (k = 0; k < this.numChannels; k++) {
  50978. var accum = 0.0;
  50979. //iterate over faces to accumulate face colors
  50980. for (iFace = 0; iFace < 6; iFace++) {
  50981. accum += cubeMap[iFace][k];
  50982. }
  50983. //compute average over 6 face colors
  50984. accum /= 6.0;
  50985. //iterate over faces to distribute face colors
  50986. for (iFace = 0; iFace < 6; iFace++) {
  50987. cubeMap[iFace][k] = accum;
  50988. }
  50989. }
  50990. return;
  50991. }
  50992. //iterate over faces to collect list of corner texel pointers
  50993. for (iFace = 0; iFace < 6; iFace++) {
  50994. //the 4 corner pointers for this face
  50995. faceCornerStartIndicies[0] = [iFace, 0];
  50996. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  50997. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  50998. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  50999. //iterate over face corners to collect cube corner pointers
  51000. for (iCorner = 0; iCorner < 4; iCorner++) {
  51001. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51002. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51003. cornerNumPtrs[corner]++;
  51004. }
  51005. }
  51006. //iterate over corners to average across corner tap values
  51007. for (iCorner = 0; iCorner < 8; iCorner++) {
  51008. for (k = 0; k < this.numChannels; k++) {
  51009. var cornerTapAccum = 0.0;
  51010. //iterate over corner texels and average results
  51011. for (i = 0; i < 3; i++) {
  51012. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51013. }
  51014. //divide by 3 to compute average of corner tap values
  51015. cornerTapAccum *= (1.0 / 3.0);
  51016. //iterate over corner texels and average results
  51017. for (i = 0; i < 3; i++) {
  51018. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51019. }
  51020. }
  51021. }
  51022. //iterate over the twelve edges of the cube to average across edges
  51023. for (i = 0; i < 12; i++) {
  51024. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51025. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51026. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51027. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51028. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51029. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51030. var edgeWalk = 0;
  51031. var neighborEdgeWalk = 0;
  51032. //Determine walking pointers based on edge type
  51033. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51034. switch (edge) {
  51035. case PMREMGenerator.CP_EDGE_LEFT:
  51036. // no change to faceEdgeStartPtr
  51037. edgeWalk = this.numChannels * cubeMapSize;
  51038. break;
  51039. case PMREMGenerator.CP_EDGE_RIGHT:
  51040. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51041. edgeWalk = this.numChannels * cubeMapSize;
  51042. break;
  51043. case PMREMGenerator.CP_EDGE_TOP:
  51044. // no change to faceEdgeStartPtr
  51045. edgeWalk = this.numChannels;
  51046. break;
  51047. case PMREMGenerator.CP_EDGE_BOTTOM:
  51048. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51049. edgeWalk = this.numChannels;
  51050. break;
  51051. }
  51052. //For certain types of edge abutments, the neighbor edge walk needs to
  51053. // be flipped: the cases are
  51054. // if a left edge mates with a left or bottom edge on the neighbor
  51055. // if a top edge mates with a top or right edge on the neighbor
  51056. // if a right edge mates with a right or top edge on the neighbor
  51057. // if a bottom edge mates with a bottom or left edge on the neighbor
  51058. //Seeing as the edges are enumerated as follows
  51059. // left =0
  51060. // right =1
  51061. // top =2
  51062. // bottom =3
  51063. //
  51064. //If the edge enums are the same, or the sum of the enums == 3,
  51065. // the neighbor edge walk needs to be flipped
  51066. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51067. switch (neighborEdge) {
  51068. case PMREMGenerator.CP_EDGE_LEFT:
  51069. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51070. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51071. break;
  51072. case PMREMGenerator.CP_EDGE_RIGHT:
  51073. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51074. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51075. break;
  51076. case PMREMGenerator.CP_EDGE_TOP:
  51077. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51078. neighborEdgeWalk = -this.numChannels;
  51079. break;
  51080. case PMREMGenerator.CP_EDGE_BOTTOM:
  51081. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51082. neighborEdgeWalk = -this.numChannels;
  51083. break;
  51084. }
  51085. }
  51086. else {
  51087. //swapped direction neighbor edge walk
  51088. switch (neighborEdge) {
  51089. case PMREMGenerator.CP_EDGE_LEFT:
  51090. //no change to neighborEdgeStartPtr for this case since it points
  51091. // to the upper left corner already
  51092. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51093. break;
  51094. case PMREMGenerator.CP_EDGE_RIGHT:
  51095. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51096. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51097. break;
  51098. case PMREMGenerator.CP_EDGE_TOP:
  51099. //no change to neighborEdgeStartPtr for this case since it points
  51100. // to the upper left corner already
  51101. neighborEdgeWalk = this.numChannels;
  51102. break;
  51103. case PMREMGenerator.CP_EDGE_BOTTOM:
  51104. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51105. neighborEdgeWalk = this.numChannels;
  51106. break;
  51107. }
  51108. }
  51109. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51110. //nearby neighborhood
  51111. //step ahead one texel on edge
  51112. edgeStartIndex += edgeWalk;
  51113. neighborEdgeStartIndex += neighborEdgeWalk;
  51114. // note that this loop does not process the corner texels, since they have already been
  51115. // averaged across faces across earlier
  51116. for (j = 1; j < (cubeMapSize - 1); j++) {
  51117. //for each set of taps along edge, average them
  51118. // and rewrite the results into the edges
  51119. for (k = 0; k < this.numChannels; k++) {
  51120. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51121. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51122. //compute average of tap intensity values
  51123. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51124. //propagate average of taps to edge taps
  51125. cubeMap[face][edgeStartIndex + k] = avgTap;
  51126. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51127. }
  51128. edgeStartIndex += edgeWalk;
  51129. neighborEdgeStartIndex += neighborEdgeWalk;
  51130. }
  51131. }
  51132. };
  51133. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51134. PMREMGenerator.CP_UDIR = 0;
  51135. PMREMGenerator.CP_VDIR = 1;
  51136. PMREMGenerator.CP_FACEAXIS = 2;
  51137. //used to index cube faces
  51138. PMREMGenerator.CP_FACE_X_POS = 0;
  51139. PMREMGenerator.CP_FACE_X_NEG = 1;
  51140. PMREMGenerator.CP_FACE_Y_POS = 2;
  51141. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51142. PMREMGenerator.CP_FACE_Z_POS = 4;
  51143. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51144. //used to index image edges
  51145. // NOTE.. the actual number corresponding to the edge is important
  51146. // do not change these, or the code will break
  51147. //
  51148. // CP_EDGE_LEFT is u = 0
  51149. // CP_EDGE_RIGHT is u = width-1
  51150. // CP_EDGE_TOP is v = 0
  51151. // CP_EDGE_BOTTOM is v = height-1
  51152. PMREMGenerator.CP_EDGE_LEFT = 0;
  51153. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51154. PMREMGenerator.CP_EDGE_TOP = 2;
  51155. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51156. //corners of CUBE map (P or N specifys if it corresponds to the
  51157. // positive or negative direction each of X, Y, and Z
  51158. PMREMGenerator.CP_CORNER_NNN = 0;
  51159. PMREMGenerator.CP_CORNER_NNP = 1;
  51160. PMREMGenerator.CP_CORNER_NPN = 2;
  51161. PMREMGenerator.CP_CORNER_NPP = 3;
  51162. PMREMGenerator.CP_CORNER_PNN = 4;
  51163. PMREMGenerator.CP_CORNER_PNP = 5;
  51164. PMREMGenerator.CP_CORNER_PPN = 6;
  51165. PMREMGenerator.CP_CORNER_PPP = 7;
  51166. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51167. //3x2 matrices that map cube map indexing vectors in 3d
  51168. // (after face selection and divide through by the
  51169. // _ABSOLUTE VALUE_ of the max coord)
  51170. // into NVC space
  51171. //Note this currently assumes the D3D cube face ordering and orientation
  51172. PMREMGenerator._sgFace2DMapping = [
  51173. //XPOS face
  51174. [[0, 0, -1],
  51175. [0, -1, 0],
  51176. [1, 0, 0]],
  51177. //XNEG face
  51178. [[0, 0, 1],
  51179. [0, -1, 0],
  51180. [-1, 0, 0]],
  51181. //YPOS face
  51182. [[1, 0, 0],
  51183. [0, 0, 1],
  51184. [0, 1, 0]],
  51185. //YNEG face
  51186. [[1, 0, 0],
  51187. [0, 0, -1],
  51188. [0, -1, 0]],
  51189. //ZPOS face
  51190. [[1, 0, 0],
  51191. [0, -1, 0],
  51192. [0, 0, 1]],
  51193. //ZNEG face
  51194. [[-1, 0, 0],
  51195. [0, -1, 0],
  51196. [0, 0, -1]],
  51197. ];
  51198. //------------------------------------------------------------------------------
  51199. // D3D cube map face specification
  51200. // mapping from 3D x,y,z cube map lookup coordinates
  51201. // to 2D within face u,v coordinates
  51202. //
  51203. // --------------------> U direction
  51204. // | (within-face texture space)
  51205. // | _____
  51206. // | | |
  51207. // | | +Y |
  51208. // | _____|_____|_____ _____
  51209. // | | | | | |
  51210. // | | -X | +Z | +X | -Z |
  51211. // | |_____|_____|_____|_____|
  51212. // | | |
  51213. // | | -Y |
  51214. // | |_____|
  51215. // |
  51216. // v V direction
  51217. // (within-face texture space)
  51218. //------------------------------------------------------------------------------
  51219. //Information about neighbors and how texture coorrdinates change across faces
  51220. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51221. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51222. //Note this currently assumes the D3D cube face ordering and orientation
  51223. PMREMGenerator._sgCubeNgh = [
  51224. //XPOS face
  51225. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51226. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51227. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51228. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51229. //XNEG face
  51230. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51231. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51232. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51233. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51234. //YPOS face
  51235. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51236. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51237. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51238. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51239. //YNEG face
  51240. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51241. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51242. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51243. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51244. //ZPOS face
  51245. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51246. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51247. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51248. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51249. //ZNEG face
  51250. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51251. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51252. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51253. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51254. ];
  51255. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51256. // this table is used to average over the edges.
  51257. PMREMGenerator._sgCubeEdgeList = [
  51258. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51259. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51260. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51261. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51262. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51263. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51264. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51265. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51266. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51267. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51268. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51269. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51270. ];
  51271. //Information about which of the 8 cube corners are correspond to the
  51272. // the 4 corners in each cube face
  51273. // the order is upper left, upper right, lower left, lower right
  51274. PMREMGenerator._sgCubeCornerList = [
  51275. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51276. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51277. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51278. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51279. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51280. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51281. ];
  51282. return PMREMGenerator;
  51283. }());
  51284. Internals.PMREMGenerator = PMREMGenerator;
  51285. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51286. })(BABYLON || (BABYLON = {}));
  51287. //# sourceMappingURL=babylon.tools.pmremgenerator.js.map
  51288. var BABYLON;
  51289. (function (BABYLON) {
  51290. /**
  51291. * This represents a texture coming from an HDR input.
  51292. *
  51293. * The only supported format is currently panorama picture stored in RGBE format.
  51294. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51295. */
  51296. var HDRCubeTexture = (function (_super) {
  51297. __extends(HDRCubeTexture, _super);
  51298. /**
  51299. * Instantiates an HDRTexture from the following parameters.
  51300. *
  51301. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51302. * @param scene The scene the texture will be used in
  51303. * @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.
  51304. * @param noMipmap Forces to not generate the mipmap if true
  51305. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51306. * @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)
  51307. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51308. */
  51309. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  51310. if (noMipmap === void 0) { noMipmap = false; }
  51311. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51312. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51313. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51314. _super.call(this, scene);
  51315. this._useInGammaSpace = false;
  51316. this._generateHarmonics = true;
  51317. this._isBABYLONPreprocessed = false;
  51318. /**
  51319. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51320. */
  51321. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51322. /**
  51323. * The spherical polynomial data extracted from the texture.
  51324. */
  51325. this.sphericalPolynomial = null;
  51326. /**
  51327. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51328. * This is usefull at run time to apply the good shader.
  51329. */
  51330. this.isPMREM = false;
  51331. if (!url) {
  51332. return;
  51333. }
  51334. this.name = url;
  51335. this.url = url;
  51336. this.hasAlpha = false;
  51337. this.isCube = true;
  51338. this._textureMatrix = BABYLON.Matrix.Identity();
  51339. if (size) {
  51340. this._isBABYLONPreprocessed = false;
  51341. this._noMipmap = noMipmap;
  51342. this._size = size;
  51343. this._useInGammaSpace = useInGammaSpace;
  51344. this._usePMREMGenerator = usePMREMGenerator &&
  51345. scene.getEngine().getCaps().textureLOD &&
  51346. this.getScene().getEngine().getCaps().textureFloat &&
  51347. !this._useInGammaSpace;
  51348. }
  51349. else {
  51350. this._isBABYLONPreprocessed = true;
  51351. this._noMipmap = false;
  51352. this._useInGammaSpace = false;
  51353. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51354. this.getScene().getEngine().getCaps().textureFloat &&
  51355. !this._useInGammaSpace;
  51356. }
  51357. this.isPMREM = this._usePMREMGenerator;
  51358. this._texture = this._getFromCache(url, this._noMipmap);
  51359. if (!this._texture) {
  51360. if (!scene.useDelayedTextureLoading) {
  51361. this.loadTexture();
  51362. }
  51363. else {
  51364. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51365. }
  51366. }
  51367. }
  51368. /**
  51369. * Occurs when the file is a preprocessed .babylon.hdr file.
  51370. */
  51371. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51372. var _this = this;
  51373. var mipLevels = 0;
  51374. var floatArrayView = null;
  51375. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51376. var mips = [];
  51377. var startIndex = 30;
  51378. for (var level = 0; level < mipLevels; level++) {
  51379. mips.push([]);
  51380. // Fill each pixel of the mip level.
  51381. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51382. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51383. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51384. mips[level].push(faceData);
  51385. startIndex += faceSize;
  51386. }
  51387. }
  51388. return mips;
  51389. } : null;
  51390. var callback = function (buffer) {
  51391. // Create Native Array Views
  51392. var intArrayView = new Int32Array(buffer);
  51393. floatArrayView = new Float32Array(buffer);
  51394. // Fill header.
  51395. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51396. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51397. // Update Texture Information.
  51398. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51399. // Fill polynomial information.
  51400. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51401. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51402. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51403. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51404. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51405. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51406. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51407. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51408. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51409. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51410. // Fill pixel data.
  51411. mipLevels = intArrayView[29]; // Number of mip levels.
  51412. var startIndex = 30;
  51413. var data = [];
  51414. var faceSize = Math.pow(_this._size, 2) * 3;
  51415. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51416. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51417. startIndex += faceSize;
  51418. }
  51419. var results = [];
  51420. var byteArray = null;
  51421. // Push each faces.
  51422. for (var k = 0; k < 6; k++) {
  51423. var dataFace = null;
  51424. // If special cases.
  51425. if (!mipmapGenerator) {
  51426. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51427. dataFace = data[j];
  51428. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51429. // 3 channels of 1 bytes per pixel in bytes.
  51430. var byteBuffer = new ArrayBuffer(faceSize);
  51431. byteArray = new Uint8Array(byteBuffer);
  51432. }
  51433. for (var i = 0; i < _this._size * _this._size; i++) {
  51434. // Put in gamma space if requested.
  51435. if (_this._useInGammaSpace) {
  51436. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51437. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51438. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51439. }
  51440. // Convert to int texture for fallback.
  51441. if (byteArray) {
  51442. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51443. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51444. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51445. // May use luminance instead if the result is not accurate.
  51446. var max = Math.max(Math.max(r, g), b);
  51447. if (max > 255) {
  51448. var scale = 255 / max;
  51449. r *= scale;
  51450. g *= scale;
  51451. b *= scale;
  51452. }
  51453. byteArray[(i * 3) + 0] = r;
  51454. byteArray[(i * 3) + 1] = g;
  51455. byteArray[(i * 3) + 2] = b;
  51456. }
  51457. }
  51458. }
  51459. else {
  51460. dataFace = data[k];
  51461. }
  51462. // Fill the array accordingly.
  51463. if (byteArray) {
  51464. results.push(byteArray);
  51465. }
  51466. else {
  51467. results.push(dataFace);
  51468. }
  51469. }
  51470. return results;
  51471. };
  51472. 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);
  51473. };
  51474. /**
  51475. * Occurs when the file is raw .hdr file.
  51476. */
  51477. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51478. var _this = this;
  51479. var callback = function (buffer) {
  51480. // Extract the raw linear data.
  51481. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51482. // Generate harmonics if needed.
  51483. if (_this._generateHarmonics) {
  51484. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51485. }
  51486. var results = [];
  51487. var byteArray = null;
  51488. // Push each faces.
  51489. for (var j = 0; j < 6; j++) {
  51490. // Create uintarray fallback.
  51491. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51492. // 3 channels of 1 bytes per pixel in bytes.
  51493. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51494. byteArray = new Uint8Array(byteBuffer);
  51495. }
  51496. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51497. // If special cases.
  51498. if (_this._useInGammaSpace || byteArray) {
  51499. for (var i = 0; i < _this._size * _this._size; i++) {
  51500. // Put in gamma space if requested.
  51501. if (_this._useInGammaSpace) {
  51502. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51503. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51504. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51505. }
  51506. // Convert to int texture for fallback.
  51507. if (byteArray) {
  51508. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51509. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51510. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51511. // May use luminance instead if the result is not accurate.
  51512. var max = Math.max(Math.max(r, g), b);
  51513. if (max > 255) {
  51514. var scale = 255 / max;
  51515. r *= scale;
  51516. g *= scale;
  51517. b *= scale;
  51518. }
  51519. byteArray[(i * 3) + 0] = r;
  51520. byteArray[(i * 3) + 1] = g;
  51521. byteArray[(i * 3) + 2] = b;
  51522. }
  51523. }
  51524. }
  51525. if (byteArray) {
  51526. results.push(byteArray);
  51527. }
  51528. else {
  51529. results.push(dataFace);
  51530. }
  51531. }
  51532. return results;
  51533. };
  51534. var mipmapGenerator = null;
  51535. if (!this._noMipmap &&
  51536. this._usePMREMGenerator) {
  51537. mipmapGenerator = function (data) {
  51538. // Custom setup of the generator matching with the PBR shader values.
  51539. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51540. return generator.filterCubeMap();
  51541. };
  51542. }
  51543. 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);
  51544. };
  51545. /**
  51546. * Starts the loading process of the texture.
  51547. */
  51548. HDRCubeTexture.prototype.loadTexture = function () {
  51549. if (this._isBABYLONPreprocessed) {
  51550. this.loadBabylonTexture();
  51551. }
  51552. else {
  51553. this.loadHDRTexture();
  51554. }
  51555. };
  51556. HDRCubeTexture.prototype.clone = function () {
  51557. var size = this._isBABYLONPreprocessed ? null : this._size;
  51558. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51559. // Base texture
  51560. newTexture.level = this.level;
  51561. newTexture.wrapU = this.wrapU;
  51562. newTexture.wrapV = this.wrapV;
  51563. newTexture.coordinatesIndex = this.coordinatesIndex;
  51564. newTexture.coordinatesMode = this.coordinatesMode;
  51565. return newTexture;
  51566. };
  51567. // Methods
  51568. HDRCubeTexture.prototype.delayLoad = function () {
  51569. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51570. return;
  51571. }
  51572. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51573. this._texture = this._getFromCache(this.url, this._noMipmap);
  51574. if (!this._texture) {
  51575. this.loadTexture();
  51576. }
  51577. };
  51578. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51579. return this._textureMatrix;
  51580. };
  51581. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51582. var texture = null;
  51583. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51584. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51585. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  51586. texture.name = parsedTexture.name;
  51587. texture.hasAlpha = parsedTexture.hasAlpha;
  51588. texture.level = parsedTexture.level;
  51589. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51590. }
  51591. return texture;
  51592. };
  51593. HDRCubeTexture.prototype.serialize = function () {
  51594. if (!this.name) {
  51595. return null;
  51596. }
  51597. var serializationObject = {};
  51598. serializationObject.name = this.name;
  51599. serializationObject.hasAlpha = this.hasAlpha;
  51600. serializationObject.isCube = true;
  51601. serializationObject.level = this.level;
  51602. serializationObject.size = this._size;
  51603. serializationObject.coordinatesMode = this.coordinatesMode;
  51604. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51605. serializationObject.generateHarmonics = this._generateHarmonics;
  51606. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51607. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51608. serializationObject.customType = "BABYLON.HDRCubeTexture";
  51609. return serializationObject;
  51610. };
  51611. /**
  51612. * Saves as a file the data contained in the texture in a binary format.
  51613. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51614. * as the spherical used in the lighting.
  51615. * @param url The HDR file url.
  51616. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51617. * @param onError Method called if any error happens during download.
  51618. * @return The packed binary data.
  51619. */
  51620. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51621. if (onError === void 0) { onError = null; }
  51622. var callback = function (buffer) {
  51623. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51624. // Returns a URL you can use as a href.
  51625. var objUrl = window.URL.createObjectURL(data);
  51626. // Simulates a link to it and click to dowload.
  51627. var a = document.createElement("a");
  51628. document.body.appendChild(a);
  51629. a.style.display = "none";
  51630. a.href = objUrl;
  51631. a.download = "envmap.babylon.hdr";
  51632. a.click();
  51633. };
  51634. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51635. };
  51636. /**
  51637. * Serializes the data contained in the texture in a binary format.
  51638. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51639. * as the spherical used in the lighting.
  51640. * @param url The HDR file url.
  51641. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51642. * @param onError Method called if any error happens during download.
  51643. * @return The packed binary data.
  51644. */
  51645. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51646. if (onError === void 0) { onError = null; }
  51647. // Needs the url tho create the texture.
  51648. if (!url) {
  51649. return null;
  51650. }
  51651. // Check Power of two size.
  51652. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51653. return null;
  51654. }
  51655. var getDataCallback = function (dataBuffer) {
  51656. // Extract the raw linear data.
  51657. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51658. // Generate harmonics if needed.
  51659. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51660. // Generate seamless faces
  51661. var mipGeneratorArray = [];
  51662. // Data are known to be in +X +Y +Z -X -Y -Z
  51663. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51664. mipGeneratorArray.push(cubeData.right); // +X
  51665. mipGeneratorArray.push(cubeData.left); // -X
  51666. mipGeneratorArray.push(cubeData.up); // +Y
  51667. mipGeneratorArray.push(cubeData.down); // -Y
  51668. mipGeneratorArray.push(cubeData.front); // +Z
  51669. mipGeneratorArray.push(cubeData.back); // -Z
  51670. // Custom setup of the generator matching with the PBR shader values.
  51671. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51672. var mippedData = generator.filterCubeMap();
  51673. // Compute required byte length.
  51674. var byteLength = 1 * 4; // Raw Data Version int32.
  51675. byteLength += 4; // CubeMap max mip face size int32.
  51676. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  51677. // Add data size.
  51678. byteLength += 4; // Number of mip levels int32.
  51679. for (var level = 0; level < mippedData.length; level++) {
  51680. var mipSize = size >> level;
  51681. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  51682. }
  51683. // Prepare binary structure.
  51684. var buffer = new ArrayBuffer(byteLength);
  51685. var intArrayView = new Int32Array(buffer);
  51686. var floatArrayView = new Float32Array(buffer);
  51687. // Fill header.
  51688. intArrayView[0] = 1; // Version 1.
  51689. intArrayView[1] = size; // CubeMap max mip face size.
  51690. // Fill polynomial information.
  51691. sphericalPolynomial.x.toArray(floatArrayView, 2);
  51692. sphericalPolynomial.y.toArray(floatArrayView, 5);
  51693. sphericalPolynomial.z.toArray(floatArrayView, 8);
  51694. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  51695. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  51696. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  51697. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  51698. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  51699. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  51700. // Fill pixel data.
  51701. intArrayView[29] = mippedData.length; // Number of mip levels.
  51702. var startIndex = 30;
  51703. for (var level = 0; level < mippedData.length; level++) {
  51704. // Fill each pixel of the mip level.
  51705. var faceSize = Math.pow(size >> level, 2) * 3;
  51706. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51707. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  51708. startIndex += faceSize;
  51709. }
  51710. }
  51711. // Callback.
  51712. callback(buffer);
  51713. };
  51714. // Download and process.
  51715. BABYLON.Tools.LoadFile(url, function (data) {
  51716. getDataCallback(data);
  51717. }, null, null, true, onError);
  51718. };
  51719. HDRCubeTexture._facesMapping = [
  51720. "right",
  51721. "up",
  51722. "front",
  51723. "left",
  51724. "down",
  51725. "back"
  51726. ];
  51727. return HDRCubeTexture;
  51728. }(BABYLON.BaseTexture));
  51729. BABYLON.HDRCubeTexture = HDRCubeTexture;
  51730. })(BABYLON || (BABYLON = {}));
  51731. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  51732. var BABYLON;
  51733. (function (BABYLON) {
  51734. var Debug;
  51735. (function (Debug) {
  51736. /**
  51737. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  51738. */
  51739. var SkeletonViewer = (function () {
  51740. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  51741. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  51742. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  51743. this.skeleton = skeleton;
  51744. this.mesh = mesh;
  51745. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  51746. this.renderingGroupId = renderingGroupId;
  51747. this.color = BABYLON.Color3.White();
  51748. this._debugLines = [];
  51749. this._isEnabled = false;
  51750. this._scene = scene;
  51751. this.update();
  51752. this._renderFunction = this.update.bind(this);
  51753. }
  51754. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  51755. get: function () {
  51756. return this._isEnabled;
  51757. },
  51758. set: function (value) {
  51759. if (this._isEnabled === value) {
  51760. return;
  51761. }
  51762. this._isEnabled = value;
  51763. if (value) {
  51764. this._scene.registerBeforeRender(this._renderFunction);
  51765. }
  51766. else {
  51767. this._scene.unregisterBeforeRender(this._renderFunction);
  51768. }
  51769. },
  51770. enumerable: true,
  51771. configurable: true
  51772. });
  51773. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  51774. if (x === void 0) { x = 0; }
  51775. if (y === void 0) { y = 0; }
  51776. if (z === void 0) { z = 0; }
  51777. var tmat = BABYLON.Tmp.Matrix[0];
  51778. var parentBone = bone.getParent();
  51779. tmat.copyFrom(bone.getLocalMatrix());
  51780. if (x !== 0 || y !== 0 || z !== 0) {
  51781. var tmat2 = BABYLON.Tmp.Matrix[1];
  51782. BABYLON.Matrix.IdentityToRef(tmat2);
  51783. tmat2.m[12] = x;
  51784. tmat2.m[13] = y;
  51785. tmat2.m[14] = z;
  51786. tmat2.multiplyToRef(tmat, tmat);
  51787. }
  51788. if (parentBone) {
  51789. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  51790. }
  51791. tmat.multiplyToRef(meshMat, tmat);
  51792. position.x = tmat.m[12];
  51793. position.y = tmat.m[13];
  51794. position.z = tmat.m[14];
  51795. };
  51796. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  51797. var len = bones.length;
  51798. for (var i = 0; i < len; i++) {
  51799. var bone = bones[i];
  51800. var points = this._debugLines[i];
  51801. if (!points) {
  51802. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51803. this._debugLines[i] = points;
  51804. }
  51805. this._getBonePosition(points[0], bone, meshMat);
  51806. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  51807. }
  51808. };
  51809. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  51810. var len = bones.length;
  51811. var boneNum = 0;
  51812. for (var i = len - 1; i >= 0; i--) {
  51813. var childBone = bones[i];
  51814. var parentBone = childBone.getParent();
  51815. if (!parentBone) {
  51816. continue;
  51817. }
  51818. var points = this._debugLines[boneNum];
  51819. if (!points) {
  51820. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51821. this._debugLines[boneNum] = points;
  51822. }
  51823. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  51824. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  51825. boneNum++;
  51826. }
  51827. };
  51828. SkeletonViewer.prototype.update = function () {
  51829. if (this.autoUpdateBonesMatrices) {
  51830. this.skeleton.computeAbsoluteTransforms();
  51831. }
  51832. if (this.skeleton.bones[0].length === undefined) {
  51833. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  51834. }
  51835. else {
  51836. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  51837. }
  51838. if (!this._debugMesh) {
  51839. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  51840. this._debugMesh.renderingGroupId = this.renderingGroupId;
  51841. }
  51842. else {
  51843. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  51844. }
  51845. this._debugMesh.color = this.color;
  51846. };
  51847. SkeletonViewer.prototype.dispose = function () {
  51848. if (this._debugMesh) {
  51849. this.isEnabled = false;
  51850. this._debugMesh.dispose();
  51851. this._debugMesh = null;
  51852. }
  51853. };
  51854. return SkeletonViewer;
  51855. }());
  51856. Debug.SkeletonViewer = SkeletonViewer;
  51857. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  51858. })(BABYLON || (BABYLON = {}));
  51859. //# sourceMappingURL=babylon.skeletonViewer.js.map
  51860. var BABYLON;
  51861. (function (BABYLON) {
  51862. var Debug;
  51863. (function (Debug) {
  51864. var AxesViewer = (function () {
  51865. function AxesViewer(scene, scaleLines) {
  51866. if (scaleLines === void 0) { scaleLines = 1; }
  51867. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51868. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51869. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51870. this.scaleLines = 1;
  51871. this.scaleLines = scaleLines;
  51872. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  51873. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  51874. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  51875. this._xmesh.renderingGroupId = 2;
  51876. this._ymesh.renderingGroupId = 2;
  51877. this._zmesh.renderingGroupId = 2;
  51878. this._xmesh.material.checkReadyOnlyOnce = true;
  51879. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  51880. this._ymesh.material.checkReadyOnlyOnce = true;
  51881. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  51882. this._zmesh.material.checkReadyOnlyOnce = true;
  51883. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  51884. this.scene = scene;
  51885. }
  51886. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  51887. var scaleLines = this.scaleLines;
  51888. var point1 = this._xline[0];
  51889. var point2 = this._xline[1];
  51890. point1.x = position.x;
  51891. point1.y = position.y;
  51892. point1.z = position.z;
  51893. point2.x = point1.x + xaxis.x * scaleLines;
  51894. point2.y = point1.y + xaxis.y * scaleLines;
  51895. point2.z = point1.z + xaxis.z * scaleLines;
  51896. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  51897. point1 = this._yline[0];
  51898. point2 = this._yline[1];
  51899. point1.x = position.x;
  51900. point1.y = position.y;
  51901. point1.z = position.z;
  51902. point2.x = point1.x + yaxis.x * scaleLines;
  51903. point2.y = point1.y + yaxis.y * scaleLines;
  51904. point2.z = point1.z + yaxis.z * scaleLines;
  51905. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  51906. point1 = this._zline[0];
  51907. point2 = this._zline[1];
  51908. point1.x = position.x;
  51909. point1.y = position.y;
  51910. point1.z = position.z;
  51911. point2.x = point1.x + zaxis.x * scaleLines;
  51912. point2.y = point1.y + zaxis.y * scaleLines;
  51913. point2.z = point1.z + zaxis.z * scaleLines;
  51914. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  51915. };
  51916. AxesViewer.prototype.dispose = function () {
  51917. if (this._xmesh) {
  51918. this._xmesh.dispose();
  51919. this._ymesh.dispose();
  51920. this._zmesh.dispose();
  51921. this._xmesh = null;
  51922. this._ymesh = null;
  51923. this._zmesh = null;
  51924. this._xline = null;
  51925. this._yline = null;
  51926. this._zline = null;
  51927. this.scene = null;
  51928. }
  51929. };
  51930. return AxesViewer;
  51931. }());
  51932. Debug.AxesViewer = AxesViewer;
  51933. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  51934. })(BABYLON || (BABYLON = {}));
  51935. //# sourceMappingURL=babylon.axesViewer.js.map
  51936. var BABYLON;
  51937. (function (BABYLON) {
  51938. var Debug;
  51939. (function (Debug) {
  51940. var BoneAxesViewer = (function (_super) {
  51941. __extends(BoneAxesViewer, _super);
  51942. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  51943. if (scaleLines === void 0) { scaleLines = 1; }
  51944. _super.call(this, scene, scaleLines);
  51945. this.pos = BABYLON.Vector3.Zero();
  51946. this.xaxis = BABYLON.Vector3.Zero();
  51947. this.yaxis = BABYLON.Vector3.Zero();
  51948. this.zaxis = BABYLON.Vector3.Zero();
  51949. this.mesh = mesh;
  51950. this.bone = bone;
  51951. }
  51952. BoneAxesViewer.prototype.update = function () {
  51953. var bone = this.bone;
  51954. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  51955. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  51956. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  51957. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  51958. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  51959. };
  51960. BoneAxesViewer.prototype.dispose = function () {
  51961. if (this.pos) {
  51962. this.pos = null;
  51963. this.xaxis = null;
  51964. this.yaxis = null;
  51965. this.zaxis = null;
  51966. this.mesh = null;
  51967. this.bone = null;
  51968. _super.prototype.dispose.call(this);
  51969. }
  51970. };
  51971. return BoneAxesViewer;
  51972. }(Debug.AxesViewer));
  51973. Debug.BoneAxesViewer = BoneAxesViewer;
  51974. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  51975. })(BABYLON || (BABYLON = {}));
  51976. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  51977. var BABYLON;
  51978. (function (BABYLON) {
  51979. /**
  51980. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  51981. * It can help converting any input color in a desired output one. This can then be used to create effects
  51982. * from sepia, black and white to sixties or futuristic rendering...
  51983. *
  51984. * The only supported format is currently 3dl.
  51985. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  51986. */
  51987. var ColorGradingTexture = (function (_super) {
  51988. __extends(ColorGradingTexture, _super);
  51989. /**
  51990. * Instantiates a ColorGradingTexture from the following parameters.
  51991. *
  51992. * @param url The location of the color gradind data (currently only supporting 3dl)
  51993. * @param scene The scene the texture will be used in
  51994. */
  51995. function ColorGradingTexture(url, scene) {
  51996. _super.call(this, scene);
  51997. if (!url) {
  51998. return;
  51999. }
  52000. this._textureMatrix = BABYLON.Matrix.Identity();
  52001. this.name = url;
  52002. this.url = url;
  52003. this.hasAlpha = false;
  52004. this.isCube = false;
  52005. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52006. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52007. this.anisotropicFilteringLevel = 1;
  52008. this._texture = this._getFromCache(url, true);
  52009. if (!this._texture) {
  52010. if (!scene.useDelayedTextureLoading) {
  52011. this.loadTexture();
  52012. }
  52013. else {
  52014. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52015. }
  52016. }
  52017. }
  52018. /**
  52019. * Returns the texture matrix used in most of the material.
  52020. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52021. */
  52022. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52023. return this._textureMatrix;
  52024. };
  52025. /**
  52026. * Occurs when the file being loaded is a .3dl LUT file.
  52027. */
  52028. ColorGradingTexture.prototype.load3dlTexture = function () {
  52029. var _this = this;
  52030. var mipLevels = 0;
  52031. var floatArrayView = null;
  52032. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52033. this._texture = texture;
  52034. var callback = function (text) {
  52035. var data;
  52036. var tempData;
  52037. var line;
  52038. var lines = text.split('\n');
  52039. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52040. var maxColor = 0;
  52041. for (var i = 0; i < lines.length; i++) {
  52042. line = lines[i];
  52043. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52044. continue;
  52045. if (line.indexOf('#') === 0)
  52046. continue;
  52047. var words = line.split(" ");
  52048. if (size === 0) {
  52049. // Number of space + one
  52050. size = words.length;
  52051. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52052. tempData = new Float32Array(size * size * size * 4);
  52053. continue;
  52054. }
  52055. if (size != 0) {
  52056. var r = Math.max(parseInt(words[0]), 0);
  52057. var g = Math.max(parseInt(words[1]), 0);
  52058. var b = Math.max(parseInt(words[2]), 0);
  52059. maxColor = Math.max(r, maxColor);
  52060. maxColor = Math.max(g, maxColor);
  52061. maxColor = Math.max(b, maxColor);
  52062. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52063. tempData[pixelStorageIndex + 0] = r;
  52064. tempData[pixelStorageIndex + 1] = g;
  52065. tempData[pixelStorageIndex + 2] = b;
  52066. tempData[pixelStorageIndex + 3] = 0;
  52067. pixelIndexSlice++;
  52068. if (pixelIndexSlice % size == 0) {
  52069. pixelIndexH++;
  52070. pixelIndexSlice = 0;
  52071. if (pixelIndexH % size == 0) {
  52072. pixelIndexW++;
  52073. pixelIndexH = 0;
  52074. }
  52075. }
  52076. }
  52077. }
  52078. for (var i = 0; i < tempData.length; i++) {
  52079. var value = tempData[i];
  52080. data[i] = (value / maxColor * 255);
  52081. }
  52082. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52083. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52084. };
  52085. BABYLON.Tools.LoadFile(this.url, callback);
  52086. return this._texture;
  52087. };
  52088. /**
  52089. * Starts the loading process of the texture.
  52090. */
  52091. ColorGradingTexture.prototype.loadTexture = function () {
  52092. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52093. this.load3dlTexture();
  52094. }
  52095. };
  52096. /**
  52097. * Clones the color gradind texture.
  52098. */
  52099. ColorGradingTexture.prototype.clone = function () {
  52100. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52101. // Base texture
  52102. newTexture.level = this.level;
  52103. return newTexture;
  52104. };
  52105. /**
  52106. * Called during delayed load for textures.
  52107. */
  52108. ColorGradingTexture.prototype.delayLoad = function () {
  52109. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52110. return;
  52111. }
  52112. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52113. this._texture = this._getFromCache(this.url, true);
  52114. if (!this._texture) {
  52115. this.loadTexture();
  52116. }
  52117. };
  52118. /**
  52119. * Binds the color grading to the shader.
  52120. * @param colorGrading The texture to bind
  52121. * @param effect The effect to bind to
  52122. */
  52123. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52124. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52125. var x = colorGrading.level; // Texture Level
  52126. var y = colorGrading.getSize().height; // Texture Size example with 8
  52127. var z = y - 1.0; // SizeMinusOne 8 - 1
  52128. var w = 1 / y; // Space of 1 slice 1 / 8
  52129. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  52130. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  52131. 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
  52132. 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
  52133. 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
  52134. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  52135. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  52136. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  52137. };
  52138. /**
  52139. * Prepare the list of uniforms associated with the ColorGrading effects.
  52140. * @param uniformsList The list of uniforms used in the effect
  52141. * @param samplersList The list of samplers used in the effect
  52142. */
  52143. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  52144. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  52145. samplersList.push("cameraColorGrading2DSampler");
  52146. };
  52147. /**
  52148. * Parses a color grading texture serialized by Babylon.
  52149. * @param parsedTexture The texture information being parsedTexture
  52150. * @param scene The scene to load the texture in
  52151. * @param rootUrl The root url of the data assets to load
  52152. * @return A color gradind texture
  52153. */
  52154. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52155. var texture = null;
  52156. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52157. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  52158. texture.name = parsedTexture.name;
  52159. texture.level = parsedTexture.level;
  52160. }
  52161. return texture;
  52162. };
  52163. /**
  52164. * Serializes the LUT texture to json format.
  52165. */
  52166. ColorGradingTexture.prototype.serialize = function () {
  52167. if (!this.name) {
  52168. return null;
  52169. }
  52170. var serializationObject = {};
  52171. serializationObject.name = this.name;
  52172. serializationObject.level = this.level;
  52173. serializationObject.customType = "BABYLON.ColorGradingTexture";
  52174. return serializationObject;
  52175. };
  52176. /**
  52177. * Empty line regex stored for GC.
  52178. */
  52179. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  52180. return ColorGradingTexture;
  52181. }(BABYLON.BaseTexture));
  52182. BABYLON.ColorGradingTexture = ColorGradingTexture;
  52183. })(BABYLON || (BABYLON = {}));
  52184. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  52185. var BABYLON;
  52186. (function (BABYLON) {
  52187. /**
  52188. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52189. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52190. * 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;
  52191. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52192. */
  52193. var ColorCurves = (function () {
  52194. function ColorCurves() {
  52195. this._dirty = true;
  52196. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  52197. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  52198. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52199. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  52200. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52201. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  52202. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  52203. this._globalHue = 30;
  52204. this._globalDensity = 0;
  52205. this._globalSaturation = 0;
  52206. this._globalExposure = 0;
  52207. this._highlightsHue = 30;
  52208. this._highlightsDensity = 0;
  52209. this._highlightsSaturation = 0;
  52210. this._highlightsExposure = 0;
  52211. this._midtonesHue = 30;
  52212. this._midtonesDensity = 0;
  52213. this._midtonesSaturation = 0;
  52214. this._midtonesExposure = 0;
  52215. this._shadowsHue = 30;
  52216. this._shadowsDensity = 0;
  52217. this._shadowsSaturation = 0;
  52218. this._shadowsExposure = 0;
  52219. }
  52220. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  52221. /**
  52222. * Gets the global Hue value.
  52223. * 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).
  52224. */
  52225. get: function () {
  52226. return this._globalHue;
  52227. },
  52228. /**
  52229. * Sets the global Hue value.
  52230. * 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).
  52231. */
  52232. set: function (value) {
  52233. this._globalHue = value;
  52234. this._dirty = true;
  52235. },
  52236. enumerable: true,
  52237. configurable: true
  52238. });
  52239. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  52240. /**
  52241. * Gets the global Density value.
  52242. * 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.
  52243. * Values less than zero provide a filter of opposite hue.
  52244. */
  52245. get: function () {
  52246. return this._globalDensity;
  52247. },
  52248. /**
  52249. * Sets the global Density value.
  52250. * 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.
  52251. * Values less than zero provide a filter of opposite hue.
  52252. */
  52253. set: function (value) {
  52254. this._globalDensity = value;
  52255. this._dirty = true;
  52256. },
  52257. enumerable: true,
  52258. configurable: true
  52259. });
  52260. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  52261. /**
  52262. * Gets the global Saturation value.
  52263. * 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.
  52264. */
  52265. get: function () {
  52266. return this._globalSaturation;
  52267. },
  52268. /**
  52269. * Sets the global Saturation value.
  52270. * 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.
  52271. */
  52272. set: function (value) {
  52273. this._globalSaturation = value;
  52274. this._dirty = true;
  52275. },
  52276. enumerable: true,
  52277. configurable: true
  52278. });
  52279. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  52280. /**
  52281. * Gets the highlights Hue value.
  52282. * 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).
  52283. */
  52284. get: function () {
  52285. return this._highlightsHue;
  52286. },
  52287. /**
  52288. * Sets the highlights Hue value.
  52289. * 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).
  52290. */
  52291. set: function (value) {
  52292. this._highlightsHue = value;
  52293. this._dirty = true;
  52294. },
  52295. enumerable: true,
  52296. configurable: true
  52297. });
  52298. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  52299. /**
  52300. * Gets the highlights Density value.
  52301. * 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.
  52302. * Values less than zero provide a filter of opposite hue.
  52303. */
  52304. get: function () {
  52305. return this._highlightsDensity;
  52306. },
  52307. /**
  52308. * Sets the highlights Density value.
  52309. * 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.
  52310. * Values less than zero provide a filter of opposite hue.
  52311. */
  52312. set: function (value) {
  52313. this._highlightsDensity = value;
  52314. this._dirty = true;
  52315. },
  52316. enumerable: true,
  52317. configurable: true
  52318. });
  52319. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  52320. /**
  52321. * Gets the highlights Saturation value.
  52322. * 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.
  52323. */
  52324. get: function () {
  52325. return this._highlightsSaturation;
  52326. },
  52327. /**
  52328. * Sets the highlights Saturation value.
  52329. * 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.
  52330. */
  52331. set: function (value) {
  52332. this._highlightsSaturation = value;
  52333. this._dirty = true;
  52334. },
  52335. enumerable: true,
  52336. configurable: true
  52337. });
  52338. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  52339. /**
  52340. * Gets the highlights Exposure value.
  52341. * 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.
  52342. */
  52343. get: function () {
  52344. return this._highlightsExposure;
  52345. },
  52346. /**
  52347. * Sets the highlights Exposure value.
  52348. * 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.
  52349. */
  52350. set: function (value) {
  52351. this._highlightsExposure = value;
  52352. this._dirty = true;
  52353. },
  52354. enumerable: true,
  52355. configurable: true
  52356. });
  52357. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  52358. /**
  52359. * Gets the midtones Hue value.
  52360. * 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).
  52361. */
  52362. get: function () {
  52363. return this._midtonesHue;
  52364. },
  52365. /**
  52366. * Sets the midtones Hue value.
  52367. * 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).
  52368. */
  52369. set: function (value) {
  52370. this._midtonesHue = value;
  52371. this._dirty = true;
  52372. },
  52373. enumerable: true,
  52374. configurable: true
  52375. });
  52376. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  52377. /**
  52378. * Gets the midtones Density value.
  52379. * 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.
  52380. * Values less than zero provide a filter of opposite hue.
  52381. */
  52382. get: function () {
  52383. return this._midtonesDensity;
  52384. },
  52385. /**
  52386. * Sets the midtones Density value.
  52387. * 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.
  52388. * Values less than zero provide a filter of opposite hue.
  52389. */
  52390. set: function (value) {
  52391. this._midtonesDensity = value;
  52392. this._dirty = true;
  52393. },
  52394. enumerable: true,
  52395. configurable: true
  52396. });
  52397. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  52398. /**
  52399. * Gets the midtones Saturation value.
  52400. * 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.
  52401. */
  52402. get: function () {
  52403. return this._midtonesSaturation;
  52404. },
  52405. /**
  52406. * Sets the midtones Saturation value.
  52407. * 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.
  52408. */
  52409. set: function (value) {
  52410. this._midtonesSaturation = value;
  52411. this._dirty = true;
  52412. },
  52413. enumerable: true,
  52414. configurable: true
  52415. });
  52416. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  52417. /**
  52418. * Gets the midtones Exposure value.
  52419. * 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.
  52420. */
  52421. get: function () {
  52422. return this._midtonesExposure;
  52423. },
  52424. /**
  52425. * Sets the midtones Exposure value.
  52426. * 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.
  52427. */
  52428. set: function (value) {
  52429. this._midtonesExposure = value;
  52430. this._dirty = true;
  52431. },
  52432. enumerable: true,
  52433. configurable: true
  52434. });
  52435. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  52436. /**
  52437. * Gets the shadows Hue value.
  52438. * 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).
  52439. */
  52440. get: function () {
  52441. return this._shadowsHue;
  52442. },
  52443. /**
  52444. * Sets the shadows Hue value.
  52445. * 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).
  52446. */
  52447. set: function (value) {
  52448. this._shadowsHue = value;
  52449. this._dirty = true;
  52450. },
  52451. enumerable: true,
  52452. configurable: true
  52453. });
  52454. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  52455. /**
  52456. * Gets the shadows Density value.
  52457. * 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.
  52458. * Values less than zero provide a filter of opposite hue.
  52459. */
  52460. get: function () {
  52461. return this._shadowsDensity;
  52462. },
  52463. /**
  52464. * Sets the shadows Density value.
  52465. * 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.
  52466. * Values less than zero provide a filter of opposite hue.
  52467. */
  52468. set: function (value) {
  52469. this._shadowsDensity = value;
  52470. this._dirty = true;
  52471. },
  52472. enumerable: true,
  52473. configurable: true
  52474. });
  52475. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  52476. /**
  52477. * Gets the shadows Saturation value.
  52478. * 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.
  52479. */
  52480. get: function () {
  52481. return this._shadowsSaturation;
  52482. },
  52483. /**
  52484. * Sets the shadows Saturation value.
  52485. * 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.
  52486. */
  52487. set: function (value) {
  52488. this._shadowsSaturation = value;
  52489. this._dirty = true;
  52490. },
  52491. enumerable: true,
  52492. configurable: true
  52493. });
  52494. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  52495. /**
  52496. * Gets the shadows Exposure value.
  52497. * 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.
  52498. */
  52499. get: function () {
  52500. return this._shadowsExposure;
  52501. },
  52502. /**
  52503. * Sets the shadows Exposure value.
  52504. * 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.
  52505. */
  52506. set: function (value) {
  52507. this._shadowsExposure = value;
  52508. this._dirty = true;
  52509. },
  52510. enumerable: true,
  52511. configurable: true
  52512. });
  52513. /**
  52514. * Binds the color curves to the shader.
  52515. * @param colorCurves The color curve to bind
  52516. * @param effect The effect to bind to
  52517. */
  52518. ColorCurves.Bind = function (colorCurves, effect) {
  52519. if (colorCurves._dirty) {
  52520. colorCurves._dirty = false;
  52521. // Fill in global info.
  52522. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  52523. // Compute highlights info.
  52524. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  52525. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  52526. // Compute midtones info.
  52527. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  52528. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  52529. // Compute shadows info.
  52530. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  52531. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  52532. // Compute deltas (neutral is midtones).
  52533. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  52534. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  52535. }
  52536. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  52537. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  52538. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  52539. };
  52540. /**
  52541. * Prepare the list of uniforms associated with the ColorCurves effects.
  52542. * @param uniformsList The list of uniforms used in the effect
  52543. */
  52544. ColorCurves.PrepareUniforms = function (uniformsList) {
  52545. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  52546. };
  52547. /**
  52548. * Returns color grading data based on a hue, density, saturation and exposure value.
  52549. * @param filterHue The hue of the color filter.
  52550. * @param filterDensity The density of the color filter.
  52551. * @param saturation The saturation.
  52552. * @param exposure The exposure.
  52553. * @param result The result data container.
  52554. */
  52555. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  52556. if (hue == null) {
  52557. return;
  52558. }
  52559. hue = ColorCurves.clamp(hue, 0, 360);
  52560. density = ColorCurves.clamp(density, -100, 100);
  52561. saturation = ColorCurves.clamp(saturation, -100, 100);
  52562. exposure = ColorCurves.clamp(exposure, -100, 100);
  52563. // Remap the slider/config filter density with non-linear mapping and also scale by half
  52564. // so that the maximum filter density is only 50% control. This provides fine control
  52565. // for small values and reasonable range.
  52566. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  52567. density *= 0.5;
  52568. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  52569. if (density < 0) {
  52570. density *= -1;
  52571. hue = (hue + 180) % 360;
  52572. }
  52573. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  52574. result.scaleToRef(2, result);
  52575. result.a = 1 + 0.01 * saturation;
  52576. };
  52577. /**
  52578. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  52579. * @param value The input slider value in range [-100,100].
  52580. * @returns Adjusted value.
  52581. */
  52582. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  52583. value /= 100;
  52584. var x = Math.abs(value);
  52585. x = Math.pow(x, 2);
  52586. if (value < 0) {
  52587. x *= -1;
  52588. }
  52589. x *= 100;
  52590. return x;
  52591. };
  52592. /**
  52593. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  52594. * @param hue The hue (H) input.
  52595. * @param saturation The saturation (S) input.
  52596. * @param brightness The brightness (B) input.
  52597. * @result An RGBA color represented as Vector4.
  52598. */
  52599. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  52600. var h = ColorCurves.clamp(hue, 0, 360);
  52601. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  52602. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  52603. if (s === 0) {
  52604. result.r = v;
  52605. result.g = v;
  52606. result.b = v;
  52607. }
  52608. else {
  52609. // sector 0 to 5
  52610. h /= 60;
  52611. var i = Math.floor(h);
  52612. // fractional part of h
  52613. var f = h - i;
  52614. var p = v * (1 - s);
  52615. var q = v * (1 - s * f);
  52616. var t = v * (1 - s * (1 - f));
  52617. switch (i) {
  52618. case 0:
  52619. result.r = v;
  52620. result.g = t;
  52621. result.b = p;
  52622. break;
  52623. case 1:
  52624. result.r = q;
  52625. result.g = v;
  52626. result.b = p;
  52627. break;
  52628. case 2:
  52629. result.r = p;
  52630. result.g = v;
  52631. result.b = t;
  52632. break;
  52633. case 3:
  52634. result.r = p;
  52635. result.g = q;
  52636. result.b = v;
  52637. break;
  52638. case 4:
  52639. result.r = t;
  52640. result.g = p;
  52641. result.b = v;
  52642. break;
  52643. default:
  52644. result.r = v;
  52645. result.g = p;
  52646. result.b = q;
  52647. break;
  52648. }
  52649. }
  52650. result.a = 1;
  52651. };
  52652. /**
  52653. * Returns a value clamped between min and max
  52654. * @param value The value to clamp
  52655. * @param min The minimum of value
  52656. * @param max The maximum of value
  52657. * @returns The clamped value.
  52658. */
  52659. ColorCurves.clamp = function (value, min, max) {
  52660. return Math.min(Math.max(value, min), max);
  52661. };
  52662. /**
  52663. * Clones the current color curve instance.
  52664. * @return The cloned curves
  52665. */
  52666. ColorCurves.prototype.clone = function () {
  52667. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  52668. };
  52669. /**
  52670. * Serializes the current color curve instance to a json representation.
  52671. * @return a JSON representation
  52672. */
  52673. ColorCurves.prototype.serialize = function () {
  52674. return BABYLON.SerializationHelper.Serialize(this);
  52675. };
  52676. /**
  52677. * Parses the color curve from a json representation.
  52678. * @param source the JSON source to parse
  52679. * @return The parsed curves
  52680. */
  52681. ColorCurves.Parse = function (source) {
  52682. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  52683. };
  52684. __decorate([
  52685. BABYLON.serialize()
  52686. ], ColorCurves.prototype, "_globalHue", void 0);
  52687. __decorate([
  52688. BABYLON.serialize()
  52689. ], ColorCurves.prototype, "_globalDensity", void 0);
  52690. __decorate([
  52691. BABYLON.serialize()
  52692. ], ColorCurves.prototype, "_globalSaturation", void 0);
  52693. __decorate([
  52694. BABYLON.serialize()
  52695. ], ColorCurves.prototype, "_globalExposure", void 0);
  52696. __decorate([
  52697. BABYLON.serialize()
  52698. ], ColorCurves.prototype, "_highlightsHue", void 0);
  52699. __decorate([
  52700. BABYLON.serialize()
  52701. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  52702. __decorate([
  52703. BABYLON.serialize()
  52704. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  52705. __decorate([
  52706. BABYLON.serialize()
  52707. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  52708. __decorate([
  52709. BABYLON.serialize()
  52710. ], ColorCurves.prototype, "_midtonesHue", void 0);
  52711. __decorate([
  52712. BABYLON.serialize()
  52713. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  52714. __decorate([
  52715. BABYLON.serialize()
  52716. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  52717. __decorate([
  52718. BABYLON.serialize()
  52719. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  52720. return ColorCurves;
  52721. }());
  52722. BABYLON.ColorCurves = ColorCurves;
  52723. })(BABYLON || (BABYLON = {}));
  52724. //# sourceMappingURL=babylon.colorCurves.js.map
  52725. var BABYLON;
  52726. (function (BABYLON) {
  52727. var PBRMaterialDefines = (function (_super) {
  52728. __extends(PBRMaterialDefines, _super);
  52729. function PBRMaterialDefines() {
  52730. _super.call(this);
  52731. this.ALBEDO = false;
  52732. this.AMBIENT = false;
  52733. this.OPACITY = false;
  52734. this.OPACITYRGB = false;
  52735. this.REFLECTION = false;
  52736. this.EMISSIVE = false;
  52737. this.REFLECTIVITY = false;
  52738. this.BUMP = false;
  52739. this.PARALLAX = false;
  52740. this.PARALLAXOCCLUSION = false;
  52741. this.SPECULAROVERALPHA = false;
  52742. this.CLIPPLANE = false;
  52743. this.ALPHATEST = false;
  52744. this.ALPHAFROMALBEDO = false;
  52745. this.POINTSIZE = false;
  52746. this.FOG = false;
  52747. this.SPECULARTERM = false;
  52748. this.OPACITYFRESNEL = false;
  52749. this.EMISSIVEFRESNEL = false;
  52750. this.FRESNEL = false;
  52751. this.NORMAL = false;
  52752. this.UV1 = false;
  52753. this.UV2 = false;
  52754. this.VERTEXCOLOR = false;
  52755. this.VERTEXALPHA = false;
  52756. this.NUM_BONE_INFLUENCERS = 0;
  52757. this.BonesPerMesh = 0;
  52758. this.INSTANCES = false;
  52759. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  52760. this.MICROSURFACEAUTOMATIC = false;
  52761. this.EMISSIVEASILLUMINATION = false;
  52762. this.LINKEMISSIVEWITHALBEDO = false;
  52763. this.LIGHTMAP = false;
  52764. this.USELIGHTMAPASSHADOWMAP = false;
  52765. this.REFLECTIONMAP_3D = false;
  52766. this.REFLECTIONMAP_SPHERICAL = false;
  52767. this.REFLECTIONMAP_PLANAR = false;
  52768. this.REFLECTIONMAP_CUBIC = false;
  52769. this.REFLECTIONMAP_PROJECTION = false;
  52770. this.REFLECTIONMAP_SKYBOX = false;
  52771. this.REFLECTIONMAP_EXPLICIT = false;
  52772. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  52773. this.INVERTCUBICMAP = false;
  52774. this.LOGARITHMICDEPTH = false;
  52775. this.CAMERATONEMAP = false;
  52776. this.CAMERACONTRAST = false;
  52777. this.CAMERACOLORGRADING = false;
  52778. this.CAMERACOLORCURVES = false;
  52779. this.OVERLOADEDVALUES = false;
  52780. this.OVERLOADEDSHADOWVALUES = false;
  52781. this.USESPHERICALFROMREFLECTIONMAP = false;
  52782. this.REFRACTION = false;
  52783. this.REFRACTIONMAP_3D = false;
  52784. this.LINKREFRACTIONTOTRANSPARENCY = false;
  52785. this.REFRACTIONMAPINLINEARSPACE = false;
  52786. this.LODBASEDMICROSFURACE = false;
  52787. this.USEPHYSICALLIGHTFALLOFF = false;
  52788. this.RADIANCEOVERALPHA = false;
  52789. this.USEPMREMREFLECTION = false;
  52790. this.USEPMREMREFRACTION = false;
  52791. this.OPENGLNORMALMAP = false;
  52792. this.INVERTNORMALMAPX = false;
  52793. this.INVERTNORMALMAPY = false;
  52794. this.SHADOWFULLFLOAT = false;
  52795. this.METALLICWORKFLOW = false;
  52796. this.METALLICROUGHNESSGSTOREINALPHA = false;
  52797. this.METALLICROUGHNESSGSTOREINGREEN = false;
  52798. this.rebuild();
  52799. }
  52800. return PBRMaterialDefines;
  52801. }(BABYLON.MaterialDefines));
  52802. /**
  52803. * The Physically based material of BJS.
  52804. *
  52805. * This offers the main features of a standard PBR material.
  52806. * For more information, please refer to the documentation :
  52807. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  52808. */
  52809. var PBRMaterial = (function (_super) {
  52810. __extends(PBRMaterial, _super);
  52811. /**
  52812. * Instantiates a new PBRMaterial instance.
  52813. *
  52814. * @param name The material name
  52815. * @param scene The scene the material will be use in.
  52816. */
  52817. function PBRMaterial(name, scene) {
  52818. var _this = this;
  52819. _super.call(this, name, scene);
  52820. /**
  52821. * Intensity of the direct lights e.g. the four lights available in your scene.
  52822. * This impacts both the direct diffuse and specular highlights.
  52823. */
  52824. this.directIntensity = 1.0;
  52825. /**
  52826. * Intensity of the emissive part of the material.
  52827. * This helps controlling the emissive effect without modifying the emissive color.
  52828. */
  52829. this.emissiveIntensity = 1.0;
  52830. /**
  52831. * Intensity of the environment e.g. how much the environment will light the object
  52832. * either through harmonics for rough material or through the refelction for shiny ones.
  52833. */
  52834. this.environmentIntensity = 1.0;
  52835. /**
  52836. * This is a special control allowing the reduction of the specular highlights coming from the
  52837. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  52838. */
  52839. this.specularIntensity = 1.0;
  52840. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  52841. /**
  52842. * Debug Control allowing disabling the bump map on this material.
  52843. */
  52844. this.disableBumpMap = false;
  52845. /**
  52846. * Debug Control helping enforcing or dropping the darkness of shadows.
  52847. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  52848. */
  52849. this.overloadedShadowIntensity = 1.0;
  52850. /**
  52851. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  52852. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  52853. */
  52854. this.overloadedShadeIntensity = 1.0;
  52855. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  52856. /**
  52857. * The camera exposure used on this material.
  52858. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  52859. * This corresponds to a photographic exposure.
  52860. */
  52861. this.cameraExposure = 1.0;
  52862. /**
  52863. * The camera contrast used on this material.
  52864. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  52865. */
  52866. this.cameraContrast = 1.0;
  52867. /**
  52868. * Color Grading 2D Lookup Texture.
  52869. * This allows special effects like sepia, black and white to sixties rendering style.
  52870. */
  52871. this.cameraColorGradingTexture = null;
  52872. /**
  52873. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52874. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52875. * 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;
  52876. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52877. */
  52878. this.cameraColorCurves = null;
  52879. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  52880. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  52881. /**
  52882. * Debug Control allowing to overload the ambient color.
  52883. * This as to be use with the overloadedAmbientIntensity parameter.
  52884. */
  52885. this.overloadedAmbient = BABYLON.Color3.White();
  52886. /**
  52887. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  52888. */
  52889. this.overloadedAmbientIntensity = 0.0;
  52890. /**
  52891. * Debug Control allowing to overload the albedo color.
  52892. * This as to be use with the overloadedAlbedoIntensity parameter.
  52893. */
  52894. this.overloadedAlbedo = BABYLON.Color3.White();
  52895. /**
  52896. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  52897. */
  52898. this.overloadedAlbedoIntensity = 0.0;
  52899. /**
  52900. * Debug Control allowing to overload the reflectivity color.
  52901. * This as to be use with the overloadedReflectivityIntensity parameter.
  52902. */
  52903. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  52904. /**
  52905. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  52906. */
  52907. this.overloadedReflectivityIntensity = 0.0;
  52908. /**
  52909. * Debug Control allowing to overload the emissive color.
  52910. * This as to be use with the overloadedEmissiveIntensity parameter.
  52911. */
  52912. this.overloadedEmissive = BABYLON.Color3.White();
  52913. /**
  52914. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  52915. */
  52916. this.overloadedEmissiveIntensity = 0.0;
  52917. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  52918. /**
  52919. * Debug Control allowing to overload the reflection color.
  52920. * This as to be use with the overloadedReflectionIntensity parameter.
  52921. */
  52922. this.overloadedReflection = BABYLON.Color3.White();
  52923. /**
  52924. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  52925. */
  52926. this.overloadedReflectionIntensity = 0.0;
  52927. /**
  52928. * Debug Control allowing to overload the microsurface.
  52929. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  52930. */
  52931. this.overloadedMicroSurface = 0.0;
  52932. /**
  52933. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  52934. */
  52935. this.overloadedMicroSurfaceIntensity = 0.0;
  52936. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  52937. /**
  52938. * AKA Occlusion Texture Intensity in other nomenclature.
  52939. */
  52940. this.ambientTextureStrength = 1.0;
  52941. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  52942. /**
  52943. * AKA Diffuse Color in other nomenclature.
  52944. */
  52945. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  52946. /**
  52947. * AKA Specular Color in other nomenclature.
  52948. */
  52949. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  52950. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  52951. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  52952. /**
  52953. * AKA Glossiness in other nomenclature.
  52954. */
  52955. this.microSurface = 0.9;
  52956. /**
  52957. * source material index of refraction (IOR)' / 'destination material IOR.
  52958. */
  52959. this.indexOfRefraction = 0.66;
  52960. /**
  52961. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  52962. */
  52963. this.invertRefractionY = false;
  52964. /**
  52965. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  52966. * Materials half opaque for instance using refraction could benefit from this control.
  52967. */
  52968. this.linkRefractionWithTransparency = false;
  52969. /**
  52970. * The emissive and albedo are linked to never be more than one (Energy conservation).
  52971. */
  52972. this.linkEmissiveWithAlbedo = false;
  52973. this.useLightmapAsShadowmap = false;
  52974. /**
  52975. * In this mode, the emissive informtaion will always be added to the lighting once.
  52976. * A light for instance can be thought as emissive.
  52977. */
  52978. this.useEmissiveAsIllumination = false;
  52979. /**
  52980. * Secifies that the alpha is coming form the albedo channel alpha channel.
  52981. */
  52982. this.useAlphaFromAlbedoTexture = false;
  52983. /**
  52984. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  52985. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  52986. */
  52987. this.useSpecularOverAlpha = true;
  52988. /**
  52989. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  52990. */
  52991. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  52992. /**
  52993. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  52994. */
  52995. this.useRoughnessFromMetallicTextureAlpha = true;
  52996. /**
  52997. * Specifies if the metallic texture contains the roughness information in its green channel.
  52998. */
  52999. this.useRoughnessFromMetallicTextureGreen = false;
  53000. /**
  53001. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53002. * The material will try to infer what glossiness each pixel should be.
  53003. */
  53004. this.useAutoMicroSurfaceFromReflectivityMap = false;
  53005. /**
  53006. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53007. * the creation of the material.
  53008. */
  53009. this.useScalarInLinearSpace = false;
  53010. /**
  53011. * BJS is using an harcoded light falloff based on a manually sets up range.
  53012. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53013. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53014. */
  53015. this.usePhysicalLightFalloff = true;
  53016. /**
  53017. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53018. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53019. */
  53020. this.useRadianceOverAlpha = true;
  53021. /**
  53022. * Allows using the bump map in parallax mode.
  53023. */
  53024. this.useParallax = false;
  53025. /**
  53026. * Allows using the bump map in parallax occlusion mode.
  53027. */
  53028. this.useParallaxOcclusion = false;
  53029. /**
  53030. * Controls the scale bias of the parallax mode.
  53031. */
  53032. this.parallaxScaleBias = 0.05;
  53033. /**
  53034. * If sets to true, disables all the lights affecting the material.
  53035. */
  53036. this.disableLighting = false;
  53037. /**
  53038. * Number of Simultaneous lights allowed on the material.
  53039. */
  53040. this.maxSimultaneousLights = 4;
  53041. /**
  53042. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53043. */
  53044. this.invertNormalMapX = false;
  53045. /**
  53046. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53047. */
  53048. this.invertNormalMapY = false;
  53049. this._renderTargets = new BABYLON.SmartArray(16);
  53050. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53051. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53052. this._tempColor = new BABYLON.Color3();
  53053. this._defines = new PBRMaterialDefines();
  53054. this._cachedDefines = new PBRMaterialDefines();
  53055. this._myScene = null;
  53056. this._myShadowGenerator = null;
  53057. this._cachedDefines.BonesPerMesh = -1;
  53058. this.getRenderTargetTextures = function () {
  53059. _this._renderTargets.reset();
  53060. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53061. _this._renderTargets.push(_this.reflectionTexture);
  53062. }
  53063. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53064. _this._renderTargets.push(_this.refractionTexture);
  53065. }
  53066. return _this._renderTargets;
  53067. };
  53068. }
  53069. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53070. get: function () {
  53071. return this._useLogarithmicDepth;
  53072. },
  53073. set: function (value) {
  53074. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53075. },
  53076. enumerable: true,
  53077. configurable: true
  53078. });
  53079. PBRMaterial.prototype.needAlphaBlending = function () {
  53080. if (this.linkRefractionWithTransparency) {
  53081. return false;
  53082. }
  53083. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53084. };
  53085. PBRMaterial.prototype.needAlphaTesting = function () {
  53086. if (this.linkRefractionWithTransparency) {
  53087. return false;
  53088. }
  53089. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53090. };
  53091. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53092. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53093. };
  53094. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53095. return this.albedoTexture;
  53096. };
  53097. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53098. if (!mesh) {
  53099. return true;
  53100. }
  53101. if (this._defines.INSTANCES !== useInstances) {
  53102. return false;
  53103. }
  53104. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53105. return true;
  53106. }
  53107. return false;
  53108. };
  53109. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53110. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53111. };
  53112. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53113. if (!useScalarInLinear) {
  53114. color.toLinearSpaceToRef(ref);
  53115. }
  53116. else {
  53117. ref.r = color.r;
  53118. ref.g = color.g;
  53119. ref.b = color.b;
  53120. }
  53121. };
  53122. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53123. var lightIndex = 0;
  53124. var depthValuesAlreadySet = false;
  53125. for (var index = 0; index < scene.lights.length; index++) {
  53126. var light = scene.lights[index];
  53127. if (!light.isEnabled()) {
  53128. continue;
  53129. }
  53130. if (!light.canAffectMesh(mesh)) {
  53131. continue;
  53132. }
  53133. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  53134. // GAMMA CORRECTION.
  53135. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  53136. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  53137. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  53138. if (defines["SPECULARTERM"]) {
  53139. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  53140. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  53141. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  53142. }
  53143. // Shadows
  53144. if (scene.shadowsEnabled) {
  53145. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  53146. }
  53147. lightIndex++;
  53148. if (lightIndex === maxSimultaneousLights)
  53149. break;
  53150. }
  53151. };
  53152. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  53153. if (this.checkReadyOnlyOnce) {
  53154. if (this._wasPreviouslyReady) {
  53155. return true;
  53156. }
  53157. }
  53158. var scene = this.getScene();
  53159. var engine = scene.getEngine();
  53160. var needNormals = false;
  53161. var needUVs = false;
  53162. this._defines.reset();
  53163. if (scene.lightsEnabled && !this.disableLighting) {
  53164. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  53165. }
  53166. if (!this.checkReadyOnEveryCall) {
  53167. if (this._renderId === scene.getRenderId()) {
  53168. if (this._checkCache(scene, mesh, useInstances)) {
  53169. return true;
  53170. }
  53171. }
  53172. }
  53173. if (scene.texturesEnabled) {
  53174. if (scene.getEngine().getCaps().textureLOD) {
  53175. this._defines.LODBASEDMICROSFURACE = true;
  53176. }
  53177. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53178. if (!this.albedoTexture.isReady()) {
  53179. return false;
  53180. }
  53181. else {
  53182. needUVs = true;
  53183. this._defines.ALBEDO = true;
  53184. }
  53185. }
  53186. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53187. if (!this.ambientTexture.isReady()) {
  53188. return false;
  53189. }
  53190. else {
  53191. needUVs = true;
  53192. this._defines.AMBIENT = true;
  53193. }
  53194. }
  53195. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53196. if (!this.opacityTexture.isReady()) {
  53197. return false;
  53198. }
  53199. else {
  53200. needUVs = true;
  53201. this._defines.OPACITY = true;
  53202. if (this.opacityTexture.getAlphaFromRGB) {
  53203. this._defines.OPACITYRGB = true;
  53204. }
  53205. }
  53206. }
  53207. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53208. if (!this.reflectionTexture.isReady()) {
  53209. return false;
  53210. }
  53211. else {
  53212. needNormals = true;
  53213. this._defines.REFLECTION = true;
  53214. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  53215. this._defines.INVERTCUBICMAP = true;
  53216. }
  53217. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  53218. switch (this.reflectionTexture.coordinatesMode) {
  53219. case BABYLON.Texture.CUBIC_MODE:
  53220. case BABYLON.Texture.INVCUBIC_MODE:
  53221. this._defines.REFLECTIONMAP_CUBIC = true;
  53222. break;
  53223. case BABYLON.Texture.EXPLICIT_MODE:
  53224. this._defines.REFLECTIONMAP_EXPLICIT = true;
  53225. break;
  53226. case BABYLON.Texture.PLANAR_MODE:
  53227. this._defines.REFLECTIONMAP_PLANAR = true;
  53228. break;
  53229. case BABYLON.Texture.PROJECTION_MODE:
  53230. this._defines.REFLECTIONMAP_PROJECTION = true;
  53231. break;
  53232. case BABYLON.Texture.SKYBOX_MODE:
  53233. this._defines.REFLECTIONMAP_SKYBOX = true;
  53234. break;
  53235. case BABYLON.Texture.SPHERICAL_MODE:
  53236. this._defines.REFLECTIONMAP_SPHERICAL = true;
  53237. break;
  53238. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  53239. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  53240. break;
  53241. }
  53242. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  53243. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  53244. needNormals = true;
  53245. if (this.reflectionTexture.isPMREM) {
  53246. this._defines.USEPMREMREFLECTION = true;
  53247. }
  53248. }
  53249. }
  53250. }
  53251. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53252. if (!this.lightmapTexture.isReady()) {
  53253. return false;
  53254. }
  53255. else {
  53256. needUVs = true;
  53257. this._defines.LIGHTMAP = true;
  53258. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  53259. }
  53260. }
  53261. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53262. if (!this.emissiveTexture.isReady()) {
  53263. return false;
  53264. }
  53265. else {
  53266. needUVs = true;
  53267. this._defines.EMISSIVE = true;
  53268. }
  53269. }
  53270. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53271. if (this.metallicTexture) {
  53272. if (!this.metallicTexture.isReady()) {
  53273. return false;
  53274. }
  53275. else {
  53276. needUVs = true;
  53277. this._defines.METALLICWORKFLOW = true;
  53278. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  53279. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  53280. }
  53281. }
  53282. else if (this.reflectivityTexture) {
  53283. if (!this.reflectivityTexture.isReady()) {
  53284. return false;
  53285. }
  53286. else {
  53287. needUVs = true;
  53288. this._defines.REFLECTIVITY = true;
  53289. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  53290. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  53291. }
  53292. }
  53293. }
  53294. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53295. if (!this.bumpTexture.isReady()) {
  53296. return false;
  53297. }
  53298. else {
  53299. needUVs = true;
  53300. this._defines.BUMP = true;
  53301. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53302. this._defines.PARALLAX = true;
  53303. if (this.useParallaxOcclusion) {
  53304. this._defines.PARALLAXOCCLUSION = true;
  53305. }
  53306. }
  53307. if (this.invertNormalMapX) {
  53308. this._defines.INVERTNORMALMAPX = true;
  53309. }
  53310. if (this.invertNormalMapY) {
  53311. this._defines.INVERTNORMALMAPY = true;
  53312. }
  53313. }
  53314. }
  53315. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53316. if (!this.refractionTexture.isReady()) {
  53317. return false;
  53318. }
  53319. else {
  53320. needUVs = true;
  53321. this._defines.REFRACTION = true;
  53322. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  53323. if (this.linkRefractionWithTransparency) {
  53324. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  53325. }
  53326. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  53327. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  53328. if (this.refractionTexture.isPMREM) {
  53329. this._defines.USEPMREMREFRACTION = true;
  53330. }
  53331. }
  53332. }
  53333. }
  53334. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53335. if (!this.cameraColorGradingTexture.isReady()) {
  53336. return false;
  53337. }
  53338. else {
  53339. this._defines.CAMERACOLORGRADING = true;
  53340. }
  53341. }
  53342. }
  53343. // Effect
  53344. if (scene.clipPlane) {
  53345. this._defines.CLIPPLANE = true;
  53346. }
  53347. if (engine.getAlphaTesting()) {
  53348. this._defines.ALPHATEST = true;
  53349. }
  53350. if (this._shouldUseAlphaFromAlbedoTexture()) {
  53351. this._defines.ALPHAFROMALBEDO = true;
  53352. }
  53353. if (this.useEmissiveAsIllumination) {
  53354. this._defines.EMISSIVEASILLUMINATION = true;
  53355. }
  53356. if (this.linkEmissiveWithAlbedo) {
  53357. this._defines.LINKEMISSIVEWITHALBEDO = true;
  53358. }
  53359. if (this.useLogarithmicDepth) {
  53360. this._defines.LOGARITHMICDEPTH = true;
  53361. }
  53362. if (this.cameraContrast != 1) {
  53363. this._defines.CAMERACONTRAST = true;
  53364. }
  53365. if (this.cameraExposure != 1) {
  53366. this._defines.CAMERATONEMAP = true;
  53367. }
  53368. if (this.cameraColorCurves) {
  53369. this._defines.CAMERACOLORCURVES = true;
  53370. }
  53371. if (this.overloadedShadeIntensity != 1 ||
  53372. this.overloadedShadowIntensity != 1) {
  53373. this._defines.OVERLOADEDSHADOWVALUES = true;
  53374. }
  53375. if (this.overloadedMicroSurfaceIntensity > 0 ||
  53376. this.overloadedEmissiveIntensity > 0 ||
  53377. this.overloadedReflectivityIntensity > 0 ||
  53378. this.overloadedAlbedoIntensity > 0 ||
  53379. this.overloadedAmbientIntensity > 0 ||
  53380. this.overloadedReflectionIntensity > 0) {
  53381. this._defines.OVERLOADEDVALUES = true;
  53382. }
  53383. // Point size
  53384. if (this.pointsCloud || scene.forcePointsCloud) {
  53385. this._defines.POINTSIZE = true;
  53386. }
  53387. // Fog
  53388. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53389. this._defines.FOG = true;
  53390. }
  53391. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53392. // Fresnel
  53393. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  53394. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53395. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53396. this._defines.OPACITYFRESNEL = true;
  53397. }
  53398. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53399. this._defines.EMISSIVEFRESNEL = true;
  53400. }
  53401. needNormals = true;
  53402. this._defines.FRESNEL = true;
  53403. }
  53404. }
  53405. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  53406. this._defines.SPECULAROVERALPHA = true;
  53407. }
  53408. if (this.usePhysicalLightFalloff) {
  53409. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  53410. }
  53411. if (this.useRadianceOverAlpha) {
  53412. this._defines.RADIANCEOVERALPHA = true;
  53413. }
  53414. // Attribs
  53415. if (mesh) {
  53416. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53417. this._defines.NORMAL = true;
  53418. }
  53419. if (needUVs) {
  53420. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53421. this._defines.UV1 = true;
  53422. }
  53423. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53424. this._defines.UV2 = true;
  53425. }
  53426. }
  53427. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53428. this._defines.VERTEXCOLOR = true;
  53429. if (mesh.hasVertexAlpha) {
  53430. this._defines.VERTEXALPHA = true;
  53431. }
  53432. }
  53433. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53434. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  53435. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  53436. }
  53437. // Instances
  53438. if (useInstances) {
  53439. this._defines.INSTANCES = true;
  53440. }
  53441. }
  53442. // Get correct effect
  53443. if (!this._defines.isEqual(this._cachedDefines)) {
  53444. this._defines.cloneTo(this._cachedDefines);
  53445. scene.resetCachedMaterial();
  53446. // Fallbacks
  53447. var fallbacks = new BABYLON.EffectFallbacks();
  53448. if (this._defines.REFLECTION) {
  53449. fallbacks.addFallback(0, "REFLECTION");
  53450. }
  53451. if (this._defines.REFRACTION) {
  53452. fallbacks.addFallback(0, "REFRACTION");
  53453. }
  53454. if (this._defines.REFLECTIVITY) {
  53455. fallbacks.addFallback(0, "REFLECTIVITY");
  53456. }
  53457. if (this._defines.BUMP) {
  53458. fallbacks.addFallback(0, "BUMP");
  53459. }
  53460. if (this._defines.PARALLAX) {
  53461. fallbacks.addFallback(1, "PARALLAX");
  53462. }
  53463. if (this._defines.PARALLAXOCCLUSION) {
  53464. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  53465. }
  53466. if (this._defines.SPECULAROVERALPHA) {
  53467. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  53468. }
  53469. if (this._defines.FOG) {
  53470. fallbacks.addFallback(1, "FOG");
  53471. }
  53472. if (this._defines.POINTSIZE) {
  53473. fallbacks.addFallback(0, "POINTSIZE");
  53474. }
  53475. if (this._defines.LOGARITHMICDEPTH) {
  53476. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  53477. }
  53478. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  53479. if (this._defines.SPECULARTERM) {
  53480. fallbacks.addFallback(0, "SPECULARTERM");
  53481. }
  53482. if (this._defines.OPACITYFRESNEL) {
  53483. fallbacks.addFallback(1, "OPACITYFRESNEL");
  53484. }
  53485. if (this._defines.EMISSIVEFRESNEL) {
  53486. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  53487. }
  53488. if (this._defines.FRESNEL) {
  53489. fallbacks.addFallback(3, "FRESNEL");
  53490. }
  53491. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  53492. fallbacks.addCPUSkinningFallback(0, mesh);
  53493. }
  53494. //Attributes
  53495. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53496. if (this._defines.NORMAL) {
  53497. attribs.push(BABYLON.VertexBuffer.NormalKind);
  53498. }
  53499. if (this._defines.UV1) {
  53500. attribs.push(BABYLON.VertexBuffer.UVKind);
  53501. }
  53502. if (this._defines.UV2) {
  53503. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53504. }
  53505. if (this._defines.VERTEXCOLOR) {
  53506. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53507. }
  53508. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  53509. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  53510. // Legacy browser patch
  53511. var join = this._defines.toString();
  53512. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  53513. "vFogInfos", "vFogColor", "pointSize",
  53514. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  53515. "mBones",
  53516. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  53517. "depthValues",
  53518. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  53519. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  53520. "logarithmicDepthConstant",
  53521. "vSphericalX", "vSphericalY", "vSphericalZ",
  53522. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  53523. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  53524. "vMicrosurfaceTextureLods",
  53525. "vCameraInfos"
  53526. ];
  53527. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  53528. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  53529. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  53530. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  53531. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  53532. }
  53533. if (!this._effect.isReady()) {
  53534. return false;
  53535. }
  53536. this._renderId = scene.getRenderId();
  53537. this._wasPreviouslyReady = true;
  53538. if (mesh) {
  53539. if (!mesh._materialDefines) {
  53540. mesh._materialDefines = new PBRMaterialDefines();
  53541. }
  53542. this._defines.cloneTo(mesh._materialDefines);
  53543. }
  53544. return true;
  53545. };
  53546. PBRMaterial.prototype.unbind = function () {
  53547. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  53548. this._effect.setTexture("reflection2DSampler", null);
  53549. }
  53550. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  53551. this._effect.setTexture("refraction2DSampler", null);
  53552. }
  53553. _super.prototype.unbind.call(this);
  53554. };
  53555. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53556. this._effect.setMatrix("world", world);
  53557. };
  53558. PBRMaterial.prototype.bind = function (world, mesh) {
  53559. this._myScene = this.getScene();
  53560. // Matrices
  53561. this.bindOnlyWorldMatrix(world);
  53562. // Bones
  53563. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53564. if (this._myScene.getCachedMaterial() !== this) {
  53565. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  53566. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53567. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53568. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  53569. }
  53570. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53571. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  53572. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  53573. }
  53574. }
  53575. // Textures
  53576. if (this._myScene.texturesEnabled) {
  53577. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53578. this._effect.setTexture("albedoSampler", this.albedoTexture);
  53579. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  53580. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  53581. }
  53582. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53583. this._effect.setTexture("ambientSampler", this.ambientTexture);
  53584. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  53585. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  53586. }
  53587. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53588. this._effect.setTexture("opacitySampler", this.opacityTexture);
  53589. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  53590. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  53591. }
  53592. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53593. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  53594. if (this.reflectionTexture.isCube) {
  53595. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  53596. }
  53597. else {
  53598. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  53599. }
  53600. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  53601. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  53602. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  53603. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  53604. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  53605. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  53606. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  53607. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  53608. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  53609. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  53610. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  53611. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  53612. }
  53613. }
  53614. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53615. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  53616. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  53617. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  53618. }
  53619. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53620. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  53621. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  53622. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  53623. }
  53624. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53625. if (this.metallicTexture) {
  53626. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  53627. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  53628. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  53629. }
  53630. else if (this.reflectivityTexture) {
  53631. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  53632. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  53633. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  53634. }
  53635. }
  53636. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53637. this._effect.setTexture("bumpSampler", this.bumpTexture);
  53638. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  53639. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  53640. }
  53641. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53642. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  53643. var depth = 1.0;
  53644. if (this.refractionTexture.isCube) {
  53645. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  53646. }
  53647. else {
  53648. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  53649. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  53650. if (this.refractionTexture.depth) {
  53651. depth = this.refractionTexture.depth;
  53652. }
  53653. }
  53654. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  53655. }
  53656. if ((this.reflectionTexture || this.refractionTexture)) {
  53657. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  53658. }
  53659. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53660. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  53661. }
  53662. }
  53663. // Clip plane
  53664. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  53665. // Point size
  53666. if (this.pointsCloud) {
  53667. this._effect.setFloat("pointSize", this.pointSize);
  53668. }
  53669. // Colors
  53670. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  53671. // GAMMA CORRECTION.
  53672. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  53673. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  53674. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  53675. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  53676. // GAMMA CORRECTION.
  53677. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  53678. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  53679. // GAMMA CORRECTION.
  53680. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  53681. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  53682. }
  53683. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  53684. // GAMMA CORRECTION.
  53685. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  53686. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  53687. // Lights
  53688. if (this._myScene.lightsEnabled && !this.disableLighting) {
  53689. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  53690. }
  53691. // View
  53692. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  53693. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  53694. }
  53695. // Fog
  53696. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  53697. this._lightingInfos.x = this.directIntensity;
  53698. this._lightingInfos.y = this.emissiveIntensity;
  53699. this._lightingInfos.z = this.environmentIntensity;
  53700. this._lightingInfos.w = this.specularIntensity;
  53701. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  53702. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  53703. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  53704. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  53705. this._cameraInfos.x = this.cameraExposure;
  53706. this._cameraInfos.y = this.cameraContrast;
  53707. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  53708. if (this.cameraColorCurves) {
  53709. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  53710. }
  53711. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  53712. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  53713. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  53714. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  53715. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  53716. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  53717. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  53718. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  53719. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  53720. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  53721. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  53722. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  53723. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  53724. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  53725. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  53726. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  53727. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  53728. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  53729. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  53730. // Log. depth
  53731. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  53732. }
  53733. _super.prototype.bind.call(this, world, mesh);
  53734. this._myScene = null;
  53735. };
  53736. PBRMaterial.prototype.getAnimatables = function () {
  53737. var results = [];
  53738. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  53739. results.push(this.albedoTexture);
  53740. }
  53741. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  53742. results.push(this.ambientTexture);
  53743. }
  53744. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  53745. results.push(this.opacityTexture);
  53746. }
  53747. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  53748. results.push(this.reflectionTexture);
  53749. }
  53750. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  53751. results.push(this.emissiveTexture);
  53752. }
  53753. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  53754. results.push(this.metallicTexture);
  53755. }
  53756. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  53757. results.push(this.reflectivityTexture);
  53758. }
  53759. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  53760. results.push(this.bumpTexture);
  53761. }
  53762. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  53763. results.push(this.lightmapTexture);
  53764. }
  53765. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  53766. results.push(this.refractionTexture);
  53767. }
  53768. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  53769. results.push(this.cameraColorGradingTexture);
  53770. }
  53771. return results;
  53772. };
  53773. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53774. if (forceDisposeTextures) {
  53775. if (this.albedoTexture) {
  53776. this.albedoTexture.dispose();
  53777. }
  53778. if (this.ambientTexture) {
  53779. this.ambientTexture.dispose();
  53780. }
  53781. if (this.opacityTexture) {
  53782. this.opacityTexture.dispose();
  53783. }
  53784. if (this.reflectionTexture) {
  53785. this.reflectionTexture.dispose();
  53786. }
  53787. if (this.emissiveTexture) {
  53788. this.emissiveTexture.dispose();
  53789. }
  53790. if (this.metallicTexture) {
  53791. this.metallicTexture.dispose();
  53792. }
  53793. if (this.reflectivityTexture) {
  53794. this.reflectivityTexture.dispose();
  53795. }
  53796. if (this.bumpTexture) {
  53797. this.bumpTexture.dispose();
  53798. }
  53799. if (this.lightmapTexture) {
  53800. this.lightmapTexture.dispose();
  53801. }
  53802. if (this.refractionTexture) {
  53803. this.refractionTexture.dispose();
  53804. }
  53805. if (this.cameraColorGradingTexture) {
  53806. this.cameraColorGradingTexture.dispose();
  53807. }
  53808. }
  53809. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53810. };
  53811. PBRMaterial.prototype.clone = function (name) {
  53812. var _this = this;
  53813. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  53814. };
  53815. PBRMaterial.prototype.serialize = function () {
  53816. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53817. serializationObject.customType = "BABYLON.PBRMaterial";
  53818. return serializationObject;
  53819. };
  53820. // Statics
  53821. PBRMaterial.Parse = function (source, scene, rootUrl) {
  53822. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  53823. };
  53824. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  53825. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  53826. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  53827. PBRMaterial._scaledReflection = new BABYLON.Color3();
  53828. __decorate([
  53829. BABYLON.serialize()
  53830. ], PBRMaterial.prototype, "directIntensity", void 0);
  53831. __decorate([
  53832. BABYLON.serialize()
  53833. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  53834. __decorate([
  53835. BABYLON.serialize()
  53836. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  53837. __decorate([
  53838. BABYLON.serialize()
  53839. ], PBRMaterial.prototype, "specularIntensity", void 0);
  53840. __decorate([
  53841. BABYLON.serialize()
  53842. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  53843. __decorate([
  53844. BABYLON.serialize()
  53845. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  53846. __decorate([
  53847. BABYLON.serialize()
  53848. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  53849. __decorate([
  53850. BABYLON.serialize()
  53851. ], PBRMaterial.prototype, "cameraExposure", void 0);
  53852. __decorate([
  53853. BABYLON.serialize()
  53854. ], PBRMaterial.prototype, "cameraContrast", void 0);
  53855. __decorate([
  53856. BABYLON.serializeAsTexture()
  53857. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  53858. __decorate([
  53859. BABYLON.serializeAsColorCurves()
  53860. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  53861. __decorate([
  53862. BABYLON.serializeAsColor3()
  53863. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  53864. __decorate([
  53865. BABYLON.serialize()
  53866. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  53867. __decorate([
  53868. BABYLON.serializeAsColor3()
  53869. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  53870. __decorate([
  53871. BABYLON.serialize()
  53872. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  53873. __decorate([
  53874. BABYLON.serializeAsColor3()
  53875. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  53876. __decorate([
  53877. BABYLON.serialize()
  53878. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  53879. __decorate([
  53880. BABYLON.serializeAsColor3()
  53881. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  53882. __decorate([
  53883. BABYLON.serialize()
  53884. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  53885. __decorate([
  53886. BABYLON.serializeAsColor3()
  53887. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  53888. __decorate([
  53889. BABYLON.serialize()
  53890. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  53891. __decorate([
  53892. BABYLON.serialize()
  53893. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  53894. __decorate([
  53895. BABYLON.serialize()
  53896. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  53897. __decorate([
  53898. BABYLON.serializeAsTexture()
  53899. ], PBRMaterial.prototype, "albedoTexture", void 0);
  53900. __decorate([
  53901. BABYLON.serializeAsTexture()
  53902. ], PBRMaterial.prototype, "ambientTexture", void 0);
  53903. __decorate([
  53904. BABYLON.serialize()
  53905. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  53906. __decorate([
  53907. BABYLON.serializeAsTexture()
  53908. ], PBRMaterial.prototype, "opacityTexture", void 0);
  53909. __decorate([
  53910. BABYLON.serializeAsTexture()
  53911. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  53912. __decorate([
  53913. BABYLON.serializeAsTexture()
  53914. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  53915. __decorate([
  53916. BABYLON.serializeAsTexture()
  53917. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  53918. __decorate([
  53919. BABYLON.serializeAsTexture()
  53920. ], PBRMaterial.prototype, "metallicTexture", void 0);
  53921. __decorate([
  53922. BABYLON.serializeAsTexture()
  53923. ], PBRMaterial.prototype, "bumpTexture", void 0);
  53924. __decorate([
  53925. BABYLON.serializeAsTexture()
  53926. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  53927. __decorate([
  53928. BABYLON.serializeAsTexture()
  53929. ], PBRMaterial.prototype, "refractionTexture", void 0);
  53930. __decorate([
  53931. BABYLON.serializeAsColor3("ambient")
  53932. ], PBRMaterial.prototype, "ambientColor", void 0);
  53933. __decorate([
  53934. BABYLON.serializeAsColor3("albedo")
  53935. ], PBRMaterial.prototype, "albedoColor", void 0);
  53936. __decorate([
  53937. BABYLON.serializeAsColor3("reflectivity")
  53938. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  53939. __decorate([
  53940. BABYLON.serializeAsColor3("reflection")
  53941. ], PBRMaterial.prototype, "reflectionColor", void 0);
  53942. __decorate([
  53943. BABYLON.serializeAsColor3("emissive")
  53944. ], PBRMaterial.prototype, "emissiveColor", void 0);
  53945. __decorate([
  53946. BABYLON.serialize()
  53947. ], PBRMaterial.prototype, "microSurface", void 0);
  53948. __decorate([
  53949. BABYLON.serialize()
  53950. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  53951. __decorate([
  53952. BABYLON.serialize()
  53953. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  53954. __decorate([
  53955. BABYLON.serializeAsFresnelParameters()
  53956. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  53957. __decorate([
  53958. BABYLON.serializeAsFresnelParameters()
  53959. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  53960. __decorate([
  53961. BABYLON.serialize()
  53962. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  53963. __decorate([
  53964. BABYLON.serialize()
  53965. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  53966. __decorate([
  53967. BABYLON.serialize()
  53968. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  53969. __decorate([
  53970. BABYLON.serialize()
  53971. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  53972. __decorate([
  53973. BABYLON.serialize()
  53974. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  53975. __decorate([
  53976. BABYLON.serialize()
  53977. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  53978. __decorate([
  53979. BABYLON.serialize()
  53980. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  53981. __decorate([
  53982. BABYLON.serialize()
  53983. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  53984. __decorate([
  53985. BABYLON.serialize()
  53986. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  53987. __decorate([
  53988. BABYLON.serialize()
  53989. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  53990. __decorate([
  53991. BABYLON.serialize()
  53992. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  53993. __decorate([
  53994. BABYLON.serialize()
  53995. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  53996. __decorate([
  53997. BABYLON.serialize()
  53998. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  53999. __decorate([
  54000. BABYLON.serialize()
  54001. ], PBRMaterial.prototype, "useParallax", void 0);
  54002. __decorate([
  54003. BABYLON.serialize()
  54004. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54005. __decorate([
  54006. BABYLON.serialize()
  54007. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54008. __decorate([
  54009. BABYLON.serialize()
  54010. ], PBRMaterial.prototype, "disableLighting", void 0);
  54011. __decorate([
  54012. BABYLON.serialize()
  54013. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54014. __decorate([
  54015. BABYLON.serialize()
  54016. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54017. __decorate([
  54018. BABYLON.serialize()
  54019. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54020. __decorate([
  54021. BABYLON.serialize()
  54022. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54023. return PBRMaterial;
  54024. }(BABYLON.Material));
  54025. BABYLON.PBRMaterial = PBRMaterial;
  54026. })(BABYLON || (BABYLON = {}));
  54027. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54028. var BABYLON;
  54029. (function (BABYLON) {
  54030. var DebugLayer = (function () {
  54031. function DebugLayer(scene) {
  54032. this._scene = scene;
  54033. }
  54034. /** Creates the inspector window. */
  54035. DebugLayer.prototype._createInspector = function () {
  54036. new INSPECTOR.Inspector(this._scene);
  54037. };
  54038. DebugLayer.prototype.isVisible = function () {
  54039. return false;
  54040. };
  54041. DebugLayer.prototype.hide = function () {
  54042. console.warn('');
  54043. };
  54044. DebugLayer.prototype.show = function () {
  54045. if (typeof INSPECTOR == 'undefined') {
  54046. // Load inspector and add it to the DOM
  54047. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this));
  54048. }
  54049. else {
  54050. // Otherwise creates the inspector
  54051. this._createInspector();
  54052. }
  54053. };
  54054. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54055. return DebugLayer;
  54056. }());
  54057. BABYLON.DebugLayer = DebugLayer;
  54058. })(BABYLON || (BABYLON = {}));
  54059. //# sourceMappingURL=babylon.debugLayer.js.map
  54060. var BABYLON;
  54061. (function (BABYLON) {
  54062. var StandardRenderingPipeline = (function (_super) {
  54063. __extends(StandardRenderingPipeline, _super);
  54064. /**
  54065. * @constructor
  54066. * @param {string} name - The rendering pipeline name
  54067. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54068. * @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)
  54069. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54070. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54071. */
  54072. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54073. var _this = this;
  54074. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54075. _super.call(this, scene.getEngine(), name);
  54076. this.downSampleX4PostProcess = null;
  54077. this.brightPassPostProcess = null;
  54078. this.gaussianBlurHPostProcesses = [];
  54079. this.gaussianBlurVPostProcesses = [];
  54080. this.textureAdderPostProcess = null;
  54081. this.textureAdderFinalPostProcess = null;
  54082. this.lensFlarePostProcess = null;
  54083. this.lensFlareComposePostProcess = null;
  54084. this.depthOfFieldPostProcess = null;
  54085. // Values
  54086. this.brightThreshold = 1.0;
  54087. this.blurWidth = 2.0;
  54088. this.gaussianCoefficient = 0.25;
  54089. this.gaussianMean = 1.0;
  54090. this.gaussianStandardDeviation = 1.0;
  54091. this.exposure = 1.0;
  54092. this.lensTexture = null;
  54093. this.lensColorTexture = null;
  54094. this.lensFlareStrength = 20.0;
  54095. this.lensFlareGhostDispersal = 1.4;
  54096. this.lensFlareHaloWidth = 0.7;
  54097. this.lensFlareDistortionStrength = 16.0;
  54098. this.lensStarTexture = null;
  54099. this.lensFlareDirtTexture = null;
  54100. this.depthOfFieldDistance = 10.0;
  54101. // IAnimatable
  54102. this.animations = [];
  54103. this._depthRenderer = null;
  54104. // Getters and setters
  54105. this._depthOfFieldEnabled = true;
  54106. this._lensFlareEnabled = true;
  54107. // Initialize
  54108. this._scene = scene;
  54109. // Create pass post-processe
  54110. if (!originalPostProcess) {
  54111. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  54112. }
  54113. else {
  54114. this.originalPostProcess = originalPostProcess;
  54115. }
  54116. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54117. // Create down sample X4 post-process
  54118. this._createDownSampleX4PostProcess(scene, ratio / 2);
  54119. // Create bright pass post-process
  54120. this._createBrightPassPostProcess(scene, ratio / 2);
  54121. // Create gaussian blur post-processes (down sampling blurs)
  54122. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  54123. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  54124. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  54125. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  54126. // Create texture adder post-process
  54127. this._createTextureAdderPostProcess(scene, ratio);
  54128. // Create depth-of-field source post-process
  54129. 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);
  54130. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54131. // Create lens flare post-process
  54132. this._createLensFlarePostProcess(scene, ratio);
  54133. // Create gaussian blur used by depth-of-field
  54134. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  54135. // Create depth-of-field post-process
  54136. this._createDepthOfFieldPostProcess(scene, ratio);
  54137. // Finish
  54138. scene.postProcessRenderPipelineManager.addPipeline(this);
  54139. if (cameras !== null) {
  54140. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54141. }
  54142. // Deactivate
  54143. this.LensFlareEnabled = false;
  54144. this.DepthOfFieldEnabled = false;
  54145. }
  54146. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54147. get: function () {
  54148. return this._depthOfFieldEnabled;
  54149. },
  54150. set: function (enabled) {
  54151. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  54152. if (enabled && !this._depthOfFieldEnabled) {
  54153. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54154. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54155. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54156. this._depthRenderer = this._scene.enableDepthRenderer();
  54157. }
  54158. else if (!enabled && this._depthOfFieldEnabled) {
  54159. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54160. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54161. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54162. }
  54163. this._depthOfFieldEnabled = enabled;
  54164. },
  54165. enumerable: true,
  54166. configurable: true
  54167. });
  54168. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54169. get: function () {
  54170. return this._lensFlareEnabled;
  54171. },
  54172. set: function (enabled) {
  54173. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  54174. if (enabled && !this._lensFlareEnabled) {
  54175. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54176. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54177. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54178. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54179. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54180. }
  54181. else if (!enabled && this._lensFlareEnabled) {
  54182. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54183. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54184. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54185. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54186. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54187. }
  54188. this._lensFlareEnabled = enabled;
  54189. },
  54190. enumerable: true,
  54191. configurable: true
  54192. });
  54193. // Down Sample X4 Post-Processs
  54194. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54195. var _this = this;
  54196. var downSampleX4Offsets = new Array(32);
  54197. 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);
  54198. this.downSampleX4PostProcess.onApply = function (effect) {
  54199. var id = 0;
  54200. for (var i = -2; i < 2; i++) {
  54201. for (var j = -2; j < 2; j++) {
  54202. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54203. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54204. id += 2;
  54205. }
  54206. }
  54207. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54208. };
  54209. // Add to pipeline
  54210. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54211. };
  54212. // Brightpass Post-Process
  54213. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54214. var _this = this;
  54215. var brightOffsets = new Array(8);
  54216. 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);
  54217. this.brightPassPostProcess.onApply = function (effect) {
  54218. var sU = (1.0 / _this.brightPassPostProcess.width);
  54219. var sV = (1.0 / _this.brightPassPostProcess.height);
  54220. brightOffsets[0] = -0.5 * sU;
  54221. brightOffsets[1] = 0.5 * sV;
  54222. brightOffsets[2] = 0.5 * sU;
  54223. brightOffsets[3] = 0.5 * sV;
  54224. brightOffsets[4] = -0.5 * sU;
  54225. brightOffsets[5] = -0.5 * sV;
  54226. brightOffsets[6] = 0.5 * sU;
  54227. brightOffsets[7] = -0.5 * sV;
  54228. effect.setArray2("dsOffsets", brightOffsets);
  54229. effect.setFloat("brightThreshold", _this.brightThreshold);
  54230. };
  54231. // Add to pipeline
  54232. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54233. };
  54234. // Create gaussian blur H&V post-processes
  54235. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  54236. var _this = this;
  54237. var blurOffsets = new Array(9);
  54238. var blurWeights = new Array(9);
  54239. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  54240. var callback = function (height) {
  54241. return function (effect) {
  54242. // Weights
  54243. var x = 0.0;
  54244. for (var i = 0; i < 9; i++) {
  54245. x = (i - 4.0) / 4.0;
  54246. blurWeights[i] =
  54247. _this.gaussianCoefficient
  54248. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  54249. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  54250. }
  54251. var lastOutputDimensions = {
  54252. width: scene.getEngine().getRenderWidth(),
  54253. height: scene.getEngine().getRenderHeight()
  54254. };
  54255. for (var i = 0; i < 9; i++) {
  54256. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54257. blurOffsets[i] = value;
  54258. }
  54259. effect.setArray("blurOffsets", blurOffsets);
  54260. effect.setArray("blurWeights", blurWeights);
  54261. effect.setFloat("blurWidth", _this.blurWidth);
  54262. };
  54263. };
  54264. // Create horizontal gaussian blur post-processes
  54265. 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);
  54266. gaussianBlurHPostProcess.onApply = callback(false);
  54267. // Create vertical gaussian blur post-process
  54268. 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);
  54269. gaussianBlurVPostProcess.onApply = callback(true);
  54270. // Add to pipeline
  54271. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  54272. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  54273. // Finish
  54274. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  54275. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  54276. };
  54277. // Create texture adder post-process
  54278. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54279. var _this = this;
  54280. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  54281. 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);
  54282. this.textureAdderPostProcess.onApply = function (effect) {
  54283. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  54284. effect.setTexture("lensSampler", _this.lensTexture);
  54285. effect.setFloat("exposure", _this.exposure);
  54286. };
  54287. // Add to pipeline
  54288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54289. };
  54290. // Create lens flare post-process
  54291. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54292. var _this = this;
  54293. 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);
  54294. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  54295. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  54296. 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);
  54297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  54298. var resolution = new BABYLON.Vector2(0, 0);
  54299. // Lens flare
  54300. this.lensFlarePostProcess.onApply = function (effect) {
  54301. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  54302. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54303. effect.setFloat("strength", _this.lensFlareStrength);
  54304. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54305. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54306. // Shift
  54307. resolution.x = _this.lensFlarePostProcess.width;
  54308. resolution.y = _this.lensFlarePostProcess.height;
  54309. effect.setVector2("resolution", resolution);
  54310. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54311. };
  54312. // Compose
  54313. 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);
  54314. 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);
  54315. this.lensFlareComposePostProcess.onApply = function (effect) {
  54316. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54317. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54318. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54319. // Lens start rotation matrix
  54320. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54321. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54322. 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));
  54323. camRot *= 4.0;
  54324. 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);
  54325. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54326. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54327. };
  54328. };
  54329. // Create depth-of-field post-process
  54330. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54331. var _this = this;
  54332. 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);
  54333. this.depthOfFieldPostProcess.onApply = function (effect) {
  54334. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54335. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  54336. effect.setFloat("distance", _this.depthOfFieldDistance);
  54337. };
  54338. // Add to pipeline
  54339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54340. };
  54341. // Dispose
  54342. StandardRenderingPipeline.prototype.dispose = function () {
  54343. for (var i = 0; i < this._scene.cameras.length; i++) {
  54344. var camera = this._scene.cameras[i];
  54345. this.originalPostProcess.dispose(camera);
  54346. this.downSampleX4PostProcess.dispose(camera);
  54347. this.brightPassPostProcess.dispose(camera);
  54348. this.textureAdderPostProcess.dispose(camera);
  54349. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  54350. this.gaussianBlurHPostProcesses[j].dispose(camera);
  54351. }
  54352. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  54353. this.gaussianBlurVPostProcesses[j].dispose(camera);
  54354. }
  54355. this.textureAdderFinalPostProcess.dispose(camera);
  54356. this.lensFlarePostProcess.dispose(camera);
  54357. this.lensFlareComposePostProcess.dispose(camera);
  54358. this.depthOfFieldPostProcess.dispose(camera);
  54359. }
  54360. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54361. _super.prototype.dispose.call(this);
  54362. };
  54363. return StandardRenderingPipeline;
  54364. }(BABYLON.PostProcessRenderPipeline));
  54365. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54366. })(BABYLON || (BABYLON = {}));
  54367. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54368. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || 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}"};
  54369. 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"};
  54370. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return-n<=r&&r<=n},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,e=t.g+(i.g-t.g)*r,s=t.b+(i.b-t.b)*r;return new n(o,e,s)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,e)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n((-this.x),(-this.y))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>r.y?r.y:e,e=e<i.y?i.y:e,new n(o,e)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r;return new n(o,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),e=o<0?-1:1,s=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*e,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var e=r.subtract(i),s=Math.max(0,Math.min(1,n.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return n.Distance(t,h)},n}();t.Vector2=o;var e=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=r*s,t.y=-o*s,t.z=n*e,t.w=i*e,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var e=n.Dot(t,r)-o,s=n.Dot(i,r)-o,h=e/(e-s);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.Forward=function(){return new n(0,0,1)},n.Right=function(){return new n(1,0,0)},n.Left=function(){return new n((-1),0,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/s,n.y=o/s,n.z=e/s},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var e=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],s=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=e/a,o.y=s/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];n.x=r,n.y=o,n.z=e},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*e+(2*t.z-5*i.z+4*r.z-o.z)*s+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>r.y?r.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>r.z?r.z:s,s=s<i.z?i.z:s,new n(o,e,s)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r,s=t.z+(i.z-t.z)*r;return new n(o,e,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=n._viewportMatrixCache?n._viewportMatrixCache:n._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=n._matrixCache?n._matrixCache:n._matrixCache=new u;return i.multiplyToRef(r,y),y.multiplyToRef(m,y),n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,e,s){var h=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},n.Unproject=function(t,r,o,e,s,h){var a=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new n(t.x/r*2-1,(-(t.y/o*2-1)),t.z),y=n.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,e,s){var h=r.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),n.CrossToRef(h,T,g),g.normalize(),n.Dot(a,g)<0&&(v=1),R=n.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,n.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),n.CrossToRef(_,T,A),A.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(T,g)<0&&(v=1),R=n.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,n.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,T,g),g.normalize(),n.Dot(g,m)<0&&(v=1),R=n.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},n}();t.Vector3=e;var s=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},n.prototype.getClassName=function(){return\"Vector4\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z),(-this.w))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return n*n+r*r+o*o+e*e},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,n){return new t(this.width*i,this.height*n)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,e=i.height+(n.height-i.height)*r;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n=this.z,r=this.x,o=this.y,e=this.w,s=e*e,h=n*n,a=r*r,u=o*o,m=o*n-r*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(r*o+n*e),-h-a+u+s),t.x=Math.asin(-2*(n*o-r*e)),t.y=Math.atan2(2*(n*r+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],e=r[4],s=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(s-m)*n,i.z=(h-e)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(e+h)/n,i.z=(s+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(s-m)/n,i.x=(e+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-e)/n,i.x=(s+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){return t.RotationAxisToRef(i,n,new t)},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(i/2);return t.normalize(),n.w=Math.cos(i/2),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),e=.5*(n-t),s=.5*i;r.x=Math.cos(e)*Math.sin(s),r.y=Math.sin(e)*Math.sin(s),r.z=Math.sin(o)*Math.cos(s),r.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,n,r){var o=t.Identity();return t.SlerpToRef(i,n,r,o),o},t.SlerpToRef=function(t,i,n,r){var o,e,s=n,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}r.x=e*t.x+o*i.x,r.y=e*t.y+o*i.y,r.z=e*t.z+o*i.z,r.w=e*t.w+o*i.w},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*e)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;n<16;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+n*_+r*M+o*A),F=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,q=s*y-h*m,D=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*R)*b,t.m[13]=(i*v-n*g+r*R)*b,t.m[2]=(n*F-r*L+o*C)*b,t.m[6]=-(i*F-r*P+o*Z)*b,t.m[10]=(i*L-n*P+o*S)*b,t.m[14]=-(i*C-n*Z+r*S)*b,t.m[3]=-(n*I-r*H+o*q)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*H-n*D+o*N)*b,t.m[15]=(i*q-n*V+r*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this;\n},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;n<16;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],b=t.m[8],F=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*T+e*b+s*P,i[n+1]=r*d+o*_+e*F+s*Z,i[n+2]=r*g+o*M+e*L+s*S,i[n+3]=r*R+o*A+e*C+s*I,i[n+4]=h*v+a*T+u*b+m*P,i[n+5]=h*d+a*_+u*F+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*R+a*A+u*C+m*I,i[n+8]=y*v+c*T+p*b+f*P,i[n+9]=y*d+c*_+p*F+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*R+c*A+p*C+f*I,i[n+12]=x*v+l*T+z*b+w*P,i[n+13]=x*d+l*_+z*F+w*Z,i[n+14]=x*g+l*M+z*L+w*S,i[n+15]=x*R+l*A+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return n.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z?(r.x=0,r.y=0,r.z=0,r.w=1,!1):(t.FromValuesToRef(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1,M.Matrix[0]),a.FromRotationMatrixToRef(M.Matrix[0],r),!0)},t.prototype.getRotationMatrix=function(){var i=t.Identity();return this.getRotationMatrixToRef(i),i},t.prototype.getRotationMatrixToRef=function(i){var n=this.m,r=n[0]*n[1]*n[2]*n[3]<0?-1:1,o=n[4]*n[5]*n[6]*n[7]<0?-1:1,e=n[8]*n[9]*n[10]*n[11]<0?-1:1,s=r*Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),h=o*Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),a=e*Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]);t.FromValuesToRef(n[0]/s,n[1]/s,n[2]/s,0,n[4]/h,n[5]/h,n[6]/h,0,n[8]/a,n[9]/a,n[10]/a,0,0,0,0,1,i)},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;r<16;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;o<16;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=n,l.m[3]=r,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},t.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return n.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),n.m[0]=t.x*t.x*e+o,n.m[1]=t.x*t.y*e-t.z*r,n.m[2]=t.x*t.z*e+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*e+t.z*r,n.m[5]=t.y*t.y*e+o,n.m[6]=t.y*t.z*e-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*e-t.y*r,n.m[9]=t.z*t.y*e+t.x*r,n.m[10]=t.z*t.z*e+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-r)+n.m[e]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.LookAtRH=function(i,n,r){var o=t.Zero();return t.LookAtRHToRef(i,n,r,o),o},t.LookAtRHToRef=function(i,n,r,o){i.subtractToRef(n,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var e=t.Zero();return t.OrthoLHToRef(i,n,r,o,e),e},t.OrthoLHToRef=function(i,n,r,o,e){var s=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-n),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(e-o),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(r+n)/(n-r),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,n,r,o,e,s,h){t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,n,r,o){var e=t.Zero();return e.m[0]=2*r/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*r/n,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(r-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=r*o/(r-o),e},t.PerspectiveFovLH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,e),e},t.PerspectiveFovLHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(n*r)/(r-n)},t.PerspectiveFovRH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,n,r,o,e),e},t.PerspectiveFovRHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(n-r),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.PerspectiveFovWebVRToRef=function(t,i,n,r,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);r.m[0]=u,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=m,r.m[6]=r.m[7]=0,r.m[8]=(h-a)*u*.5,r.m[9]=-((e-s)*m*.5),r.m[10]=-n/(i-n),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=i*n/(i-n)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t.FromXYZAxesToRef=function(t,i,n,r){r.m[0]=t.x,r.m[1]=t.y,r.m[2]=t.z,r.m[3]=0,r.m[4]=i.x,r.m[5]=i.y,r.m[6]=i.z,r.m[7]=0,r.m[8]=n.x,r.m[9]=n.y,r.m[10]=n.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.FromQuaternionToRef=function(t,i){var n=t.x*t.x,r=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(r+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+n),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(r+n),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return n<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;r<6;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var e=1-3*r+3*i,s=3*r-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,s=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-n.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-n.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var e=(r+1)%this._points.length,s=this._points[r],h=this._points[e],a=h.subtract(s),u=a.length()+n;if(i>=n&&i<=u){var m=a.normalize(),y=i-n;return new o(s.x+m.x*y,s.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var s,h=r.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(r.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(r,a)}else s=e.Cross(r,o),e.CrossToRef(s,r,s);return s.normalize(),s},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)r.push(o[e].subtract(o[0]).add(n));var s=new t(r);return s},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  54371. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54372. module.exports = BABYLON;
  54373. };